Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 196
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Mailpoet_Export_Segment_To_MailPoet
0.00% covered (danger)
0.00%
0 / 195
0.00% covered (danger)
0.00%
0 / 4
552
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 instance
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 init_hooks
0.00% covered (danger)
0.00%
0 / 188
0.00% covered (danger)
0.00%
0 / 1
380
 get_export_list_name
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/*
3 * Jetpack CRM
4 * https://jetpackcrm.com
5 *
6 * MailPoet Sync: Export CRM segment to MailPoet list class
7 */
8namespace Automattic\JetpackCRM;
9
10// block direct access
11defined( 'ZEROBSCRM_PATH' ) || exit( 0 );
12
13/**
14 * Export CRM segment to MailPoet list class
15 */
16class Mailpoet_Export_Segment_To_MailPoet {
17
18    /**
19     * The single instance of the class.
20     */
21    protected static $_instance = null;
22
23    /**
24     * Setup Mailpoet_Export_Segment_To_MailPoet
25     */
26    public function __construct() {
27
28        // Initialise Hooks
29        $this->init_hooks();
30    }
31
32    /**
33     * Main Class Instance.
34     *
35     * Ensures only one instance of Mailpoet_Export_Segment_To_MailPoet is loaded or can be loaded.
36     *
37     * @since 2.0
38     * @static
39     * @see
40     * @return Mailpoet_Admin_Integration main instance
41     */
42    public static function instance() {
43        if ( self::$_instance === null ) {
44            self::$_instance = new self();
45        }
46        return self::$_instance;
47    }
48
49    /**
50     * Initialise Hooks
51     */
52    private function init_hooks() {
53
54        add_action(
55            'jpcrm_segment_edit_export_mailpoet_button',
56            function () {
57                // AJAX call to action 'jpcrm_segment_export_to_mailpoet'
58                ?>
59            <button class="ui submit black large icon button zbs-segment-export-mailpoet">
60                <?php esc_html_e( 'Export to MailPoet', 'zero-bs-crm' ); ?> <i class="mail forward icon"></i>
61            </button>
62                <?php
63            }
64        );
65
66        // enqueue our listview script additions
67        add_action(
68            'jpcrm_enqueue_styles_listview',
69            function () {
70
71                global $zbs;
72                wp_enqueue_script( 'jpcrm-mailpoet-listview', plugins_url( '/js/jpcrm-mailpoet-listview-additions' . wp_scripts_get_suffix() . '.js', JPCRM_MAILPOET_ROOT_FILE ), array( 'jquery' ), $zbs::VERSION ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter
73            }
74        );
75
76        // hook into zbs_root.lang to add lang labels on our page
77        add_filter(
78            'zbs_globaljs_lang',
79            function ( $language_labels = array() ) {
80
81                global $zbs, $pagenow;
82
83                // only on our page
84                if ( zeroBS_hasGETParamsWithValues(
85                    array( 'admin.php' ),
86                    array(
87                        'page'    => $zbs->slugs['addedit'],
88                        'zbstype' => 'segment',
89                    )
90                ) ) {
91
92                    $language_labels['mailpoet_list_exists']        = __( 'Previously Exported', 'zero-bs-crm' );
93                    $language_labels['mailpoet_list_exists_detail'] = __( 'This segment was previously exported to MailPoet. Are you sure you want to export it again?<br>(Doing so will overwrite the existing MailPoet List.)', 'zero-bs-crm' );
94                    $language_labels['continue_export']             = __( 'Start Export', 'zero-bs-crm' );
95
96                }
97
98                return $language_labels;
99            }
100        );
101
102        add_action(
103            'segment_edit_extra_js',
104            function () {
105
106                // JS to initiate export when window param passed
107                ?>
108
109                // Export segment as MailPoet list.
110                jQuery( '.zbs-segment-export-mailpoet' ).off( 'click' ).on( 'click', function ( e ) {
111                    let exportButton = jQuery( e.target );
112                    jpcrm_segment_export_to_mailpoet( exportButton );
113                });
114
115                // Check if mailpoet_export URL param is present, and start auto-export.
116                let searchParams = new URLSearchParams(window.location.search);
117                if ( searchParams.has('mailpoet_export') ) {
118                    jQuery( '.zbs-segment-export-mailpoet' ).click();
119                }
120
121                <?php
122            }
123        );
124
125        /**
126         * AJAX endpoint to kick off export from Segments to MailPoet
127         * This function only returns the total count of contacts that will
128         * be created as subscribers. Another AJAX request will POST-batch them
129         */
130        add_action(
131            'wp_ajax_jpcrm_mailpoet_export_kick_off',
132            function () {
133
134                // Check nonce
135                check_ajax_referer( 'zbs-ajax-nonce', 'sec' );
136
137                if ( current_user_can( 'admin_zerobs_customers' ) ) {
138                    global $zbs;
139
140                    $segment_id = -1;
141                    if ( isset( $_POST['segment_id'] ) ) {
142                        $segment_id = (int) sanitize_text_field( $_POST['segment_id'] );
143                    }
144
145                    try {
146
147                        $retrieve_fields  = array( 'email' );
148                        $segment_contacts = $zbs->DAL->segments->getSegmentAudience( $segment_id, 0, 100000, 'ID', 'DESC', false, false, $retrieve_fields );
149
150                        $segment = $zbs->DAL->segments->getSegment( $segment_id );
151
152                        if ( ! empty( $segment ) && is_array( $segment_contacts ) ) {
153
154                            $valid_emails = array_filter(
155                                $segment_contacts,
156                                function ( $sc ) {
157                                    return zeroBSCRM_validateEmail( $sc['email'] );
158                                }
159                            );
160
161                            $count_valid_emails = count( $valid_emails );
162                            $extra_message      = '';
163                            if ( $count_valid_emails > 500 ) {
164                                $extra_message = __( 'This might take a while.', 'zero-bs-crm' );
165                            }
166
167                            $list_name = $this->get_export_list_name( $segment['name'] );
168                            $list_id   = $zbs->modules->mailpoet->reset_mailpoet_list_by_segment_name( $list_name );
169
170                            if ( ! empty( $list_id ) ) {
171                                wp_send_json(
172                                    array(
173                                        'jpcrm_segment_ID' => $segment_id,
174                                        'mailpoet_list_ID' => $list_id,
175                                        'success'          => true,
176                                        'total_contacts'   => $count_valid_emails,
177                                        'lang'             => array(
178                                            'export_in_progress' => __( 'Export in progress', 'zero-bs-crm' ),
179                                            'export_finished' => __( 'Export finished', 'zero-bs-crm' ),
180                                            'export_in_progress_long' => __( 'This Segment is being exported to a MailPoet List.', 'zero-bs-crm' ) . ' ' . $extra_message,
181                                            'export_finished_long' => __( 'The export process is now complete. Click the button below to view the list of subscribers.', 'zero-bs-crm' ),
182                                            'go_to_mailpoet_list' => __( 'Go to MailPoet', 'zero-bs-crm' ),
183                                        ),
184                                    )
185                                );
186                            }
187                        }
188                    } catch ( \Throwable $th ) {
189                        wp_send_json(
190                            array(
191                                'success' => false,
192                                'lang'    => array(
193                                    'error_title'   => __( 'Something went wrong', 'zero-bs-crm' ),
194                                    'error_message' => $th->getMessage(),
195                                ),
196                            )
197                        );
198                    }
199                }
200
201                // empty handed
202                wp_send_json(
203                    array(
204                        'segmentID' => $segment_id,
205                        'success'   => false,
206                        'lang'      => array(
207                            'error_title'   => __( 'Something went wrong', 'zero-bs-crm' ),
208                            'error_message' => __( 'The segment could not be exported to MailPoet', 'zero-bs-crm' ),
209                        ),
210                    )
211                );
212            }
213        );
214
215        /**
216         * AJAX endpoint to export to MailPoet Segment, by batch
217         */
218        add_action(
219            'wp_ajax_jpcrm_mailpoet_export_segment',
220            function () {
221
222                header( 'Content-Type: application/json' );
223
224                global $zbs;
225
226                try {
227
228                    if ( ! current_user_can( 'admin_zerobs_customers' ) ) {
229                        echo esc_html__( 'Not enough permissions.', 'zero-bs-crm' );
230                        exit( 0 );
231                    }
232
233                    if ( ! isset( $_POST['segment_id'] ) || ! isset( $_POST['mailpoet_id'] ) ) {
234                        echo esc_html__( 'Not enough data provided to perform export.', 'zero-bs-crm' );
235                        exit( 0 );
236                    }
237
238                    $segment_id  = (int) sanitize_text_field( $_POST['segment_id'] );
239                    $mailpoet_id = (int) sanitize_text_field( $_POST['mailpoet_id'] );
240                    $page        = (int) sanitize_text_field( $_POST['page'] );
241                    $per_page    = (int) sanitize_text_field( $_POST['per_page'] );
242
243                    $retrieve_fields = $retrieve_fields = array( 'email', 'fname', 'lname' );
244                    $contacts_batch  = $zbs->DAL->segments->getSegmentAudience( $segment_id, $page, $per_page, 'ID', 'DESC', false, false, $retrieve_fields );
245
246                    // Create MailPoet Mailing List
247                    $response = $zbs->modules->mailpoet->contacts_to_subscribers( $mailpoet_id, $contacts_batch );
248
249                    if ( ! empty( $response['success'] ) ) {
250
251                        $is_last_batch = ( count( $contacts_batch ) < $per_page );
252
253                        wp_send_json(
254                            array(
255                                'success'       => true,
256                                'segmentID'     => $segment_id,
257                                'current_page'  => $page,
258                                'is_last_batch' => $is_last_batch,
259                            )
260                        );
261
262                    } else {
263
264                        wp_send_json(
265                            array(
266                                'segmentID' => $segment_id,
267                                'success'   => false,
268                                'error'     => $response['error'],
269                                'lang'      => array(
270                                    'error_title'   => __( 'Something went wrong', 'zero-bs-crm' ),
271                                    'error_message' => __( 'The segment could not be exported to MailPoet', 'zero-bs-crm' ),
272                                ),
273                            )
274                        );
275
276                    }
277                } catch ( \Throwable $th ) {
278
279                                wp_send_json(
280                                    array(
281                                        'segmentID' => $segment_id,
282                                        'success'   => false,
283                                        'error'     => $th->getMessage(),
284                                        'lang'      => array(
285                                            'error_title' => __( 'Something went wrong', 'zero-bs-crm' ),
286                                            'error_message' => __( 'The segment could not be exported to MailPoet', 'zero-bs-crm' ),
287                                        ),
288                                    )
289                                );
290
291                }
292            }
293        );
294
295        /**
296         * AJAX endpoint to retrieve summary data about a mailpoet list
297         */
298        add_action(
299            'wp_ajax_jpcrm_mailpoet_retrieve_list_summary',
300            function () {
301
302                header( 'Content-Type: application/json' );
303
304                global $zbs;
305
306                try {
307
308                    if ( ! current_user_can( 'admin_zerobs_customers' ) ) {
309                        echo esc_html__( 'Not enough permissions.', 'zero-bs-crm' );
310                        exit( 0 );
311                    }
312
313                    if ( ! isset( $_POST['list_name'] ) ) {
314                        echo esc_html__( 'Not enough data provided to perform export.', 'zero-bs-crm' );
315                        exit( 0 );
316                    }
317
318                    $list_name   = sanitize_text_field( $_POST['list_name'] );
319                    $list_suffix = (int) sanitize_text_field( $_POST['add_suffix'] );
320
321                    // add ` | CRM`?
322                    if ( $list_suffix ) {
323                        $list_name = $this->get_export_list_name( $list_name );
324                    }
325
326                    $list_details = $zbs->modules->mailpoet->get_mailpoet_list_summary_by_name( $list_name );
327
328                    if ( ! is_array( $list_details ) ) {
329                        // nope
330                        wp_send_json( false );
331                    } else {
332                        // success
333                        wp_send_json( $list_details );
334                    }
335                } catch ( \Throwable $th ) {
336                    wp_send_json_error( array( 'fail' => 1 ), 500 );
337                }
338            }
339        );
340    }
341
342    /**
343     * Returns the name that a segment would be exported to
344     */
345    public function get_export_list_name( $list_name = '' ) {
346
347        $name = $list_name . ' | CRM';
348        ##WLREMOVE
349        $name = $list_name . ' | Jetpack CRM';
350        ##/WLREMOVE
351
352        return $name;
353    }
354}