Completed
Branch master (16095c)
by
unknown
09:17 queued 04:49
created
modules/events_archive/EventsArchiveIframe.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -21,62 +21,62 @@
 block discarded – undo
21 21
  */
22 22
 class EventsArchiveIframe extends Iframe
23 23
 {
24
-    /**
25
-     * EventsArchiveIframe constructor.
26
-     *
27
-     * @param EED_Events_Archive $EED_Events_Archive
28
-     * @throws EE_Error
29
-     * @throws ReflectionException
30
-     */
31
-    public function __construct($EED_Events_Archive)
32
-    {
33
-        /** @var CurrentPage $current_page */
34
-        $current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
35
-        $current_page->setEspressoPage(true);
36
-        add_filter('FHEE__EED_Events_Archive__event_list_iframe', '__return_true');
37
-        $EED_Events_Archive->event_list();
38
-        /** @var EspressoEvents $event_list */
39
-        $event_list = EE_Registry::instance()->create('EventEspresso\core\domain\entities\shortcodes\EspressoEvents');
40
-        $shortcode_content = $event_list->processShortcode();
41
-        if (empty($shortcode_content)) {
42
-            return;
43
-        }
44
-        parent::__construct(
45
-            esc_html__('Event List', 'event_espresso'),
46
-            $shortcode_content
47
-        );
48
-        $this->addStylesheets(
49
-            apply_filters(
50
-                'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
51
-                [
52
-                    'espresso_default' => is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
53
-                        ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION
54
-                        : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
55
-                ],
56
-                $this
57
-            )
58
-        );
59
-        $this->addScripts(
60
-            apply_filters(
61
-                'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
62
-                [
63
-                    'gmap_api' => sprintf(
64
-                        'https://maps.googleapis.com/maps/api/js?key=%s',
65
-                        apply_filters(
66
-                            'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
67
-                            EE_Registry::instance()->CFG->map_settings->google_map_api_key
68
-                        )
69
-                    ),
70
-                    'ee_gmap'  => EE_HELPERS_ASSETS . 'ee_gmap.js?ver=1.0',
71
-                ],
72
-                $this
73
-            )
74
-        );
75
-        $this->addLocalizedVars(
76
-            [
77
-                'ee_gmap' => EEH_Maps::$gmap_vars,
78
-            ],
79
-            'ee_gmap_vars'
80
-        );
81
-    }
24
+	/**
25
+	 * EventsArchiveIframe constructor.
26
+	 *
27
+	 * @param EED_Events_Archive $EED_Events_Archive
28
+	 * @throws EE_Error
29
+	 * @throws ReflectionException
30
+	 */
31
+	public function __construct($EED_Events_Archive)
32
+	{
33
+		/** @var CurrentPage $current_page */
34
+		$current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
35
+		$current_page->setEspressoPage(true);
36
+		add_filter('FHEE__EED_Events_Archive__event_list_iframe', '__return_true');
37
+		$EED_Events_Archive->event_list();
38
+		/** @var EspressoEvents $event_list */
39
+		$event_list = EE_Registry::instance()->create('EventEspresso\core\domain\entities\shortcodes\EspressoEvents');
40
+		$shortcode_content = $event_list->processShortcode();
41
+		if (empty($shortcode_content)) {
42
+			return;
43
+		}
44
+		parent::__construct(
45
+			esc_html__('Event List', 'event_espresso'),
46
+			$shortcode_content
47
+		);
48
+		$this->addStylesheets(
49
+			apply_filters(
50
+				'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
51
+				[
52
+					'espresso_default' => is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
53
+						? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION
54
+						: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
55
+				],
56
+				$this
57
+			)
58
+		);
59
+		$this->addScripts(
60
+			apply_filters(
61
+				'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
62
+				[
63
+					'gmap_api' => sprintf(
64
+						'https://maps.googleapis.com/maps/api/js?key=%s',
65
+						apply_filters(
66
+							'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
67
+							EE_Registry::instance()->CFG->map_settings->google_map_api_key
68
+						)
69
+					),
70
+					'ee_gmap'  => EE_HELPERS_ASSETS . 'ee_gmap.js?ver=1.0',
71
+				],
72
+				$this
73
+			)
74
+		);
75
+		$this->addLocalizedVars(
76
+			[
77
+				'ee_gmap' => EEH_Maps::$gmap_vars,
78
+			],
79
+			'ee_gmap_vars'
80
+		);
81
+	}
82 82
 }
Please login to merge, or discard this patch.
modules/batch/EED_Batch.module.php 2 patches
Indentation   +434 added lines, -434 removed lines patch added patch discarded remove patch
@@ -29,438 +29,438 @@
 block discarded – undo
29 29
  */
30 30
 class EED_Batch extends EED_Module
31 31
 {
32
-    public const PAGE_SLUG = 'espresso_batch';
33
-
34
-    /**
35
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
36
-     * processes data only
37
-     */
38
-    const batch_job = 'job';
39
-
40
-    /**
41
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
42
-     * produces a file for download
43
-     */
44
-    const batch_file_job = 'file';
45
-
46
-    /**
47
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
48
-     * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
49
-     * at all
50
-     */
51
-    const batch_not_job = 'none';
52
-
53
-    /**
54
-     *
55
-     * @var string 'file', or 'job', or false to indicate its not a batch request at all
56
-     */
57
-    protected $_batch_request_type = '';
58
-
59
-    /**
60
-     * Because we want to use the response in both the localized JS and in the body
61
-     * we need to make this response available between method calls
62
-     *
63
-     * @var JobStepResponse|null
64
-     */
65
-    protected $_job_step_response = null;
66
-
67
-    /**
68
-     * @var LoaderInterface|null
69
-     */
70
-    protected $loader = null;
71
-
72
-
73
-    /**
74
-     * Gets the batch instance
75
-     *
76
-     * @return  EED_Module|EED_Batch
77
-     * @throws EE_Error
78
-     * @throws ReflectionException
79
-     */
80
-    public static function instance(): EED_Batch
81
-    {
82
-        return parent::get_instance(__CLASS__);
83
-    }
84
-
85
-
86
-    /**
87
-     * Sets hooks to enable batch jobs on the frontend. Disabled by default
88
-     * because it's an attack vector and there are currently no implementations
89
-     *
90
-     * @throws EE_Error
91
-     * @throws ReflectionException
92
-     */
93
-    public static function set_hooks()
94
-    {
95
-        // because this is a possible attack vector, let's have this disabled until
96
-        // we at least have a real use for it on the frontend
97
-        if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
98
-            add_action('wp_enqueue_scripts', [self::instance(), 'enqueue_scripts']);
99
-            add_filter('template_include', [self::instance(), 'override_template'], 99);
100
-        }
101
-    }
102
-
103
-
104
-    /**
105
-     * Initializes some hooks for the admin in order to run batch jobs
106
-     *
107
-     * @throws EE_Error
108
-     * @throws ReflectionException
109
-     */
110
-    public static function set_hooks_admin()
111
-    {
112
-        add_action('admin_menu', [self::instance(), 'register_admin_pages']);
113
-        add_action('admin_enqueue_scripts', [self::instance(), 'enqueue_scripts']);
114
-
115
-        // ajax
116
-        add_action('wp_ajax_espresso_batch_continue', [self::instance(), 'continueBatchJob']);
117
-        add_action('wp_ajax_espresso_batch_advance', [self::instance(), 'advanceBatchJob']);
118
-        add_action('wp_ajax_espresso_batch_cleanup', [self::instance(), 'cleanupBatchJob']);
119
-        add_action('wp_ajax_nopriv_espresso_batch_continue', [self::instance(), 'continueBatchJob']);
120
-        add_action('wp_ajax_nopriv_espresso_batch_advance', [self::instance(), 'advanceBatchJob']);
121
-        add_action('wp_ajax_nopriv_espresso_batch_cleanup', [self::instance(), 'cleanupBatchJob']);
122
-    }
123
-
124
-
125
-    /**
126
-     * @return LoaderInterface
127
-     * @throws InvalidArgumentException
128
-     * @throws InvalidDataTypeException
129
-     * @throws InvalidInterfaceException
130
-     * @since 4.9.80.p
131
-     */
132
-    protected function getLoader(): LoaderInterface
133
-    {
134
-        if (! $this->loader instanceof LoaderInterface) {
135
-            $this->loader = LoaderFactory::getLoader();
136
-        }
137
-        return $this->loader;
138
-    }
139
-
140
-
141
-    /**
142
-     * Enqueues batch scripts on the frontend or admin, and creates a job
143
-     */
144
-    public function enqueue_scripts()
145
-    {
146
-        $request = EED_Batch::getRequest();
147
-        if (
148
-            $request->getRequestParam(EED_Batch::PAGE_SLUG)
149
-            || $request->getRequestParam('page') === EED_Batch::PAGE_SLUG
150
-        ) {
151
-            if (
152
-                ! $request->requestParamIsSet('default_nonce')
153
-                || ! wp_verify_nonce($request->getRequestParam('default_nonce'), 'default_nonce')
154
-            ) {
155
-                wp_die(
156
-                    esc_html__(
157
-                        'The link you clicked to start the batch job has expired. Please go back and refresh the previous page.',
158
-                        'event_espresso'
159
-                    )
160
-                );
161
-            }
162
-            switch ($this->batch_request_type()) {
163
-                case self::batch_job:
164
-                    $this->enqueue_scripts_styles_batch_create();
165
-                    break;
166
-                case self::batch_file_job:
167
-                    $this->enqueue_scripts_styles_batch_file_create();
168
-                    break;
169
-            }
170
-        }
171
-    }
172
-
173
-
174
-    /**
175
-     * Create a batch job, enqueues a script to run it, and localizes some data for it
176
-     */
177
-    public function enqueue_scripts_styles_batch_create()
178
-    {
179
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
180
-        wp_enqueue_script(
181
-            'batch_runner_init',
182
-            BATCH_URL . 'assets/batch_runner_init.js',
183
-            ['batch_runner'],
184
-            date('Y-m-d-H:i', time()),
185
-            true
186
-        );
187
-        wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
188
-        wp_localize_script('batch_runner_init', 'eei18n', EE_Registry::$i18n_js_strings);
189
-
190
-        $return_url = EED_Batch::getRequest()->getRequestParam('return_url', '', DataType::URL);
191
-        if ($return_url) {
192
-            wp_localize_script(
193
-                'batch_runner_init',
194
-                'ee_job_i18n',
195
-                [
196
-                    'return_url'                => $return_url,
197
-                    'auto_redirect_on_complete' => EED_Batch::getRequest()->getRequestParam(
198
-                        'auto_redirect_on_complete'
199
-                    ),
200
-                    'user_message'              => EED_Batch::getRequest()->getRequestParam('assessment_notice')
201
-                        ?: EED_Batch::getRequest()->getRequestParam('job_start_notice'),
202
-                ]
203
-            );
204
-        }
205
-    }
206
-
207
-
208
-    /**
209
-     * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
210
-     */
211
-    public function enqueue_scripts_styles_batch_file_create()
212
-    {
213
-        // creates a job based on the request variable
214
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
215
-        wp_enqueue_script(
216
-            'batch_file_runner_init',
217
-            BATCH_URL . 'assets/batch_file_runner_init.js',
218
-            ['batch_runner'],
219
-            date('Y-m-d-H:i', time()),
220
-            true
221
-        );
222
-        wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
223
-        wp_localize_script('batch_file_runner_init', 'eei18n', EE_Registry::$i18n_js_strings);
224
-
225
-        $return_url = EED_Batch::getRequest()->getRequestParam('return_url', '', DataType::URL);
226
-        if ($return_url) {
227
-            wp_localize_script(
228
-                'batch_file_runner_init',
229
-                'ee_job_i18n',
230
-                ['return_url' => $return_url]
231
-            );
232
-        }
233
-    }
234
-
235
-
236
-    /**
237
-     * Enqueues scripts and styles common to any batch job, and creates
238
-     * a job from the request data, and stores the response in the
239
-     * $this->_job_step_response property
240
-     *
241
-     * @return JobStepResponse
242
-     */
243
-    protected function _enqueue_batch_job_scripts_and_styles_and_start_job(): JobStepResponse
244
-    {
245
-        // just copy the bits of EE admin's eei18n that we need in the JS
246
-        EE_Registry::$i18n_js_strings['batchJobError'] = __(
247
-            'An error occurred and the job has been stopped. Please refresh the page to try again.',
248
-            'event_espresso'
249
-        );
250
-        EE_Registry::$i18n_js_strings['is_admin']      = is_admin();
251
-        wp_enqueue_style(
252
-            EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN,
253
-            EE_ADMIN_URL . 'assets/ee-admin-page.css',
254
-            ['espresso_admin_base'],
255
-            EVENT_ESPRESSO_VERSION
256
-        );
257
-        wp_enqueue_style(
258
-            'batch_runner',
259
-            BATCH_URL . 'assets/batch_runner.css',
260
-            [EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
261
-            date('Y-m-d-H:i', time())
262
-        );
263
-        wp_register_script(
264
-            'progress_bar',
265
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
266
-            ['jquery'],
267
-            date('Y-m-d-H:i', time()),
268
-            true
269
-        );
270
-        wp_enqueue_style(
271
-            'progress_bar',
272
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
273
-            [],
274
-            date('Y-m-d-H:i', time())
275
-        );
276
-        wp_enqueue_script(
277
-            'batch_runner',
278
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
279
-            ['progress_bar', CoreAssetManager::JS_HANDLE_CORE],
280
-            date('Y-m-d-H:i', time()),
281
-            true
282
-        );
283
-        /** @var BatchRequestProcessor $batch_runner */
284
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
285
-        // eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
286
-        // remember the response for later. We need it to display the page body
287
-        $this->_job_step_response = $batch_runner->createJob();
288
-        return $this->_job_step_response;
289
-    }
290
-
291
-
292
-    /**
293
-     * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
294
-     *
295
-     * @param string $template
296
-     * @return string
297
-     */
298
-    public function override_template(string $template): string
299
-    {
300
-        $request = EED_Batch::getRequest();
301
-        if ($request->requestParamIsSet('batch') && $request->requestParamIsSet(EED_Batch::PAGE_SLUG)) {
302
-            return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.php';
303
-        }
304
-        return $template;
305
-    }
306
-
307
-
308
-    /**
309
-     * Adds an admin page which doesn't appear in the admin menu
310
-     *
311
-     * @throws EE_Error
312
-     * @throws ReflectionException
313
-     */
314
-    public function register_admin_pages()
315
-    {
316
-        add_submenu_page(
317
-            '',
318
-            // parent slug. we don't want this to actually appear in the menu
319
-            esc_html__('Batch Job', 'event_espresso'),
320
-            // page title
321
-            'n/a',
322
-            // menu title
323
-            'read',
324
-            // we want this page to actually be accessible to anyone,
325
-            EED_Batch::PAGE_SLUG,
326
-            // menu slug
327
-            [self::instance(), 'show_admin_page']
328
-        );
329
-    }
330
-
331
-
332
-    /**
333
-     * Renders the admin page, after most of the work was already done during enqueuing scripts
334
-     * of creating the job and localizing some data
335
-     */
336
-    public function show_admin_page()
337
-    {
338
-        echo EEH_Template::locate_template(
339
-            EE_MODULES . 'batch/templates/batch_wrapper.template.php',
340
-            [
341
-                'batch_request_type'        => $this->batch_request_type(),
342
-                'auto_redirect_on_complete' => EED_Batch::getRequest()->getRequestParam('auto_redirect_on_complete'),
343
-                'user_message'              => EED_Batch::getRequest()->getRequestParam('assessment_notice')
344
-                    ?: EED_Batch::getRequest()->getRequestParam('job_start_notice'),
345
-            ]
346
-        );
347
-    }
348
-
349
-
350
-    private function runBatchRunnerJob(string $job)
351
-    {
352
-        $job_id = EED_Batch::getRequest()->getRequestParam('job_id');
353
-        /** @var BatchRequestProcessor $batch_runner */
354
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
355
-        $job_response = $batch_runner->{$job}($job_id);
356
-        $this->_return_json($job_response->to_array());
357
-    }
358
-
359
-
360
-    /**
361
-     * Receives ajax calls for continuing a job
362
-     */
363
-    public function continueBatchJob()
364
-    {
365
-        $this->runBatchRunnerJob('continueJob');
366
-    }
367
-
368
-
369
-    /**
370
-     * Receives ajax calls for continuing a job
371
-     */
372
-    public function advanceBatchJob()
373
-    {
374
-        $this->runBatchRunnerJob('advanceJob');
375
-    }
376
-
377
-
378
-    /**
379
-     * Receives the ajax call to cleanup a job
380
-     *
381
-     * @return void
382
-     */
383
-    public function cleanupBatchJob()
384
-    {
385
-        $this->runBatchRunnerJob('cleanupJob');
386
-    }
387
-
388
-
389
-    /**
390
-     * Returns a json response
391
-     *
392
-     * @param array $data The data we want to send echo via in the JSON response's "data" element
393
-     *
394
-     * The returned json object is created from an array in the following format:
395
-     * array(
396
-     *    'notices' => '', // - contains any EE_Error formatted notices
397
-     *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
398
-     *    We're also going to include the template args with every package (so js can pick out any specific template
399
-     *    args that might be included in here)
400
-     *    'isEEajax' => true,//indicates this is a response from EE
401
-     * )
402
-     */
403
-    protected function _return_json(array $data)
404
-    {
405
-        $json = [
406
-            'data'     => $data,
407
-            'isEEajax' => true,
408
-            // special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
409
-        ];
410
-
411
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
412
-        if (error_get_last() === null || ! headers_sent()) {
413
-            $notices = EE_Error::get_notices(false);
414
-            header('Content-Type: application/json; charset=UTF-8');
415
-            echo wp_json_encode($json + $notices);
416
-            exit();
417
-        }
418
-    }
419
-
420
-
421
-    /**
422
-     * Gets the job step response which was done during the enqueuing of scripts
423
-     *
424
-     * @return JobStepResponse
425
-     */
426
-    public function job_step_response(): JobStepResponse
427
-    {
428
-        return $this->_job_step_response;
429
-    }
430
-
431
-
432
-    /**
433
-     * Gets the batch request type indicated in the current request
434
-     *
435
-     * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
436
-     */
437
-    public function batch_request_type(): string
438
-    {
439
-        if (! $this->_batch_request_type) {
440
-            $request = EED_Batch::getRequest();
441
-            $batch   = $request->getRequestParam('batch');
442
-            switch ($batch) {
443
-                case self::batch_job:
444
-                    $this->_batch_request_type = self::batch_job;
445
-                    break;
446
-                case self::batch_file_job:
447
-                    $this->_batch_request_type = self::batch_file_job;
448
-                    break;
449
-                default:
450
-                    // if we didn't find that it was a batch request, indicate it wasn't
451
-                    $this->_batch_request_type = self::batch_not_job;
452
-            }
453
-        }
454
-        return $this->_batch_request_type;
455
-    }
456
-
457
-
458
-    /**
459
-     * Unnecessary
460
-     *
461
-     * @param WP $WP
462
-     */
463
-    public function run($WP)
464
-    {
465
-    }
32
+	public const PAGE_SLUG = 'espresso_batch';
33
+
34
+	/**
35
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
36
+	 * processes data only
37
+	 */
38
+	const batch_job = 'job';
39
+
40
+	/**
41
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
42
+	 * produces a file for download
43
+	 */
44
+	const batch_file_job = 'file';
45
+
46
+	/**
47
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
48
+	 * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
49
+	 * at all
50
+	 */
51
+	const batch_not_job = 'none';
52
+
53
+	/**
54
+	 *
55
+	 * @var string 'file', or 'job', or false to indicate its not a batch request at all
56
+	 */
57
+	protected $_batch_request_type = '';
58
+
59
+	/**
60
+	 * Because we want to use the response in both the localized JS and in the body
61
+	 * we need to make this response available between method calls
62
+	 *
63
+	 * @var JobStepResponse|null
64
+	 */
65
+	protected $_job_step_response = null;
66
+
67
+	/**
68
+	 * @var LoaderInterface|null
69
+	 */
70
+	protected $loader = null;
71
+
72
+
73
+	/**
74
+	 * Gets the batch instance
75
+	 *
76
+	 * @return  EED_Module|EED_Batch
77
+	 * @throws EE_Error
78
+	 * @throws ReflectionException
79
+	 */
80
+	public static function instance(): EED_Batch
81
+	{
82
+		return parent::get_instance(__CLASS__);
83
+	}
84
+
85
+
86
+	/**
87
+	 * Sets hooks to enable batch jobs on the frontend. Disabled by default
88
+	 * because it's an attack vector and there are currently no implementations
89
+	 *
90
+	 * @throws EE_Error
91
+	 * @throws ReflectionException
92
+	 */
93
+	public static function set_hooks()
94
+	{
95
+		// because this is a possible attack vector, let's have this disabled until
96
+		// we at least have a real use for it on the frontend
97
+		if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
98
+			add_action('wp_enqueue_scripts', [self::instance(), 'enqueue_scripts']);
99
+			add_filter('template_include', [self::instance(), 'override_template'], 99);
100
+		}
101
+	}
102
+
103
+
104
+	/**
105
+	 * Initializes some hooks for the admin in order to run batch jobs
106
+	 *
107
+	 * @throws EE_Error
108
+	 * @throws ReflectionException
109
+	 */
110
+	public static function set_hooks_admin()
111
+	{
112
+		add_action('admin_menu', [self::instance(), 'register_admin_pages']);
113
+		add_action('admin_enqueue_scripts', [self::instance(), 'enqueue_scripts']);
114
+
115
+		// ajax
116
+		add_action('wp_ajax_espresso_batch_continue', [self::instance(), 'continueBatchJob']);
117
+		add_action('wp_ajax_espresso_batch_advance', [self::instance(), 'advanceBatchJob']);
118
+		add_action('wp_ajax_espresso_batch_cleanup', [self::instance(), 'cleanupBatchJob']);
119
+		add_action('wp_ajax_nopriv_espresso_batch_continue', [self::instance(), 'continueBatchJob']);
120
+		add_action('wp_ajax_nopriv_espresso_batch_advance', [self::instance(), 'advanceBatchJob']);
121
+		add_action('wp_ajax_nopriv_espresso_batch_cleanup', [self::instance(), 'cleanupBatchJob']);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @return LoaderInterface
127
+	 * @throws InvalidArgumentException
128
+	 * @throws InvalidDataTypeException
129
+	 * @throws InvalidInterfaceException
130
+	 * @since 4.9.80.p
131
+	 */
132
+	protected function getLoader(): LoaderInterface
133
+	{
134
+		if (! $this->loader instanceof LoaderInterface) {
135
+			$this->loader = LoaderFactory::getLoader();
136
+		}
137
+		return $this->loader;
138
+	}
139
+
140
+
141
+	/**
142
+	 * Enqueues batch scripts on the frontend or admin, and creates a job
143
+	 */
144
+	public function enqueue_scripts()
145
+	{
146
+		$request = EED_Batch::getRequest();
147
+		if (
148
+			$request->getRequestParam(EED_Batch::PAGE_SLUG)
149
+			|| $request->getRequestParam('page') === EED_Batch::PAGE_SLUG
150
+		) {
151
+			if (
152
+				! $request->requestParamIsSet('default_nonce')
153
+				|| ! wp_verify_nonce($request->getRequestParam('default_nonce'), 'default_nonce')
154
+			) {
155
+				wp_die(
156
+					esc_html__(
157
+						'The link you clicked to start the batch job has expired. Please go back and refresh the previous page.',
158
+						'event_espresso'
159
+					)
160
+				);
161
+			}
162
+			switch ($this->batch_request_type()) {
163
+				case self::batch_job:
164
+					$this->enqueue_scripts_styles_batch_create();
165
+					break;
166
+				case self::batch_file_job:
167
+					$this->enqueue_scripts_styles_batch_file_create();
168
+					break;
169
+			}
170
+		}
171
+	}
172
+
173
+
174
+	/**
175
+	 * Create a batch job, enqueues a script to run it, and localizes some data for it
176
+	 */
177
+	public function enqueue_scripts_styles_batch_create()
178
+	{
179
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
180
+		wp_enqueue_script(
181
+			'batch_runner_init',
182
+			BATCH_URL . 'assets/batch_runner_init.js',
183
+			['batch_runner'],
184
+			date('Y-m-d-H:i', time()),
185
+			true
186
+		);
187
+		wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
188
+		wp_localize_script('batch_runner_init', 'eei18n', EE_Registry::$i18n_js_strings);
189
+
190
+		$return_url = EED_Batch::getRequest()->getRequestParam('return_url', '', DataType::URL);
191
+		if ($return_url) {
192
+			wp_localize_script(
193
+				'batch_runner_init',
194
+				'ee_job_i18n',
195
+				[
196
+					'return_url'                => $return_url,
197
+					'auto_redirect_on_complete' => EED_Batch::getRequest()->getRequestParam(
198
+						'auto_redirect_on_complete'
199
+					),
200
+					'user_message'              => EED_Batch::getRequest()->getRequestParam('assessment_notice')
201
+						?: EED_Batch::getRequest()->getRequestParam('job_start_notice'),
202
+				]
203
+			);
204
+		}
205
+	}
206
+
207
+
208
+	/**
209
+	 * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
210
+	 */
211
+	public function enqueue_scripts_styles_batch_file_create()
212
+	{
213
+		// creates a job based on the request variable
214
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
215
+		wp_enqueue_script(
216
+			'batch_file_runner_init',
217
+			BATCH_URL . 'assets/batch_file_runner_init.js',
218
+			['batch_runner'],
219
+			date('Y-m-d-H:i', time()),
220
+			true
221
+		);
222
+		wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
223
+		wp_localize_script('batch_file_runner_init', 'eei18n', EE_Registry::$i18n_js_strings);
224
+
225
+		$return_url = EED_Batch::getRequest()->getRequestParam('return_url', '', DataType::URL);
226
+		if ($return_url) {
227
+			wp_localize_script(
228
+				'batch_file_runner_init',
229
+				'ee_job_i18n',
230
+				['return_url' => $return_url]
231
+			);
232
+		}
233
+	}
234
+
235
+
236
+	/**
237
+	 * Enqueues scripts and styles common to any batch job, and creates
238
+	 * a job from the request data, and stores the response in the
239
+	 * $this->_job_step_response property
240
+	 *
241
+	 * @return JobStepResponse
242
+	 */
243
+	protected function _enqueue_batch_job_scripts_and_styles_and_start_job(): JobStepResponse
244
+	{
245
+		// just copy the bits of EE admin's eei18n that we need in the JS
246
+		EE_Registry::$i18n_js_strings['batchJobError'] = __(
247
+			'An error occurred and the job has been stopped. Please refresh the page to try again.',
248
+			'event_espresso'
249
+		);
250
+		EE_Registry::$i18n_js_strings['is_admin']      = is_admin();
251
+		wp_enqueue_style(
252
+			EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN,
253
+			EE_ADMIN_URL . 'assets/ee-admin-page.css',
254
+			['espresso_admin_base'],
255
+			EVENT_ESPRESSO_VERSION
256
+		);
257
+		wp_enqueue_style(
258
+			'batch_runner',
259
+			BATCH_URL . 'assets/batch_runner.css',
260
+			[EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
261
+			date('Y-m-d-H:i', time())
262
+		);
263
+		wp_register_script(
264
+			'progress_bar',
265
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
266
+			['jquery'],
267
+			date('Y-m-d-H:i', time()),
268
+			true
269
+		);
270
+		wp_enqueue_style(
271
+			'progress_bar',
272
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
273
+			[],
274
+			date('Y-m-d-H:i', time())
275
+		);
276
+		wp_enqueue_script(
277
+			'batch_runner',
278
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
279
+			['progress_bar', CoreAssetManager::JS_HANDLE_CORE],
280
+			date('Y-m-d-H:i', time()),
281
+			true
282
+		);
283
+		/** @var BatchRequestProcessor $batch_runner */
284
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
285
+		// eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
286
+		// remember the response for later. We need it to display the page body
287
+		$this->_job_step_response = $batch_runner->createJob();
288
+		return $this->_job_step_response;
289
+	}
290
+
291
+
292
+	/**
293
+	 * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
294
+	 *
295
+	 * @param string $template
296
+	 * @return string
297
+	 */
298
+	public function override_template(string $template): string
299
+	{
300
+		$request = EED_Batch::getRequest();
301
+		if ($request->requestParamIsSet('batch') && $request->requestParamIsSet(EED_Batch::PAGE_SLUG)) {
302
+			return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.php';
303
+		}
304
+		return $template;
305
+	}
306
+
307
+
308
+	/**
309
+	 * Adds an admin page which doesn't appear in the admin menu
310
+	 *
311
+	 * @throws EE_Error
312
+	 * @throws ReflectionException
313
+	 */
314
+	public function register_admin_pages()
315
+	{
316
+		add_submenu_page(
317
+			'',
318
+			// parent slug. we don't want this to actually appear in the menu
319
+			esc_html__('Batch Job', 'event_espresso'),
320
+			// page title
321
+			'n/a',
322
+			// menu title
323
+			'read',
324
+			// we want this page to actually be accessible to anyone,
325
+			EED_Batch::PAGE_SLUG,
326
+			// menu slug
327
+			[self::instance(), 'show_admin_page']
328
+		);
329
+	}
330
+
331
+
332
+	/**
333
+	 * Renders the admin page, after most of the work was already done during enqueuing scripts
334
+	 * of creating the job and localizing some data
335
+	 */
336
+	public function show_admin_page()
337
+	{
338
+		echo EEH_Template::locate_template(
339
+			EE_MODULES . 'batch/templates/batch_wrapper.template.php',
340
+			[
341
+				'batch_request_type'        => $this->batch_request_type(),
342
+				'auto_redirect_on_complete' => EED_Batch::getRequest()->getRequestParam('auto_redirect_on_complete'),
343
+				'user_message'              => EED_Batch::getRequest()->getRequestParam('assessment_notice')
344
+					?: EED_Batch::getRequest()->getRequestParam('job_start_notice'),
345
+			]
346
+		);
347
+	}
348
+
349
+
350
+	private function runBatchRunnerJob(string $job)
351
+	{
352
+		$job_id = EED_Batch::getRequest()->getRequestParam('job_id');
353
+		/** @var BatchRequestProcessor $batch_runner */
354
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
355
+		$job_response = $batch_runner->{$job}($job_id);
356
+		$this->_return_json($job_response->to_array());
357
+	}
358
+
359
+
360
+	/**
361
+	 * Receives ajax calls for continuing a job
362
+	 */
363
+	public function continueBatchJob()
364
+	{
365
+		$this->runBatchRunnerJob('continueJob');
366
+	}
367
+
368
+
369
+	/**
370
+	 * Receives ajax calls for continuing a job
371
+	 */
372
+	public function advanceBatchJob()
373
+	{
374
+		$this->runBatchRunnerJob('advanceJob');
375
+	}
376
+
377
+
378
+	/**
379
+	 * Receives the ajax call to cleanup a job
380
+	 *
381
+	 * @return void
382
+	 */
383
+	public function cleanupBatchJob()
384
+	{
385
+		$this->runBatchRunnerJob('cleanupJob');
386
+	}
387
+
388
+
389
+	/**
390
+	 * Returns a json response
391
+	 *
392
+	 * @param array $data The data we want to send echo via in the JSON response's "data" element
393
+	 *
394
+	 * The returned json object is created from an array in the following format:
395
+	 * array(
396
+	 *    'notices' => '', // - contains any EE_Error formatted notices
397
+	 *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
398
+	 *    We're also going to include the template args with every package (so js can pick out any specific template
399
+	 *    args that might be included in here)
400
+	 *    'isEEajax' => true,//indicates this is a response from EE
401
+	 * )
402
+	 */
403
+	protected function _return_json(array $data)
404
+	{
405
+		$json = [
406
+			'data'     => $data,
407
+			'isEEajax' => true,
408
+			// special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
409
+		];
410
+
411
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
412
+		if (error_get_last() === null || ! headers_sent()) {
413
+			$notices = EE_Error::get_notices(false);
414
+			header('Content-Type: application/json; charset=UTF-8');
415
+			echo wp_json_encode($json + $notices);
416
+			exit();
417
+		}
418
+	}
419
+
420
+
421
+	/**
422
+	 * Gets the job step response which was done during the enqueuing of scripts
423
+	 *
424
+	 * @return JobStepResponse
425
+	 */
426
+	public function job_step_response(): JobStepResponse
427
+	{
428
+		return $this->_job_step_response;
429
+	}
430
+
431
+
432
+	/**
433
+	 * Gets the batch request type indicated in the current request
434
+	 *
435
+	 * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
436
+	 */
437
+	public function batch_request_type(): string
438
+	{
439
+		if (! $this->_batch_request_type) {
440
+			$request = EED_Batch::getRequest();
441
+			$batch   = $request->getRequestParam('batch');
442
+			switch ($batch) {
443
+				case self::batch_job:
444
+					$this->_batch_request_type = self::batch_job;
445
+					break;
446
+				case self::batch_file_job:
447
+					$this->_batch_request_type = self::batch_file_job;
448
+					break;
449
+				default:
450
+					// if we didn't find that it was a batch request, indicate it wasn't
451
+					$this->_batch_request_type = self::batch_not_job;
452
+			}
453
+		}
454
+		return $this->_batch_request_type;
455
+	}
456
+
457
+
458
+	/**
459
+	 * Unnecessary
460
+	 *
461
+	 * @param WP $WP
462
+	 */
463
+	public function run($WP)
464
+	{
465
+	}
466 466
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     protected function getLoader(): LoaderInterface
133 133
     {
134
-        if (! $this->loader instanceof LoaderInterface) {
134
+        if ( ! $this->loader instanceof LoaderInterface) {
135 135
             $this->loader = LoaderFactory::getLoader();
136 136
         }
137 137
         return $this->loader;
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
180 180
         wp_enqueue_script(
181 181
             'batch_runner_init',
182
-            BATCH_URL . 'assets/batch_runner_init.js',
182
+            BATCH_URL.'assets/batch_runner_init.js',
183 183
             ['batch_runner'],
184 184
             date('Y-m-d-H:i', time()),
185 185
             true
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
215 215
         wp_enqueue_script(
216 216
             'batch_file_runner_init',
217
-            BATCH_URL . 'assets/batch_file_runner_init.js',
217
+            BATCH_URL.'assets/batch_file_runner_init.js',
218 218
             ['batch_runner'],
219 219
             date('Y-m-d-H:i', time()),
220 220
             true
@@ -247,35 +247,35 @@  discard block
 block discarded – undo
247 247
             'An error occurred and the job has been stopped. Please refresh the page to try again.',
248 248
             'event_espresso'
249 249
         );
250
-        EE_Registry::$i18n_js_strings['is_admin']      = is_admin();
250
+        EE_Registry::$i18n_js_strings['is_admin'] = is_admin();
251 251
         wp_enqueue_style(
252 252
             EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN,
253
-            EE_ADMIN_URL . 'assets/ee-admin-page.css',
253
+            EE_ADMIN_URL.'assets/ee-admin-page.css',
254 254
             ['espresso_admin_base'],
255 255
             EVENT_ESPRESSO_VERSION
256 256
         );
257 257
         wp_enqueue_style(
258 258
             'batch_runner',
259
-            BATCH_URL . 'assets/batch_runner.css',
259
+            BATCH_URL.'assets/batch_runner.css',
260 260
             [EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
261 261
             date('Y-m-d-H:i', time())
262 262
         );
263 263
         wp_register_script(
264 264
             'progress_bar',
265
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
265
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.js',
266 266
             ['jquery'],
267 267
             date('Y-m-d-H:i', time()),
268 268
             true
269 269
         );
270 270
         wp_enqueue_style(
271 271
             'progress_bar',
272
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
272
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.css',
273 273
             [],
274 274
             date('Y-m-d-H:i', time())
275 275
         );
276 276
         wp_enqueue_script(
277 277
             'batch_runner',
278
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
278
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/batch_runner.js',
279 279
             ['progress_bar', CoreAssetManager::JS_HANDLE_CORE],
280 280
             date('Y-m-d-H:i', time()),
281 281
             true
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
     {
300 300
         $request = EED_Batch::getRequest();
301 301
         if ($request->requestParamIsSet('batch') && $request->requestParamIsSet(EED_Batch::PAGE_SLUG)) {
302
-            return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.php';
302
+            return EE_MODULES.'batch/templates/batch_frontend_wrapper.template.php';
303 303
         }
304 304
         return $template;
305 305
     }
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
     public function show_admin_page()
337 337
     {
338 338
         echo EEH_Template::locate_template(
339
-            EE_MODULES . 'batch/templates/batch_wrapper.template.php',
339
+            EE_MODULES.'batch/templates/batch_wrapper.template.php',
340 340
             [
341 341
                 'batch_request_type'        => $this->batch_request_type(),
342 342
                 'auto_redirect_on_complete' => EED_Batch::getRequest()->getRequestParam('auto_redirect_on_complete'),
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
      */
437 437
     public function batch_request_type(): string
438 438
     {
439
-        if (! $this->_batch_request_type) {
439
+        if ( ! $this->_batch_request_type) {
440 440
             $request = EED_Batch::getRequest();
441 441
             $batch   = $request->getRequestParam('batch');
442 442
             switch ($batch) {
Please login to merge, or discard this patch.