Completed
Branch BUG/3575-event-deletion-previe... (bbeda1)
by
unknown
06:40 queued 04:49
created
caffeinated/core/libraries/shortcodes/EE_Question_List_Shortcodes.lib.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -94,16 +94,16 @@
 block discarded – undo
94 94
             ? $this->_extra_data['template']['question_list']
95 95
             : $template;
96 96
         $ans_result       = '';
97
-        $answers          = ! empty($this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs'])
98
-            ? $this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs']
97
+        $answers          = ! empty($this->_extra_data['data']->registrations[$reg_obj->ID()]['ans_objs'])
98
+            ? $this->_extra_data['data']->registrations[$reg_obj->ID()]['ans_objs']
99 99
             : [];
100 100
         $questions        = ! empty($this->_extra_data['data']->questions)
101 101
             ? $this->_extra_data['data']->questions
102 102
             : [];
103 103
         foreach ($answers as $answer) {
104 104
             // first see if the question is in our $questions array.  If not then try to get from answer object
105
-            $question = isset($questions[ $answer->ID() ])
106
-                ? $questions[ $answer->ID() ]
105
+            $question = isset($questions[$answer->ID()])
106
+                ? $questions[$answer->ID()]
107 107
                 : null;
108 108
             $question = ! $question instanceof EE_Question
109 109
                 ? $answer->question()
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -16,109 +16,109 @@
 block discarded – undo
16 16
 class EE_Question_List_Shortcodes extends EE_Shortcodes
17 17
 {
18 18
 
19
-    public function __construct()
20
-    {
21
-        parent::__construct();
22
-    }
19
+	public function __construct()
20
+	{
21
+		parent::__construct();
22
+	}
23 23
 
24 24
 
25
-    protected function _init_props()
26
-    {
27
-        $this->label       = esc_html__('Questions and Answers Shortcodes', 'event_espresso');
28
-        $this->description = esc_html__('All shortcodes related to custom questions and answers', 'event_espresso');
29
-        $this->_shortcodes = [
30
-            '[QUESTION_LIST]' => esc_html__(
31
-                'This is used to indicate where you want the list of questions and answers to show for the registrant.  You place this within the "[attendee_list]" field.',
32
-                'event_espresso'
33
-            ),
34
-        ];
35
-    }
25
+	protected function _init_props()
26
+	{
27
+		$this->label       = esc_html__('Questions and Answers Shortcodes', 'event_espresso');
28
+		$this->description = esc_html__('All shortcodes related to custom questions and answers', 'event_espresso');
29
+		$this->_shortcodes = [
30
+			'[QUESTION_LIST]' => esc_html__(
31
+				'This is used to indicate where you want the list of questions and answers to show for the registrant.  You place this within the "[attendee_list]" field.',
32
+				'event_espresso'
33
+			),
34
+		];
35
+	}
36 36
 
37 37
 
38
-    /**
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    protected function _parser($shortcode)
43
-    {
44
-        switch ($shortcode) {
45
-            case '[QUESTION_LIST]':
46
-                return $this->_get_question_list();
47
-        }
48
-        return '';
49
-    }
38
+	/**
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	protected function _parser($shortcode)
43
+	{
44
+		switch ($shortcode) {
45
+			case '[QUESTION_LIST]':
46
+				return $this->_get_question_list();
47
+		}
48
+		return '';
49
+	}
50 50
 
51 51
 
52
-    /**
53
-     * @throws EE_Error
54
-     * @throws ReflectionException
55
-     */
56
-    protected function _get_question_list()
57
-    {
58
-        $this->_validate_list_requirements();
52
+	/**
53
+	 * @throws EE_Error
54
+	 * @throws ReflectionException
55
+	 */
56
+	protected function _get_question_list()
57
+	{
58
+		$this->_validate_list_requirements();
59 59
 
60
-        // for when [QUESTION_LIST] is used in the [attendee_list] field.
61
-        if ($this->_data['data'] instanceof EE_Registration) {
62
-            return $this->_get_question_answer_list_for_attendee();
63
-        }
64
-        // for when [QUESTION_LIST] is used in the main content field.
65
-        if (
66
-            $this->_data['data'] instanceof EE_Messages_Addressee
67
-            && $this->_data['data']->reg_obj instanceof EE_Registration
68
-        ) {
69
-            return $this->_get_question_answer_list_for_attendee($this->_data['data']->reg_obj);
70
-        }
71
-        return '';
72
-    }
60
+		// for when [QUESTION_LIST] is used in the [attendee_list] field.
61
+		if ($this->_data['data'] instanceof EE_Registration) {
62
+			return $this->_get_question_answer_list_for_attendee();
63
+		}
64
+		// for when [QUESTION_LIST] is used in the main content field.
65
+		if (
66
+			$this->_data['data'] instanceof EE_Messages_Addressee
67
+			&& $this->_data['data']->reg_obj instanceof EE_Registration
68
+		) {
69
+			return $this->_get_question_answer_list_for_attendee($this->_data['data']->reg_obj);
70
+		}
71
+		return '';
72
+	}
73 73
 
74 74
 
75
-    /**
76
-     * Note when we parse the "[question_list]" shortcode for attendees we're actually going to retrieve the list of
77
-     * answers for that attendee since that is what we really need (we can derive the questions from the answers);
78
-     *
79
-     * @param null $reg_obj
80
-     * @return string parsed template.
81
-     * @throws EE_Error
82
-     * @throws ReflectionException
83
-     */
84
-    private function _get_question_answer_list_for_attendee($reg_obj = null)
85
-    {
86
-        $valid_shortcodes = ['question'];
87
-        $reg_obj          = $reg_obj instanceof EE_Registration
88
-            ? $reg_obj
89
-            : $this->_data['data'];
90
-        $template         = is_array($this->_data['template']) && isset($this->_data['template']['question_list'])
91
-            ? $this->_data['template']['question_list']
92
-            : '';
93
-        $template         = empty($template) && isset($this->_extra_data['template']['question_list'])
94
-            ? $this->_extra_data['template']['question_list']
95
-            : $template;
96
-        $ans_result       = '';
97
-        $answers          = ! empty($this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs'])
98
-            ? $this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs']
99
-            : [];
100
-        $questions        = ! empty($this->_extra_data['data']->questions)
101
-            ? $this->_extra_data['data']->questions
102
-            : [];
103
-        foreach ($answers as $answer) {
104
-            // first see if the question is in our $questions array.  If not then try to get from answer object
105
-            $question = isset($questions[ $answer->ID() ])
106
-                ? $questions[ $answer->ID() ]
107
-                : null;
108
-            $question = ! $question instanceof EE_Question
109
-                ? $answer->question()
110
-                : $question;
111
-            if ($question instanceof EE_Question and $question->admin_only()) {
112
-                continue;
113
-            }
114
-            $ans_result .= $this->_shortcode_helper->parse_question_list_template(
115
-                $template,
116
-                $answer,
117
-                $valid_shortcodes,
118
-                $this->_extra_data
119
-            );
120
-        }
75
+	/**
76
+	 * Note when we parse the "[question_list]" shortcode for attendees we're actually going to retrieve the list of
77
+	 * answers for that attendee since that is what we really need (we can derive the questions from the answers);
78
+	 *
79
+	 * @param null $reg_obj
80
+	 * @return string parsed template.
81
+	 * @throws EE_Error
82
+	 * @throws ReflectionException
83
+	 */
84
+	private function _get_question_answer_list_for_attendee($reg_obj = null)
85
+	{
86
+		$valid_shortcodes = ['question'];
87
+		$reg_obj          = $reg_obj instanceof EE_Registration
88
+			? $reg_obj
89
+			: $this->_data['data'];
90
+		$template         = is_array($this->_data['template']) && isset($this->_data['template']['question_list'])
91
+			? $this->_data['template']['question_list']
92
+			: '';
93
+		$template         = empty($template) && isset($this->_extra_data['template']['question_list'])
94
+			? $this->_extra_data['template']['question_list']
95
+			: $template;
96
+		$ans_result       = '';
97
+		$answers          = ! empty($this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs'])
98
+			? $this->_extra_data['data']->registrations[ $reg_obj->ID() ]['ans_objs']
99
+			: [];
100
+		$questions        = ! empty($this->_extra_data['data']->questions)
101
+			? $this->_extra_data['data']->questions
102
+			: [];
103
+		foreach ($answers as $answer) {
104
+			// first see if the question is in our $questions array.  If not then try to get from answer object
105
+			$question = isset($questions[ $answer->ID() ])
106
+				? $questions[ $answer->ID() ]
107
+				: null;
108
+			$question = ! $question instanceof EE_Question
109
+				? $answer->question()
110
+				: $question;
111
+			if ($question instanceof EE_Question and $question->admin_only()) {
112
+				continue;
113
+			}
114
+			$ans_result .= $this->_shortcode_helper->parse_question_list_template(
115
+				$template,
116
+				$answer,
117
+				$valid_shortcodes,
118
+				$this->_extra_data
119
+			);
120
+		}
121 121
 
122
-        return $ans_result;
123
-    }
122
+		return $ans_result;
123
+	}
124 124
 }
Please login to merge, or discard this patch.
Paypal_Pro/help_tabs/payment_methods_overview_paypalpro.help_tab.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -4,10 +4,10 @@  discard block
 block discarded – undo
4 4
 </p>
5 5
 <p>
6 6
     <?php printf(
7
-        esc_html__('See %1$shere%2$s for list of currencies supported by Paypal Pro.', 'event_espresso'),
8
-        "<a href='https://www.paypal.com/multicurrency' target='_blank' rel='noopener noreferrer'>",
9
-        "</a>"
10
-    ); ?>
7
+		esc_html__('See %1$shere%2$s for list of currencies supported by Paypal Pro.', 'event_espresso'),
8
+		"<a href='https://www.paypal.com/multicurrency' target='_blank' rel='noopener noreferrer'>",
9
+		"</a>"
10
+	); ?>
11 11
 </p>
12 12
 <p><strong><?php esc_html_e('PayPal Pro Settings', 'event_espresso'); ?></strong></p>
13 13
 <ul>
@@ -18,48 +18,48 @@  discard block
 block discarded – undo
18 18
     <li>
19 19
         <strong><?php esc_html_e('PayPal API Username', 'event_espresso'); ?></strong><br/>
20 20
         <?php
21
-        printf(
22
-            esc_html__(
23
-                'Enter your API Username for PayPal. Learn how to find your %1$sAPI Username%2$s.',
24
-                'event_espresso'
25
-            ),
26
-            '<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
27
-            '</a>'
28
-        );
29
-        ?>
21
+		printf(
22
+			esc_html__(
23
+				'Enter your API Username for PayPal. Learn how to find your %1$sAPI Username%2$s.',
24
+				'event_espresso'
25
+			),
26
+			'<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
27
+			'</a>'
28
+		);
29
+		?>
30 30
     </li>
31 31
     <li>
32 32
         <strong><?php esc_html_e('PayPal API Password', 'event_espresso'); ?></strong><br/>
33 33
         <?php
34
-        printf(
35
-            esc_html__(
36
-                'Enter your API Password for PayPal. Learn how to find your %1$sAPI Password%2$s.',
37
-                'event_espresso'
38
-            ),
39
-            '<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
40
-            '</a>'
41
-        );
42
-        ?>
34
+		printf(
35
+			esc_html__(
36
+				'Enter your API Password for PayPal. Learn how to find your %1$sAPI Password%2$s.',
37
+				'event_espresso'
38
+			),
39
+			'<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
40
+			'</a>'
41
+		);
42
+		?>
43 43
     </li>
44 44
     <li>
45 45
         <strong><?php esc_html_e('PayPal API Signature', 'event_espresso'); ?></strong><br/>
46 46
         <?php
47
-        printf(
48
-            esc_html__(
49
-                'Enter your API Signature for PayPal. Learn how to find your %1$sAPI Signature%2$s.',
50
-                'event_espresso'
51
-            ),
52
-            '<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
53
-            '</a>'
54
-        );
55
-        ?>
47
+		printf(
48
+			esc_html__(
49
+				'Enter your API Signature for PayPal. Learn how to find your %1$sAPI Signature%2$s.',
50
+				'event_espresso'
51
+			),
52
+			'<a href="https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/merchant/wppro/WPProIntegrationSteps-outside#SectionB" target="_blank" rel="noopener noreferrer">',
53
+			'</a>'
54
+		);
55
+		?>
56 56
     </li>
57 57
     <li>
58 58
         <strong><?php esc_html_e('Country Currency', 'event_espresso'); ?></strong><br/>
59 59
         <?php esc_html_e(
60
-            'Select the currency for your country. Payments will be accepted in this currency.',
61
-            'event_espresso'
62
-        ); ?>
60
+			'Select the currency for your country. Payments will be accepted in this currency.',
61
+			'event_espresso'
62
+		); ?>
63 63
     </li>
64 64
     <li>
65 65
         <strong><?php esc_html_e('Accepted Card Types', 'event_espresso'); ?></strong><br/>
@@ -68,9 +68,9 @@  discard block
 block discarded – undo
68 68
     <li>
69 69
         <strong><?php esc_html_e('Use the Debugging Feature and the PayPal Sandbox', 'event_espresso'); ?></strong><br/>
70 70
         <?php esc_html_e(
71
-            'Specify if you want to test the payment gateway by submitting a test transaction. If this option is enabled, be sure to enter your PayPal sandbox credentials in the fields above. Be sure to turn this setting off when you are done testing.',
72
-            'event_espresso'
73
-        ); ?>
71
+			'Specify if you want to test the payment gateway by submitting a test transaction. If this option is enabled, be sure to enter your PayPal sandbox credentials in the fields above. Be sure to turn this setting off when you are done testing.',
72
+			'event_espresso'
73
+		); ?>
74 74
     </li>
75 75
     <li>
76 76
         <strong><?php esc_html_e('Button Image URL', 'event_espresso'); ?></strong><br/>
Please login to merge, or discard this patch.
payment_methods/Aim/help_tabs/payment_methods_overview_aim.help_tab.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -6,15 +6,15 @@  discard block
 block discarded – undo
6 6
 </p>
7 7
 <p>
8 8
     <?php
9
-    printf(
10
-        esc_html__(
11
-            'See %1$shere%2$s for list of currencies supported by Authorize.net AIM.',
12
-            'event_espresso'
13
-        ),
14
-        "<a href='https://support.authorize.net/s/article/Which-Currencies-Does-Authorize-Net-Support/' target='_blank' rel='noopener noreferrer'>",
15
-        "</a>"
16
-    );
17
-    ?>
9
+	printf(
10
+		esc_html__(
11
+			'See %1$shere%2$s for list of currencies supported by Authorize.net AIM.',
12
+			'event_espresso'
13
+		),
14
+		"<a href='https://support.authorize.net/s/article/Which-Currencies-Does-Authorize-Net-Support/' target='_blank' rel='noopener noreferrer'>",
15
+		"</a>"
16
+	);
17
+	?>
18 18
 </p>
19 19
 <p>
20 20
     <strong><?php esc_html_e('Authorize.net AIM Settings', 'event_espresso'); ?></strong>
@@ -24,70 +24,70 @@  discard block
 block discarded – undo
24 24
         <strong><?php esc_html_e('Authorize.net API Login ID', 'event_espresso'); ?></strong>
25 25
         <br/>
26 26
         <?php
27
-        printf(
28
-            esc_html__(
29
-                'Enter your API Login ID for Authorize.net. Learn how to find your %1$sAPI Login%2$s ID.',
30
-                'event_espresso'
31
-            ),
32
-            '<a href="https://support.authorize.net/authkb/index?page=content&id=A405" target="_blank" rel="noopener noreferrer">',
33
-            '</a>'
34
-        );
35
-        ?>
27
+		printf(
28
+			esc_html__(
29
+				'Enter your API Login ID for Authorize.net. Learn how to find your %1$sAPI Login%2$s ID.',
30
+				'event_espresso'
31
+			),
32
+			'<a href="https://support.authorize.net/authkb/index?page=content&id=A405" target="_blank" rel="noopener noreferrer">',
33
+			'</a>'
34
+		);
35
+		?>
36 36
     </li>
37 37
     <li>
38 38
         <strong><?php esc_html_e('Authorize.net Transaction Key', 'event_espresso'); ?></strong>
39 39
         <br/>
40 40
         <?php
41
-        printf(
42
-            esc_html__(
43
-                'Enter your Transaction Key for Authorize.net. Learn how to find your %1$sTransaction Key%2$s.',
44
-                'event_espresso'
45
-            ),
46
-            '<a href="https://support.authorize.net/authkb/index?page=content&id=A405" target="_blank" rel="noopener noreferrer">',
47
-            '</a>'
48
-        );
49
-        ?>
41
+		printf(
42
+			esc_html__(
43
+				'Enter your Transaction Key for Authorize.net. Learn how to find your %1$sTransaction Key%2$s.',
44
+				'event_espresso'
45
+			),
46
+			'<a href="https://support.authorize.net/authkb/index?page=content&id=A405" target="_blank" rel="noopener noreferrer">',
47
+			'</a>'
48
+		);
49
+		?>
50 50
     </li>
51 51
     <li>
52 52
         <strong>
53 53
             <?php esc_html_e(
54
-                'Is this an account on the Authorize.net development server?',
55
-                'event_espresso'
56
-            ); ?>
54
+				'Is this an account on the Authorize.net development server?',
55
+				'event_espresso'
56
+			); ?>
57 57
         </strong>
58 58
         <br/>
59 59
         <?php esc_html_e(
60
-            'Specify whether this is a live/production account or a test account on the Authorize.net development server.',
61
-            'event_espresso'
62
-        ); ?>
60
+			'Specify whether this is a live/production account or a test account on the Authorize.net development server.',
61
+			'event_espresso'
62
+		); ?>
63 63
     </li>
64 64
     <li>
65 65
         <strong><?php esc_html_e('Do you want to submit a test transaction?', 'event_espresso'); ?></strong>
66 66
         <br/>
67 67
         <?php esc_html_e(
68
-            'Specify if you want to test the Authorize.net AIM payment gateway by submitting a test transaction. Be sure to turn this setting off when you are done testing.',
69
-            'event_espresso'
70
-        ); ?>
68
+			'Specify if you want to test the Authorize.net AIM payment gateway by submitting a test transaction. Be sure to turn this setting off when you are done testing.',
69
+			'event_espresso'
70
+		); ?>
71 71
     </li>
72 72
     <li>
73 73
         <strong><?php esc_html_e('Excluded and Required Payment Form Fields', 'event_espresso'); ?></strong>
74 74
         <br/>
75 75
         <?php esc_html_e(
76
-            'By logging into Authorize.net, you can change which payment fields are required by Authorize.net when processing payments. These settings affect both the Advanced Integration Method (AIM, this) and the Simple Integration Method (SIM, different). The payment method settings "Excluded Payment Form Fields" and "Required Payment Form Fields" allow you to change the billing form in Event Espresso to reflect your payment form settings in Authorize.net.',
77
-            'event_espresso'
78
-        ); ?>
76
+			'By logging into Authorize.net, you can change which payment fields are required by Authorize.net when processing payments. These settings affect both the Advanced Integration Method (AIM, this) and the Simple Integration Method (SIM, different). The payment method settings "Excluded Payment Form Fields" and "Required Payment Form Fields" allow you to change the billing form in Event Espresso to reflect your payment form settings in Authorize.net.',
77
+			'event_espresso'
78
+		); ?>
79 79
         <br>
80 80
         <?php printf(
81
-            esc_html__(
82
-                'To change your payment form settings in Authorize.net, %1$slog in to authorize.net%2$s, go to %3$sAccount then Payment Form%2$s, then %4$sForm Fields%2$s. It will look similar to %5$sthis%2$s. If you make a field required in Authorize.net, you should also make it required in Event Espresso. If it isn\'t required in Authorize.net, and you want to simplify the billing form in Event Espresso, you can exclude it from the Event Espresso Form too.',
83
-                'event_espresso'
84
-            ),
85
-            '<a href="http://authorize.net" target="_blank" rel="noopener noreferrer">',
86
-            '</a>',
87
-            '<a href="https://monosnap.com/file/nebVteOkEXcdDIos88SojStWOifP23" target="_blank" rel="noopener noreferrer">',
88
-            '<a href="https://monosnap.com/file/WyxGJtev87TcDmdGBEZ2oi1xaBIQAm" target="_blank" rel="noopener noreferrer">',
89
-            '<a href="https://monosnap.com/image/DbCJNfEesWXeSNUs1wLIpGYODFw52m" target="_blank" rel="noopener noreferrer">'
90
-        ); ?>
81
+			esc_html__(
82
+				'To change your payment form settings in Authorize.net, %1$slog in to authorize.net%2$s, go to %3$sAccount then Payment Form%2$s, then %4$sForm Fields%2$s. It will look similar to %5$sthis%2$s. If you make a field required in Authorize.net, you should also make it required in Event Espresso. If it isn\'t required in Authorize.net, and you want to simplify the billing form in Event Espresso, you can exclude it from the Event Espresso Form too.',
83
+				'event_espresso'
84
+			),
85
+			'<a href="http://authorize.net" target="_blank" rel="noopener noreferrer">',
86
+			'</a>',
87
+			'<a href="https://monosnap.com/file/nebVteOkEXcdDIos88SojStWOifP23" target="_blank" rel="noopener noreferrer">',
88
+			'<a href="https://monosnap.com/file/WyxGJtev87TcDmdGBEZ2oi1xaBIQAm" target="_blank" rel="noopener noreferrer">',
89
+			'<a href="https://monosnap.com/image/DbCJNfEesWXeSNUs1wLIpGYODFw52m" target="_blank" rel="noopener noreferrer">'
90
+		); ?>
91 91
     </li>
92 92
     <li>
93 93
         <strong><?php esc_html_e('Button Image URL', 'event_espresso'); ?></strong>
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
     <li>
98 98
         <strong><?php esc_html_e('Note About Special Characters', 'event_espresso'); ?></strong>
99 99
         <?php
100
-        esc_html_e(
101
-            'If your event name, ticket name or ticket description contain special characters (eg emojis, foreign language characters, or curly quotes) they will be removed when sent to Authorize.net. This is because Authorize.net doesn\'t support them.',
102
-            'event_espresso'
103
-        );
104
-        ?>
100
+		esc_html_e(
101
+			'If your event name, ticket name or ticket description contain special characters (eg emojis, foreign language characters, or curly quotes) they will be removed when sent to Authorize.net. This is because Authorize.net doesn\'t support them.',
102
+			'event_espresso'
103
+		);
104
+		?>
105 105
     </li>
106 106
 </ul>
107 107
\ No newline at end of file
Please login to merge, or discard this patch.
caffeinated/brewing_regular.php 2 patches
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -12,10 +12,10 @@  discard block
 block discarded – undo
12 12
 use EventEspresso\core\services\database\TableAnalysis;
13 13
 
14 14
 // defined some new constants related to caffeinated folder
15
-define('EE_CAF_URL', EE_PLUGIN_DIR_URL . 'caffeinated/');
16
-define('EE_CAF_CORE', EE_CAFF_PATH . 'core/');
17
-define('EE_CAF_LIBRARIES', EE_CAF_CORE . 'libraries/');
18
-define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH . 'payment_methods/');
15
+define('EE_CAF_URL', EE_PLUGIN_DIR_URL.'caffeinated/');
16
+define('EE_CAF_CORE', EE_CAFF_PATH.'core/');
17
+define('EE_CAF_LIBRARIES', EE_CAF_CORE.'libraries/');
18
+define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH.'payment_methods/');
19 19
 
20 20
 
21 21
 /**
@@ -65,11 +65,11 @@  discard block
 block discarded – undo
65 65
         add_filter('FHEE__EE_Registry__load_helper__helper_paths', [$this, 'caf_helper_paths'], 10);
66 66
         add_filter(
67 67
             'AHEE__EE_System__load_core_configuration__complete',
68
-            function () {
68
+            function() {
69 69
                 EE_Register_Payment_Method::register(
70 70
                     'caffeinated_payment_methods',
71 71
                     [
72
-                        'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR),
72
+                        'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS.'*', GLOB_ONLYDIR),
73 73
                     ]
74 74
                 );
75 75
             }
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
      */
125 125
     public function caf_helper_paths($paths)
126 126
     {
127
-        $paths[] = EE_CAF_CORE . 'helpers/';
127
+        $paths[] = EE_CAF_CORE.'helpers/';
128 128
         return $paths;
129 129
     }
130 130
 
@@ -145,11 +145,11 @@  discard block
 block discarded – undo
145 145
         global $wpdb;
146 146
         // use same method of getting creator id as the version introducing the change
147 147
         $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
148
-        $price_type_table   = $wpdb->prefix . "esp_price_type";
149
-        $price_table        = $wpdb->prefix . "esp_price";
148
+        $price_type_table   = $wpdb->prefix."esp_price_type";
149
+        $price_table        = $wpdb->prefix."esp_price";
150 150
         if ($this->_get_table_analysis()->tableExists($price_type_table)) {
151 151
             $SQL                  =
152
-                'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';// include trashed price types
152
+                'SELECT COUNT(PRT_ID) FROM '.$price_type_table.' WHERE PBT_ID=4'; // include trashed price types
153 153
             $tax_price_type_count = $wpdb->get_var($SQL);
154 154
             if ($tax_price_type_count <= 1) {
155 155
                 $wpdb->insert(
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
                         'PRT_wp_user'    => $default_creator_id,
164 164
                     ],
165 165
                     [
166
-                        '%s',// PRT_name
167
-                        '%d',// PBT_id
168
-                        '%d',// PRT_is_percent
169
-                        '%d',// PRT_order
170
-                        '%d',// PRT_deleted
166
+                        '%s', // PRT_name
167
+                        '%d', // PBT_id
168
+                        '%d', // PRT_is_percent
169
+                        '%d', // PRT_order
170
+                        '%d', // PRT_deleted
171 171
                         '%d', // PRT_wp_user
172 172
                     ]
173 173
                 );
@@ -183,11 +183,11 @@  discard block
 block discarded – undo
183 183
                         'PRT_wp_user'    => $default_creator_id,
184 184
                     ],
185 185
                     [
186
-                        '%s',// PRT_name
187
-                        '%d',// PBT_id
188
-                        '%d',// PRT_is_percent
189
-                        '%d',// PRT_order
190
-                        '%d',// PRT_deleted
186
+                        '%s', // PRT_name
187
+                        '%d', // PBT_id
188
+                        '%d', // PRT_is_percent
189
+                        '%d', // PRT_order
190
+                        '%d', // PRT_deleted
191 191
                         '%d' // PRT_wp_user
192 192
                     ]
193 193
                 );
@@ -207,15 +207,15 @@  discard block
 block discarded – undo
207 207
                             'PRC_wp_user'    => $default_creator_id,
208 208
                         ],
209 209
                         [
210
-                            '%d',// PRT_id
211
-                            '%f',// PRC_amount
212
-                            '%s',// PRC_name
213
-                            '%s',// PRC_desc
214
-                            '%d',// PRC_is_default
215
-                            '%d',// PRC_overrides
216
-                            '%d',// PRC_deleted
217
-                            '%d',// PRC_order
218
-                            '%d',// PRC_parent
210
+                            '%d', // PRT_id
211
+                            '%f', // PRC_amount
212
+                            '%s', // PRC_name
213
+                            '%s', // PRC_desc
214
+                            '%d', // PRC_is_default
215
+                            '%d', // PRC_overrides
216
+                            '%d', // PRC_deleted
217
+                            '%d', // PRC_order
218
+                            '%d', // PRC_parent
219 219
                             '%d' // PRC_wp_user
220 220
                         ]
221 221
                     );
@@ -234,8 +234,8 @@  discard block
 block discarded – undo
234 234
      */
235 235
     public function caffeinated_modules_to_register($modules_to_register = [])
236 236
     {
237
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
238
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules/*', GLOB_ONLYDIR);
237
+        if (is_readable(EE_CAFF_PATH.'modules')) {
238
+            $caffeinated_modules_to_register = glob(EE_CAFF_PATH.'modules/*', GLOB_ONLYDIR);
239 239
             if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
240 240
                 $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
241 241
             }
Please login to merge, or discard this patch.
Indentation   +315 added lines, -315 removed lines patch added patch discarded remove patch
@@ -28,323 +28,323 @@
 block discarded – undo
28 28
 class EE_Brewing_Regular extends EE_BASE implements InterminableInterface
29 29
 {
30 30
 
31
-    /**
32
-     * @var TableAnalysis $table_analysis
33
-     */
34
-    protected $_table_analysis;
35
-
36
-
37
-    /**
38
-     * EE_Brewing_Regular constructor.
39
-     *
40
-     * @param TableAnalysis $table_analysis
41
-     */
42
-    public function __construct(TableAnalysis $table_analysis)
43
-    {
44
-        $this->_table_analysis = $table_analysis;
45
-        if (defined('EE_CAFF_PATH')) {
46
-            $this->setInitializationHooks();
47
-            $this->setApiRegistrationHooks();
48
-            $this->setSwitchHooks();
49
-            $this->setDefaultFilterHooks();
50
-            // caffeinated constructed
51
-            do_action('AHEE__EE_Brewing_Regular__construct__complete');
52
-        }
53
-    }
54
-
55
-
56
-    /**
57
-     * Various hooks used for extending features via registration of modules or extensions.
58
-     */
59
-    private function setApiRegistrationHooks()
60
-    {
61
-        add_filter(
62
-            'FHEE__EE_Config__register_modules__modules_to_register',
63
-            [$this, 'caffeinated_modules_to_register']
64
-        );
65
-        add_filter('FHEE__EE_Registry__load_helper__helper_paths', [$this, 'caf_helper_paths'], 10);
66
-        add_filter(
67
-            'AHEE__EE_System__load_core_configuration__complete',
68
-            function () {
69
-                EE_Register_Payment_Method::register(
70
-                    'caffeinated_payment_methods',
71
-                    [
72
-                        'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR),
73
-                    ]
74
-                );
75
-            }
76
-        );
77
-    }
78
-
79
-
80
-    /**
81
-     * Various hooks used for modifying initialization or activation processes.
82
-     */
83
-    private function setInitializationHooks()
84
-    {
85
-        // activation
86
-        add_action('AHEE__EEH_Activation__initialize_db_content', [$this, 'initialize_caf_db_content']);
87
-        // load caff init
88
-        add_action('AHEE__EE_System__set_hooks_for_core', [$this, 'caffeinated_init']);
89
-        // load caff scripts
90
-        add_action('wp_enqueue_scripts', [$this, 'enqueue_caffeinated_scripts'], 10);
91
-    }
92
-
93
-
94
-    /**
95
-     * Various hooks used for switch (on/off) type filters.
96
-     */
97
-    private function setSwitchHooks()
98
-    {
99
-        // remove the "powered by" credit link from receipts and invoices
100
-        add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
101
-        // seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
102
-        add_filter('FHEE__ee_show_affiliate_links', '__return_false');
103
-    }
104
-
105
-
106
-    /**
107
-     * Various filters for affecting default configuration values in the caffeinated
108
-     * context.
109
-     */
110
-    private function setDefaultFilterHooks()
111
-    {
112
-        add_filter(
113
-            'FHEE__EE_Admin_Config__show_reg_footer__default',
114
-            '__return_true'
115
-        );
116
-    }
117
-
118
-
119
-    /**
120
-     * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
121
-     *
122
-     * @param array $paths original helper paths array
123
-     * @return array             new array of paths
124
-     */
125
-    public function caf_helper_paths($paths)
126
-    {
127
-        $paths[] = EE_CAF_CORE . 'helpers/';
128
-        return $paths;
129
-    }
130
-
131
-
132
-    /**
133
-     * Upon brand-new activation, if this is a new activation of CAF, we want to add
134
-     * some global prices that will show off EE4's capabilities. However, if they're upgrading
135
-     * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
136
-     * This action should only be called when EE 4.x.0.P is initially activated.
137
-     * Right now the only CAF content are these global prices. If there's more in the future, then
138
-     * we should probably create a caf file to contain it all instead just a function like this.
139
-     * Right now, we ASSUME the only price types in the system are default ones
140
-     *
141
-     * @global wpdb $wpdb
142
-     */
143
-    public function initialize_caf_db_content()
144
-    {
145
-        global $wpdb;
146
-        // use same method of getting creator id as the version introducing the change
147
-        $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
148
-        $price_type_table   = $wpdb->prefix . "esp_price_type";
149
-        $price_table        = $wpdb->prefix . "esp_price";
150
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
151
-            $SQL                  =
152
-                'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';// include trashed price types
153
-            $tax_price_type_count = $wpdb->get_var($SQL);
154
-            if ($tax_price_type_count <= 1) {
155
-                $wpdb->insert(
156
-                    $price_type_table,
157
-                    [
158
-                        'PRT_name'       => esc_html__("Regional Tax", "event_espresso"),
159
-                        'PBT_ID'         => 4,
160
-                        'PRT_is_percent' => true,
161
-                        'PRT_order'      => 60,
162
-                        'PRT_deleted'    => false,
163
-                        'PRT_wp_user'    => $default_creator_id,
164
-                    ],
165
-                    [
166
-                        '%s',// PRT_name
167
-                        '%d',// PBT_id
168
-                        '%d',// PRT_is_percent
169
-                        '%d',// PRT_order
170
-                        '%d',// PRT_deleted
171
-                        '%d', // PRT_wp_user
172
-                    ]
173
-                );
174
-                // federal tax
175
-                $result = $wpdb->insert(
176
-                    $price_type_table,
177
-                    [
178
-                        'PRT_name'       => esc_html__("Federal Tax", "event_espresso"),
179
-                        'PBT_ID'         => 4,
180
-                        'PRT_is_percent' => true,
181
-                        'PRT_order'      => 70,
182
-                        'PRT_deleted'    => false,
183
-                        'PRT_wp_user'    => $default_creator_id,
184
-                    ],
185
-                    [
186
-                        '%s',// PRT_name
187
-                        '%d',// PBT_id
188
-                        '%d',// PRT_is_percent
189
-                        '%d',// PRT_order
190
-                        '%d',// PRT_deleted
191
-                        '%d' // PRT_wp_user
192
-                    ]
193
-                );
194
-                if ($result) {
195
-                    $wpdb->insert(
196
-                        $price_table,
197
-                        [
198
-                            'PRT_ID'         => $wpdb->insert_id,
199
-                            'PRC_amount'     => 15.00,
200
-                            'PRC_name'       => esc_html__("Sales Tax", "event_espresso"),
201
-                            'PRC_desc'       => '',
202
-                            'PRC_is_default' => true,
203
-                            'PRC_overrides'  => null,
204
-                            'PRC_deleted'    => false,
205
-                            'PRC_order'      => 50,
206
-                            'PRC_parent'     => null,
207
-                            'PRC_wp_user'    => $default_creator_id,
208
-                        ],
209
-                        [
210
-                            '%d',// PRT_id
211
-                            '%f',// PRC_amount
212
-                            '%s',// PRC_name
213
-                            '%s',// PRC_desc
214
-                            '%d',// PRC_is_default
215
-                            '%d',// PRC_overrides
216
-                            '%d',// PRC_deleted
217
-                            '%d',// PRC_order
218
-                            '%d',// PRC_parent
219
-                            '%d' // PRC_wp_user
220
-                        ]
221
-                    );
222
-                }
223
-            }
224
-        }
225
-    }
226
-
227
-
228
-    /**
229
-     *    caffeinated_modules_to_register
230
-     *
231
-     * @access public
232
-     * @param array $modules_to_register
233
-     * @return array
234
-     */
235
-    public function caffeinated_modules_to_register($modules_to_register = [])
236
-    {
237
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
238
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules/*', GLOB_ONLYDIR);
239
-            if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
240
-                $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
241
-            }
242
-        }
243
-        return $modules_to_register;
244
-    }
245
-
246
-
247
-    /**
248
-     * @throws EE_Error
249
-     * @throws InvalidArgumentException
250
-     * @throws ReflectionException
251
-     * @throws InvalidDataTypeException
252
-     * @throws InvalidInterfaceException
253
-     */
254
-    public function caffeinated_init()
255
-    {
256
-        // Custom Post Type hooks
257
-        add_filter(
258
-            'FHEE__EventEspresso_core_domain_entities_custom_post_types_TaxonomyDefinitions__getTaxonomies',
259
-            [$this, 'filter_taxonomies']
260
-        );
261
-        add_filter(
262
-            'FHEE__EventEspresso_core_domain_entities_custom_post_types_CustomPostTypeDefinitions__getCustomPostTypes',
263
-            [$this, 'filter_cpts']
264
-        );
265
-        add_filter(
266
-            'FHEE__EE_Admin__get_extra_nav_menu_pages_items',
267
-            [$this, 'nav_metabox_items']
268
-        );
269
-        EE_Registry::instance()->load_file(
270
-            EE_CAFF_PATH,
271
-            'EE_Caf_Messages',
272
-            'class',
273
-            [],
274
-            false
275
-        );
276
-        // caffeinated_init__complete hook
277
-        do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
278
-    }
279
-
280
-
281
-    public function enqueue_caffeinated_scripts()
282
-    {
283
-        // sound of crickets...
284
-    }
285
-
286
-
287
-    /**
288
-     * callbacks below here
289
-     *
290
-     * @param array $taxonomy_array
291
-     * @return array
292
-     */
293
-    public function filter_taxonomies(array $taxonomy_array)
294
-    {
295
-        $taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
296
-        return $taxonomy_array;
297
-    }
298
-
299
-
300
-    /**
301
-     * @param array $cpt_array
302
-     * @return mixed
303
-     */
304
-    public function filter_cpts(array $cpt_array)
305
-    {
306
-        $cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
307
-        return $cpt_array;
308
-    }
309
-
310
-
311
-    /**
312
-     * @param array $menuitems
313
-     * @return array
314
-     */
315
-    public function nav_metabox_items(array $menuitems)
316
-    {
317
-        $menuitems[] = [
318
-            'title'       => esc_html__('Venue List', 'event_espresso'),
319
-            'url'         => get_post_type_archive_link('espresso_venues'),
320
-            'description' => esc_html__('Archive page for all venues.', 'event_espresso'),
321
-        ];
322
-        return $menuitems;
323
-    }
324
-
325
-
326
-    /**
327
-     * Gets the injected table analyzer, or throws an exception
328
-     *
329
-     * @return TableAnalysis
330
-     * @throws \EE_Error
331
-     */
332
-    protected function _get_table_analysis()
333
-    {
334
-        if ($this->_table_analysis instanceof TableAnalysis) {
335
-            return $this->_table_analysis;
336
-        } else {
337
-            throw new \EE_Error(
338
-                sprintf(
339
-                    esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
340
-                    get_class($this)
341
-                )
342
-            );
343
-        }
344
-    }
31
+	/**
32
+	 * @var TableAnalysis $table_analysis
33
+	 */
34
+	protected $_table_analysis;
35
+
36
+
37
+	/**
38
+	 * EE_Brewing_Regular constructor.
39
+	 *
40
+	 * @param TableAnalysis $table_analysis
41
+	 */
42
+	public function __construct(TableAnalysis $table_analysis)
43
+	{
44
+		$this->_table_analysis = $table_analysis;
45
+		if (defined('EE_CAFF_PATH')) {
46
+			$this->setInitializationHooks();
47
+			$this->setApiRegistrationHooks();
48
+			$this->setSwitchHooks();
49
+			$this->setDefaultFilterHooks();
50
+			// caffeinated constructed
51
+			do_action('AHEE__EE_Brewing_Regular__construct__complete');
52
+		}
53
+	}
54
+
55
+
56
+	/**
57
+	 * Various hooks used for extending features via registration of modules or extensions.
58
+	 */
59
+	private function setApiRegistrationHooks()
60
+	{
61
+		add_filter(
62
+			'FHEE__EE_Config__register_modules__modules_to_register',
63
+			[$this, 'caffeinated_modules_to_register']
64
+		);
65
+		add_filter('FHEE__EE_Registry__load_helper__helper_paths', [$this, 'caf_helper_paths'], 10);
66
+		add_filter(
67
+			'AHEE__EE_System__load_core_configuration__complete',
68
+			function () {
69
+				EE_Register_Payment_Method::register(
70
+					'caffeinated_payment_methods',
71
+					[
72
+						'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR),
73
+					]
74
+				);
75
+			}
76
+		);
77
+	}
78
+
79
+
80
+	/**
81
+	 * Various hooks used for modifying initialization or activation processes.
82
+	 */
83
+	private function setInitializationHooks()
84
+	{
85
+		// activation
86
+		add_action('AHEE__EEH_Activation__initialize_db_content', [$this, 'initialize_caf_db_content']);
87
+		// load caff init
88
+		add_action('AHEE__EE_System__set_hooks_for_core', [$this, 'caffeinated_init']);
89
+		// load caff scripts
90
+		add_action('wp_enqueue_scripts', [$this, 'enqueue_caffeinated_scripts'], 10);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Various hooks used for switch (on/off) type filters.
96
+	 */
97
+	private function setSwitchHooks()
98
+	{
99
+		// remove the "powered by" credit link from receipts and invoices
100
+		add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
101
+		// seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
102
+		add_filter('FHEE__ee_show_affiliate_links', '__return_false');
103
+	}
104
+
105
+
106
+	/**
107
+	 * Various filters for affecting default configuration values in the caffeinated
108
+	 * context.
109
+	 */
110
+	private function setDefaultFilterHooks()
111
+	{
112
+		add_filter(
113
+			'FHEE__EE_Admin_Config__show_reg_footer__default',
114
+			'__return_true'
115
+		);
116
+	}
117
+
118
+
119
+	/**
120
+	 * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
121
+	 *
122
+	 * @param array $paths original helper paths array
123
+	 * @return array             new array of paths
124
+	 */
125
+	public function caf_helper_paths($paths)
126
+	{
127
+		$paths[] = EE_CAF_CORE . 'helpers/';
128
+		return $paths;
129
+	}
130
+
131
+
132
+	/**
133
+	 * Upon brand-new activation, if this is a new activation of CAF, we want to add
134
+	 * some global prices that will show off EE4's capabilities. However, if they're upgrading
135
+	 * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
136
+	 * This action should only be called when EE 4.x.0.P is initially activated.
137
+	 * Right now the only CAF content are these global prices. If there's more in the future, then
138
+	 * we should probably create a caf file to contain it all instead just a function like this.
139
+	 * Right now, we ASSUME the only price types in the system are default ones
140
+	 *
141
+	 * @global wpdb $wpdb
142
+	 */
143
+	public function initialize_caf_db_content()
144
+	{
145
+		global $wpdb;
146
+		// use same method of getting creator id as the version introducing the change
147
+		$default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
148
+		$price_type_table   = $wpdb->prefix . "esp_price_type";
149
+		$price_table        = $wpdb->prefix . "esp_price";
150
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
151
+			$SQL                  =
152
+				'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';// include trashed price types
153
+			$tax_price_type_count = $wpdb->get_var($SQL);
154
+			if ($tax_price_type_count <= 1) {
155
+				$wpdb->insert(
156
+					$price_type_table,
157
+					[
158
+						'PRT_name'       => esc_html__("Regional Tax", "event_espresso"),
159
+						'PBT_ID'         => 4,
160
+						'PRT_is_percent' => true,
161
+						'PRT_order'      => 60,
162
+						'PRT_deleted'    => false,
163
+						'PRT_wp_user'    => $default_creator_id,
164
+					],
165
+					[
166
+						'%s',// PRT_name
167
+						'%d',// PBT_id
168
+						'%d',// PRT_is_percent
169
+						'%d',// PRT_order
170
+						'%d',// PRT_deleted
171
+						'%d', // PRT_wp_user
172
+					]
173
+				);
174
+				// federal tax
175
+				$result = $wpdb->insert(
176
+					$price_type_table,
177
+					[
178
+						'PRT_name'       => esc_html__("Federal Tax", "event_espresso"),
179
+						'PBT_ID'         => 4,
180
+						'PRT_is_percent' => true,
181
+						'PRT_order'      => 70,
182
+						'PRT_deleted'    => false,
183
+						'PRT_wp_user'    => $default_creator_id,
184
+					],
185
+					[
186
+						'%s',// PRT_name
187
+						'%d',// PBT_id
188
+						'%d',// PRT_is_percent
189
+						'%d',// PRT_order
190
+						'%d',// PRT_deleted
191
+						'%d' // PRT_wp_user
192
+					]
193
+				);
194
+				if ($result) {
195
+					$wpdb->insert(
196
+						$price_table,
197
+						[
198
+							'PRT_ID'         => $wpdb->insert_id,
199
+							'PRC_amount'     => 15.00,
200
+							'PRC_name'       => esc_html__("Sales Tax", "event_espresso"),
201
+							'PRC_desc'       => '',
202
+							'PRC_is_default' => true,
203
+							'PRC_overrides'  => null,
204
+							'PRC_deleted'    => false,
205
+							'PRC_order'      => 50,
206
+							'PRC_parent'     => null,
207
+							'PRC_wp_user'    => $default_creator_id,
208
+						],
209
+						[
210
+							'%d',// PRT_id
211
+							'%f',// PRC_amount
212
+							'%s',// PRC_name
213
+							'%s',// PRC_desc
214
+							'%d',// PRC_is_default
215
+							'%d',// PRC_overrides
216
+							'%d',// PRC_deleted
217
+							'%d',// PRC_order
218
+							'%d',// PRC_parent
219
+							'%d' // PRC_wp_user
220
+						]
221
+					);
222
+				}
223
+			}
224
+		}
225
+	}
226
+
227
+
228
+	/**
229
+	 *    caffeinated_modules_to_register
230
+	 *
231
+	 * @access public
232
+	 * @param array $modules_to_register
233
+	 * @return array
234
+	 */
235
+	public function caffeinated_modules_to_register($modules_to_register = [])
236
+	{
237
+		if (is_readable(EE_CAFF_PATH . 'modules')) {
238
+			$caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules/*', GLOB_ONLYDIR);
239
+			if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
240
+				$modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
241
+			}
242
+		}
243
+		return $modules_to_register;
244
+	}
245
+
246
+
247
+	/**
248
+	 * @throws EE_Error
249
+	 * @throws InvalidArgumentException
250
+	 * @throws ReflectionException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws InvalidInterfaceException
253
+	 */
254
+	public function caffeinated_init()
255
+	{
256
+		// Custom Post Type hooks
257
+		add_filter(
258
+			'FHEE__EventEspresso_core_domain_entities_custom_post_types_TaxonomyDefinitions__getTaxonomies',
259
+			[$this, 'filter_taxonomies']
260
+		);
261
+		add_filter(
262
+			'FHEE__EventEspresso_core_domain_entities_custom_post_types_CustomPostTypeDefinitions__getCustomPostTypes',
263
+			[$this, 'filter_cpts']
264
+		);
265
+		add_filter(
266
+			'FHEE__EE_Admin__get_extra_nav_menu_pages_items',
267
+			[$this, 'nav_metabox_items']
268
+		);
269
+		EE_Registry::instance()->load_file(
270
+			EE_CAFF_PATH,
271
+			'EE_Caf_Messages',
272
+			'class',
273
+			[],
274
+			false
275
+		);
276
+		// caffeinated_init__complete hook
277
+		do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
278
+	}
279
+
280
+
281
+	public function enqueue_caffeinated_scripts()
282
+	{
283
+		// sound of crickets...
284
+	}
285
+
286
+
287
+	/**
288
+	 * callbacks below here
289
+	 *
290
+	 * @param array $taxonomy_array
291
+	 * @return array
292
+	 */
293
+	public function filter_taxonomies(array $taxonomy_array)
294
+	{
295
+		$taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
296
+		return $taxonomy_array;
297
+	}
298
+
299
+
300
+	/**
301
+	 * @param array $cpt_array
302
+	 * @return mixed
303
+	 */
304
+	public function filter_cpts(array $cpt_array)
305
+	{
306
+		$cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
307
+		return $cpt_array;
308
+	}
309
+
310
+
311
+	/**
312
+	 * @param array $menuitems
313
+	 * @return array
314
+	 */
315
+	public function nav_metabox_items(array $menuitems)
316
+	{
317
+		$menuitems[] = [
318
+			'title'       => esc_html__('Venue List', 'event_espresso'),
319
+			'url'         => get_post_type_archive_link('espresso_venues'),
320
+			'description' => esc_html__('Archive page for all venues.', 'event_espresso'),
321
+		];
322
+		return $menuitems;
323
+	}
324
+
325
+
326
+	/**
327
+	 * Gets the injected table analyzer, or throws an exception
328
+	 *
329
+	 * @return TableAnalysis
330
+	 * @throws \EE_Error
331
+	 */
332
+	protected function _get_table_analysis()
333
+	{
334
+		if ($this->_table_analysis instanceof TableAnalysis) {
335
+			return $this->_table_analysis;
336
+		} else {
337
+			throw new \EE_Error(
338
+				sprintf(
339
+					esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
340
+					get_class($this)
341
+				)
342
+			);
343
+		}
344
+	}
345 345
 }
346 346
 
347 347
 
348 348
 $brewing = new EE_Brewing_Regular(
349
-    EE_Registry::instance()->create('TableAnalysis', [], true)
349
+	EE_Registry::instance()->create('TableAnalysis', [], true)
350 350
 );
Please login to merge, or discard this patch.
core/services/request/CurrentPage.php 2 patches
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
             return;
86 86
         }
87 87
         // if somebody forgot to provide us with WP, that's ok because its global
88
-        if (! $WP instanceof WP) {
88
+        if ( ! $WP instanceof WP) {
89 89
             global $WP;
90 90
         }
91 91
         $this->post_id   = $this->getPostId($WP);
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
         if ($post_id) {
111 111
             return get_permalink($post_id);
112 112
         }
113
-        if (! $WP instanceof WP) {
113
+        if ( ! $WP instanceof WP) {
114 114
             global $WP;
115 115
         }
116 116
         if ($WP instanceof WP && $WP->request) {
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
     {
128 128
         return array_filter(
129 129
             $this->post_type,
130
-            function ($post_type) {
130
+            function($post_type) {
131 131
                 return strpos($post_type, 'espresso_') === 0;
132 132
             }
133 133
         );
@@ -149,17 +149,17 @@  discard block
 block discarded – undo
149 149
                 $post_id = $WP->query_vars['p'];
150 150
             }
151 151
             // not a post? what about a page?
152
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
152
+            if ( ! $post_id && isset($WP->query_vars['page_id'])) {
153 153
                 $post_id = $WP->query_vars['page_id'];
154 154
             }
155 155
             // ok... maybe pretty permalinks are off and the ID is set in the raw request...
156 156
             // but hasn't been processed yet ie: this method is being called too early :\
157
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
157
+            if ( ! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158 158
                 $post_id = basename($WP->request);
159 159
             }
160 160
         }
161 161
         // none of the above? ok what about an explicit "post_id" URL parameter?
162
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
162
+        if ( ! $post_id && $this->request->requestParamIsSet('post_id')) {
163 163
             $post_id = $this->request->getRequestParam('post_id');
164 164
         }
165 165
         return $post_id;
@@ -182,14 +182,14 @@  discard block
 block discarded – undo
182 182
                 $post_name = $WP->query_vars['name'];
183 183
             }
184 184
             // what about the page name?
185
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
185
+            if ( ! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186 186
                 $post_name = $WP->query_vars['pagename'];
187 187
             }
188 188
             // this stinks but let's run a query to try and get the post name from the URL
189 189
             // (assuming pretty permalinks are on)
190
-            if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
190
+            if ( ! $post_name && $WP->request !== null && ! empty($WP->request)) {
191 191
                 $possible_post_name = basename($WP->request);
192
-                if (! is_numeric($possible_post_name)) {
192
+                if ( ! is_numeric($possible_post_name)) {
193 193
                     $SQL                = "SELECT ID from {$wpdb->posts}";
194 194
                     $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
195 195
                     $SQL                .= ' AND post_name=%s';
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         }
203 203
         // ug... ok... nothing yet... but do we have a post ID?
204 204
         // if so then... sigh... run a query to get the post name :\
205
-        if (! $post_name && $this->post_id) {
205
+        if ( ! $post_name && $this->post_id) {
206 206
             $SQL                = "SELECT post_name from {$wpdb->posts}";
207 207
             $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
208 208
             $SQL                .= ' AND ID=%d';
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
             }
213 213
         }
214 214
         // still nothing? ok what about an explicit 'post_name' URL parameter?
215
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
215
+        if ( ! $post_name && $this->request->requestParamIsSet('post_name')) {
216 216
             $post_name = $this->request->getRequestParam('post_name');
217 217
         }
218 218
         return $post_name;
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
         $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
309 309
         if (is_array($espresso_CPT_taxonomies)) {
310 310
             foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
311
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
311
+                if (isset($WP->query_vars, $WP->query_vars[$espresso_CPT_taxonomy])) {
312 312
                     return true;
313 313
                 }
314 314
             }
@@ -318,14 +318,14 @@  discard block
 block discarded – undo
318 318
         $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
319 319
         foreach ($this->post_type as $post_type) {
320 320
             // was a post name passed ?
321
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
321
+            if (isset($post_type_CPT_endpoints[$post_type])) {
322 322
                 // kk we know this is an espresso page, but is it a specific post ?
323
-                if (! $this->post_name) {
323
+                if ( ! $this->post_name) {
324 324
                     $espresso_post_type = $this->request->getRequestParam('post_type');
325 325
                     // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
326 326
                     // this essentially sets the post_name to "events" (or whatever EE CPT)
327
-                    $post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
328
-                        ? $post_type_CPT_endpoints[ $espresso_post_type ]
327
+                    $post_name = isset($post_type_CPT_endpoints[$espresso_post_type])
328
+                        ? $post_type_CPT_endpoints[$espresso_post_type]
329 329
                         : '';
330 330
                     // if the post type matches one of ours then set the post name to the endpoint
331 331
                     if ($post_name) {
Please login to merge, or discard this patch.
Indentation   +314 added lines, -314 removed lines patch added patch discarded remove patch
@@ -23,318 +23,318 @@
 block discarded – undo
23 23
  */
24 24
 class CurrentPage
25 25
 {
26
-    /**
27
-     * @var EE_CPT_Strategy
28
-     */
29
-    private $cpt_strategy;
30
-
31
-    /**
32
-     * @var bool
33
-     */
34
-    private $initialized;
35
-
36
-    /**
37
-     * @var bool
38
-     */
39
-    private $is_espresso_page = false;
40
-
41
-    /**
42
-     * @var int
43
-     */
44
-    private $post_id = 0;
45
-
46
-    /**
47
-     * @var string
48
-     */
49
-    private $post_name = '';
50
-
51
-    /**
52
-     * @var array
53
-     */
54
-    private $post_type = [];
55
-
56
-    /**
57
-     * @var RequestInterface $request
58
-     */
59
-    private $request;
60
-
61
-
62
-    /**
63
-     * CurrentPage constructor.
64
-     *
65
-     * @param EE_CPT_Strategy  $cpt_strategy
66
-     * @param RequestInterface $request
67
-     */
68
-    public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
-    {
70
-        $this->cpt_strategy = $cpt_strategy;
71
-        $this->request      = $request;
72
-        $this->initialized  = is_admin();
73
-        // analyse the incoming WP request
74
-        add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param WP $WP
80
-     * @return void
81
-     */
82
-    public function parseQueryVars(WP $WP = null)
83
-    {
84
-        if ($this->initialized) {
85
-            return;
86
-        }
87
-        // if somebody forgot to provide us with WP, that's ok because its global
88
-        if (! $WP instanceof WP) {
89
-            global $WP;
90
-        }
91
-        $this->post_id   = $this->getPostId($WP);
92
-        $this->post_name = $this->getPostName($WP);
93
-        $this->post_type = $this->getPostType($WP);
94
-        // true or false ? is this page being used by EE ?
95
-        $this->setEspressoPage();
96
-        remove_action('parse_request', [$this, 'parseRequest'], 2);
97
-        $this->initialized = true;
98
-    }
99
-
100
-
101
-    /**
102
-     * Just a helper method for getting the url for the displayed page.
103
-     *
104
-     * @param WP|null $WP
105
-     * @return string
106
-     */
107
-    public function getPermalink(WP $WP = null)
108
-    {
109
-        $post_id = $this->post_id ?: $this->getPostId($WP);
110
-        if ($post_id) {
111
-            return get_permalink($post_id);
112
-        }
113
-        if (! $WP instanceof WP) {
114
-            global $WP;
115
-        }
116
-        if ($WP instanceof WP && $WP->request) {
117
-            return site_url($WP->request);
118
-        }
119
-        return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
-    }
121
-
122
-
123
-    /**
124
-     * @return array
125
-     */
126
-    public function espressoPostType()
127
-    {
128
-        return array_filter(
129
-            $this->post_type,
130
-            function ($post_type) {
131
-                return strpos($post_type, 'espresso_') === 0;
132
-            }
133
-        );
134
-    }
135
-
136
-
137
-    /**
138
-     * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
-     *
140
-     * @param WP $WP
141
-     * @return int
142
-     */
143
-    private function getPostId(WP $WP = null)
144
-    {
145
-        $post_id = null;
146
-        if ($WP instanceof WP) {
147
-            // look for the post ID in the aptly named 'p' query var
148
-            if (isset($WP->query_vars['p'])) {
149
-                $post_id = $WP->query_vars['p'];
150
-            }
151
-            // not a post? what about a page?
152
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
153
-                $post_id = $WP->query_vars['page_id'];
154
-            }
155
-            // ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
-            // but hasn't been processed yet ie: this method is being called too early :\
157
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
-                $post_id = basename($WP->request);
159
-            }
160
-        }
161
-        // none of the above? ok what about an explicit "post_id" URL parameter?
162
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
-            $post_id = $this->request->getRequestParam('post_id');
164
-        }
165
-        return $post_id;
166
-    }
167
-
168
-
169
-    /**
170
-     * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
-     *
172
-     * @param WP $WP
173
-     * @return string
174
-     */
175
-    private function getPostName(WP $WP = null)
176
-    {
177
-        global $wpdb;
178
-        $post_name = null;
179
-        if ($WP instanceof WP) {
180
-            // if this is a post, then is the post name set?
181
-            if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
-                $post_name = $WP->query_vars['name'];
183
-            }
184
-            // what about the page name?
185
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
-                $post_name = $WP->query_vars['pagename'];
187
-            }
188
-            // this stinks but let's run a query to try and get the post name from the URL
189
-            // (assuming pretty permalinks are on)
190
-            if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
191
-                $possible_post_name = basename($WP->request);
192
-                if (! is_numeric($possible_post_name)) {
193
-                    $SQL                = "SELECT ID from {$wpdb->posts}";
194
-                    $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
195
-                    $SQL                .= ' AND post_name=%s';
196
-                    $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
197
-                    if ($possible_post_name) {
198
-                        $post_name = $possible_post_name;
199
-                    }
200
-                }
201
-            }
202
-        }
203
-        // ug... ok... nothing yet... but do we have a post ID?
204
-        // if so then... sigh... run a query to get the post name :\
205
-        if (! $post_name && $this->post_id) {
206
-            $SQL                = "SELECT post_name from {$wpdb->posts}";
207
-            $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
208
-            $SQL                .= ' AND ID=%d';
209
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
210
-            if ($possible_post_name) {
211
-                $post_name = $possible_post_name;
212
-            }
213
-        }
214
-        // still nothing? ok what about an explicit 'post_name' URL parameter?
215
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
216
-            $post_name = $this->request->getRequestParam('post_name');
217
-        }
218
-        return $post_name;
219
-    }
220
-
221
-
222
-    /**
223
-     * also similar to getPostId() and getPostName() above but not as insane
224
-     *
225
-     * @param WP $WP
226
-     * @return array
227
-     */
228
-    private function getPostType(WP $WP = null)
229
-    {
230
-        $post_types = [];
231
-        if ($WP instanceof WP) {
232
-            $post_types = isset($WP->query_vars['post_type'])
233
-                ? (array) $WP->query_vars['post_type']
234
-                : [];
235
-        }
236
-        if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
237
-            $post_types = $this->request->getRequestParam('post_type', [], 'string', true);
238
-        }
239
-        return (array) $post_types;
240
-    }
241
-
242
-
243
-    /**
244
-     * if TRUE, then the current page is somehow utilizing EE logic
245
-     *
246
-     * @return bool
247
-     */
248
-    public function isEspressoPage()
249
-    {
250
-        return $this->is_espresso_page;
251
-    }
252
-
253
-
254
-    /**
255
-     * @return int
256
-     */
257
-    public function postId()
258
-    {
259
-        return $this->post_id;
260
-    }
261
-
262
-
263
-    /**
264
-     * @return string
265
-     */
266
-    public function postName()
267
-    {
268
-        return $this->post_name;
269
-    }
270
-
271
-
272
-    /**
273
-     * @return array
274
-     */
275
-    public function postType()
276
-    {
277
-        return $this->post_type;
278
-    }
279
-
280
-
281
-    /**
282
-     * for manually indicating the current page will utilize EE logic
283
-     *
284
-     * @param null|bool $value
285
-     * @return void
286
-     */
287
-    public function setEspressoPage($value = null)
288
-    {
289
-        $this->is_espresso_page = $value !== null
290
-            ? filter_var($value, FILTER_VALIDATE_BOOLEAN)
291
-            : $this->testForEspressoPage();
292
-    }
293
-
294
-
295
-    /**
296
-     * attempts to determine if the current page/post is an EE related page/post
297
-     * because it utilizes one of our CPT taxonomies, endpoints, or post types
298
-     *
299
-     * @return bool
300
-     */
301
-    private function testForEspressoPage()
302
-    {
303
-        // in case it has already been set
304
-        if ($this->is_espresso_page) {
305
-            return true;
306
-        }
307
-        global $WP;
308
-        $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
309
-        if (is_array($espresso_CPT_taxonomies)) {
310
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
311
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
312
-                    return true;
313
-                }
314
-            }
315
-        }
316
-        // load espresso CPT endpoints
317
-        $espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
318
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
319
-        foreach ($this->post_type as $post_type) {
320
-            // was a post name passed ?
321
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
322
-                // kk we know this is an espresso page, but is it a specific post ?
323
-                if (! $this->post_name) {
324
-                    $espresso_post_type = $this->request->getRequestParam('post_type');
325
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
326
-                    // this essentially sets the post_name to "events" (or whatever EE CPT)
327
-                    $post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
328
-                        ? $post_type_CPT_endpoints[ $espresso_post_type ]
329
-                        : '';
330
-                    // if the post type matches one of ours then set the post name to the endpoint
331
-                    if ($post_name) {
332
-                        $this->post_name = $post_name;
333
-                    }
334
-                }
335
-                return true;
336
-            }
337
-        }
338
-        return false;
339
-    }
26
+	/**
27
+	 * @var EE_CPT_Strategy
28
+	 */
29
+	private $cpt_strategy;
30
+
31
+	/**
32
+	 * @var bool
33
+	 */
34
+	private $initialized;
35
+
36
+	/**
37
+	 * @var bool
38
+	 */
39
+	private $is_espresso_page = false;
40
+
41
+	/**
42
+	 * @var int
43
+	 */
44
+	private $post_id = 0;
45
+
46
+	/**
47
+	 * @var string
48
+	 */
49
+	private $post_name = '';
50
+
51
+	/**
52
+	 * @var array
53
+	 */
54
+	private $post_type = [];
55
+
56
+	/**
57
+	 * @var RequestInterface $request
58
+	 */
59
+	private $request;
60
+
61
+
62
+	/**
63
+	 * CurrentPage constructor.
64
+	 *
65
+	 * @param EE_CPT_Strategy  $cpt_strategy
66
+	 * @param RequestInterface $request
67
+	 */
68
+	public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
+	{
70
+		$this->cpt_strategy = $cpt_strategy;
71
+		$this->request      = $request;
72
+		$this->initialized  = is_admin();
73
+		// analyse the incoming WP request
74
+		add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param WP $WP
80
+	 * @return void
81
+	 */
82
+	public function parseQueryVars(WP $WP = null)
83
+	{
84
+		if ($this->initialized) {
85
+			return;
86
+		}
87
+		// if somebody forgot to provide us with WP, that's ok because its global
88
+		if (! $WP instanceof WP) {
89
+			global $WP;
90
+		}
91
+		$this->post_id   = $this->getPostId($WP);
92
+		$this->post_name = $this->getPostName($WP);
93
+		$this->post_type = $this->getPostType($WP);
94
+		// true or false ? is this page being used by EE ?
95
+		$this->setEspressoPage();
96
+		remove_action('parse_request', [$this, 'parseRequest'], 2);
97
+		$this->initialized = true;
98
+	}
99
+
100
+
101
+	/**
102
+	 * Just a helper method for getting the url for the displayed page.
103
+	 *
104
+	 * @param WP|null $WP
105
+	 * @return string
106
+	 */
107
+	public function getPermalink(WP $WP = null)
108
+	{
109
+		$post_id = $this->post_id ?: $this->getPostId($WP);
110
+		if ($post_id) {
111
+			return get_permalink($post_id);
112
+		}
113
+		if (! $WP instanceof WP) {
114
+			global $WP;
115
+		}
116
+		if ($WP instanceof WP && $WP->request) {
117
+			return site_url($WP->request);
118
+		}
119
+		return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
+	}
121
+
122
+
123
+	/**
124
+	 * @return array
125
+	 */
126
+	public function espressoPostType()
127
+	{
128
+		return array_filter(
129
+			$this->post_type,
130
+			function ($post_type) {
131
+				return strpos($post_type, 'espresso_') === 0;
132
+			}
133
+		);
134
+	}
135
+
136
+
137
+	/**
138
+	 * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
+	 *
140
+	 * @param WP $WP
141
+	 * @return int
142
+	 */
143
+	private function getPostId(WP $WP = null)
144
+	{
145
+		$post_id = null;
146
+		if ($WP instanceof WP) {
147
+			// look for the post ID in the aptly named 'p' query var
148
+			if (isset($WP->query_vars['p'])) {
149
+				$post_id = $WP->query_vars['p'];
150
+			}
151
+			// not a post? what about a page?
152
+			if (! $post_id && isset($WP->query_vars['page_id'])) {
153
+				$post_id = $WP->query_vars['page_id'];
154
+			}
155
+			// ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
+			// but hasn't been processed yet ie: this method is being called too early :\
157
+			if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
+				$post_id = basename($WP->request);
159
+			}
160
+		}
161
+		// none of the above? ok what about an explicit "post_id" URL parameter?
162
+		if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
+			$post_id = $this->request->getRequestParam('post_id');
164
+		}
165
+		return $post_id;
166
+	}
167
+
168
+
169
+	/**
170
+	 * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
+	 *
172
+	 * @param WP $WP
173
+	 * @return string
174
+	 */
175
+	private function getPostName(WP $WP = null)
176
+	{
177
+		global $wpdb;
178
+		$post_name = null;
179
+		if ($WP instanceof WP) {
180
+			// if this is a post, then is the post name set?
181
+			if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
+				$post_name = $WP->query_vars['name'];
183
+			}
184
+			// what about the page name?
185
+			if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
+				$post_name = $WP->query_vars['pagename'];
187
+			}
188
+			// this stinks but let's run a query to try and get the post name from the URL
189
+			// (assuming pretty permalinks are on)
190
+			if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
191
+				$possible_post_name = basename($WP->request);
192
+				if (! is_numeric($possible_post_name)) {
193
+					$SQL                = "SELECT ID from {$wpdb->posts}";
194
+					$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
195
+					$SQL                .= ' AND post_name=%s';
196
+					$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
197
+					if ($possible_post_name) {
198
+						$post_name = $possible_post_name;
199
+					}
200
+				}
201
+			}
202
+		}
203
+		// ug... ok... nothing yet... but do we have a post ID?
204
+		// if so then... sigh... run a query to get the post name :\
205
+		if (! $post_name && $this->post_id) {
206
+			$SQL                = "SELECT post_name from {$wpdb->posts}";
207
+			$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
208
+			$SQL                .= ' AND ID=%d';
209
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
210
+			if ($possible_post_name) {
211
+				$post_name = $possible_post_name;
212
+			}
213
+		}
214
+		// still nothing? ok what about an explicit 'post_name' URL parameter?
215
+		if (! $post_name && $this->request->requestParamIsSet('post_name')) {
216
+			$post_name = $this->request->getRequestParam('post_name');
217
+		}
218
+		return $post_name;
219
+	}
220
+
221
+
222
+	/**
223
+	 * also similar to getPostId() and getPostName() above but not as insane
224
+	 *
225
+	 * @param WP $WP
226
+	 * @return array
227
+	 */
228
+	private function getPostType(WP $WP = null)
229
+	{
230
+		$post_types = [];
231
+		if ($WP instanceof WP) {
232
+			$post_types = isset($WP->query_vars['post_type'])
233
+				? (array) $WP->query_vars['post_type']
234
+				: [];
235
+		}
236
+		if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
237
+			$post_types = $this->request->getRequestParam('post_type', [], 'string', true);
238
+		}
239
+		return (array) $post_types;
240
+	}
241
+
242
+
243
+	/**
244
+	 * if TRUE, then the current page is somehow utilizing EE logic
245
+	 *
246
+	 * @return bool
247
+	 */
248
+	public function isEspressoPage()
249
+	{
250
+		return $this->is_espresso_page;
251
+	}
252
+
253
+
254
+	/**
255
+	 * @return int
256
+	 */
257
+	public function postId()
258
+	{
259
+		return $this->post_id;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @return string
265
+	 */
266
+	public function postName()
267
+	{
268
+		return $this->post_name;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @return array
274
+	 */
275
+	public function postType()
276
+	{
277
+		return $this->post_type;
278
+	}
279
+
280
+
281
+	/**
282
+	 * for manually indicating the current page will utilize EE logic
283
+	 *
284
+	 * @param null|bool $value
285
+	 * @return void
286
+	 */
287
+	public function setEspressoPage($value = null)
288
+	{
289
+		$this->is_espresso_page = $value !== null
290
+			? filter_var($value, FILTER_VALIDATE_BOOLEAN)
291
+			: $this->testForEspressoPage();
292
+	}
293
+
294
+
295
+	/**
296
+	 * attempts to determine if the current page/post is an EE related page/post
297
+	 * because it utilizes one of our CPT taxonomies, endpoints, or post types
298
+	 *
299
+	 * @return bool
300
+	 */
301
+	private function testForEspressoPage()
302
+	{
303
+		// in case it has already been set
304
+		if ($this->is_espresso_page) {
305
+			return true;
306
+		}
307
+		global $WP;
308
+		$espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
309
+		if (is_array($espresso_CPT_taxonomies)) {
310
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
311
+				if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
312
+					return true;
313
+				}
314
+			}
315
+		}
316
+		// load espresso CPT endpoints
317
+		$espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
318
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
319
+		foreach ($this->post_type as $post_type) {
320
+			// was a post name passed ?
321
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
322
+				// kk we know this is an espresso page, but is it a specific post ?
323
+				if (! $this->post_name) {
324
+					$espresso_post_type = $this->request->getRequestParam('post_type');
325
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
326
+					// this essentially sets the post_name to "events" (or whatever EE CPT)
327
+					$post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
328
+						? $post_type_CPT_endpoints[ $espresso_post_type ]
329
+						: '';
330
+					// if the post type matches one of ours then set the post name to the endpoint
331
+					if ($post_name) {
332
+						$this->post_name = $post_name;
333
+					}
334
+				}
335
+				return true;
336
+			}
337
+		}
338
+		return false;
339
+	}
340 340
 }
Please login to merge, or discard this patch.
core/libraries/messages/validators/EE_Messages_Validator.core.php 2 patches
Indentation   +622 added lines, -622 removed lines patch added patch discarded remove patch
@@ -17,626 +17,626 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * These properties just hold the name for the Messenger and Message Type (defined by child classes).
22
-     * These are used for retrieving objects etc.
23
-     *
24
-     * @var string
25
-     */
26
-    protected $_m_name;
27
-
28
-    protected $_mt_name;
29
-
30
-
31
-    /**
32
-     * This will hold any error messages from the validation process.
33
-     * The _errors property holds an associative array of error messages
34
-     * listing the field as the key and the message as the value.
35
-     *
36
-     * @var array()
37
-     */
38
-    private $_errors = [];
39
-
40
-
41
-    /**
42
-     * holds an array of fields being validated
43
-     *
44
-     * @var array
45
-     */
46
-    protected $_fields;
47
-
48
-
49
-    /**
50
-     * this will hold the incoming context
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_context;
55
-
56
-
57
-    /**
58
-     * this holds an array of fields and the relevant validation information
59
-     * that the incoming fields data get validated against.
60
-     * This gets setup in the _set_props() method.
61
-     *
62
-     * @var array
63
-     */
64
-    protected $_validators;
65
-
66
-
67
-    /**
68
-     * holds the messenger object
69
-     *
70
-     * @var object
71
-     */
72
-    protected $_messenger;
73
-
74
-
75
-    /**
76
-     * holds the message type object
77
-     *
78
-     * @var object
79
-     */
80
-    protected $_message_type;
81
-
82
-
83
-    /**
84
-     * will hold any valid_shortcode modifications made by the _modify_validator() method.
85
-     *
86
-     * @var array
87
-     */
88
-    protected $_valid_shortcodes_modifier;
89
-
90
-
91
-    /**
92
-     * There may be times where a message type wants to include a shortcode group but exclude specific
93
-     * shortcodes.  If that's the case then it can set this property as an array of shortcodes to exclude and
94
-     * they will not be allowed.
95
-     * Array should be indexed by field and values are an array of specific shortcodes to exclude.
96
-     *
97
-     * @var array
98
-     */
99
-    protected $_specific_shortcode_excludes = [];
100
-
101
-
102
-    /**
103
-     * Runs the validator using the incoming fields array as the fields/values to check.
104
-     *
105
-     * @param array $fields The fields sent by the EEM object.
106
-     * @param       $context
107
-     * @throws EE_Error
108
-     * @throws ReflectionException
109
-     */
110
-    public function __construct($fields, $context)
111
-    {
112
-        // check that _m_name and _mt_name have been set by child class otherwise we get out.
113
-        if (empty($this->_m_name) || empty($this->_mt_name)) {
114
-            throw new EE_Error(
115
-                esc_html__(
116
-                    'EE_Messages_Validator child classes MUST set the $_m_name and $_mt_name property.  Check that the child class is doing this',
117
-                    'event_espresso'
118
-                )
119
-            );
120
-        }
121
-        $this->_fields  = $fields;
122
-        $this->_context = $context;
123
-
124
-        // load messenger and message_type objects and the related shortcode objects.
125
-        $this->_load_objects();
126
-
127
-
128
-        // modify any messenger/message_type specific validation instructions.  This is what child classes define.
129
-        $this->_modify_validator();
130
-
131
-
132
-        // let's set validators property
133
-        $this->_set_validators();
134
-    }
135
-
136
-
137
-    /**
138
-     * Child classes instantiate this and use it to modify the _validator_config array property
139
-     * for the messenger using messengers set_validate_config() method.
140
-     * This is so we can specify specific validation instructions for a messenger/message_type combo
141
-     * that aren't handled by the defaults setup in the messenger.
142
-     *
143
-     * @abstract
144
-     * @return void
145
-     */
146
-    abstract protected function _modify_validator();
147
-
148
-
149
-    /**
150
-     * loads all objects used by validator
151
-     *
152
-     * @throws EE_Error
153
-     */
154
-    private function _load_objects()
155
-    {
156
-        // load messenger
157
-        $messenger = ucwords(str_replace('_', ' ', $this->_m_name));
158
-        $messenger = str_replace(' ', '_', $messenger);
159
-        $messenger = 'EE_' . $messenger . '_messenger';
160
-
161
-        if (! class_exists($messenger)) {
162
-            throw new EE_Error(
163
-                sprintf(
164
-                    esc_html__('There is no messenger class for the given string (%s)', 'event_espresso'),
165
-                    $this->_m_name
166
-                )
167
-            );
168
-        }
169
-
170
-        $this->_messenger = new $messenger();
171
-
172
-        // load message type
173
-        $message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
174
-        $message_type = str_replace(' ', '_', $message_type);
175
-        $message_type = 'EE_' . $message_type . '_message_type';
176
-
177
-        if (! class_exists($message_type)) {
178
-            throw new EE_Error(
179
-                sprintf(
180
-                    esc_html__('There is no message type class for the given string (%s)', 'event_espresso'),
181
-                    $this->_mt_name
182
-                )
183
-            );
184
-        }
185
-
186
-        $this->_message_type = new $message_type();
187
-    }
188
-
189
-
190
-    /**
191
-     * used to set the $_validators property
192
-     *
193
-     * @return void
194
-     * @throws ReflectionException
195
-     */
196
-    private function _set_validators()
197
-    {
198
-        // let's get all valid shortcodes from mt and message type
199
-        // (messenger will have its set in the _validator_config property for the messenger)
200
-        $mt_codes = $this->_message_type->get_valid_shortcodes();
201
-
202
-
203
-        // get messenger validator_config
204
-        $msgr_validator = $this->_messenger->get_validator_config();
205
-
206
-
207
-        // we only want the valid shortcodes for the given context!
208
-        $context  = $this->_context;
209
-        $mt_codes = $mt_codes[ $context ];
210
-
211
-        // in this first loop we're just getting all shortcode group indexes from the msgr_validator
212
-        // into a single array (so we can get the appropriate shortcode objects for the groups)
213
-        $shortcode_groups = $mt_codes;
214
-        $groups_per_field = [];
215
-
216
-        foreach ($msgr_validator as $field => $config) {
217
-            if (empty($config) || ! isset($config['shortcodes'])) {
218
-                continue;
219
-            }  //Nothing to see here.
220
-            $groups_per_field[ $field ] = array_intersect($config['shortcodes'], $mt_codes);
221
-            $shortcode_groups           = array_merge($config['shortcodes'], $shortcode_groups);
222
-        }
223
-
224
-        $shortcode_groups = array_unique($shortcode_groups);
225
-
226
-        // okay now we've got our groups.
227
-        // Let's get the codes from the objects into an array indexed by group for easy retrieval later.
228
-        $codes_from_objs = [];
229
-
230
-        foreach ($shortcode_groups as $group) {
231
-            $ref       = ucwords(str_replace('_', ' ', $group));
232
-            $ref       = str_replace(' ', '_', $ref);
233
-            $classname = 'EE_' . $ref . '_Shortcodes';
234
-            if (class_exists($classname)) {
235
-                $a                         = new ReflectionClass($classname);
236
-                $obj                       = $a->newInstance();
237
-                $codes_from_objs[ $group ] = $obj->get_shortcodes();
238
-            }
239
-        }
240
-
241
-
242
-        // let's just replace the $mt shortcode group indexes with the actual shortcodes (unique)
243
-        $final_mt_codes = [];
244
-        foreach ($mt_codes as $group) {
245
-            $final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[ $group ]);
246
-        }
247
-
248
-        $mt_codes = $final_mt_codes;
249
-
250
-
251
-        // k now in this next loop we're going to loop through $msgr_validator again
252
-        // and setup the _validators property from the data we've setup so far.
253
-        foreach ($msgr_validator as $field => $config) {
254
-            // if required shortcode is not in our list of codes for the given field, then we skip this field.
255
-            $required = isset($config['required'])
256
-                ? array_intersect($config['required'], array_keys($mt_codes))
257
-                : true;
258
-            if (empty($required)) {
259
-                continue;
260
-            }
261
-
262
-            // If we have an override then we use it to indicate the codes we want.
263
-            if (isset($this->_valid_shortcodes_modifier[ $context ][ $field ])) {
264
-                $this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
265
-                    $this->_valid_shortcodes_modifier[ $context ][ $field ],
266
-                    $codes_from_objs
267
-                );
268
-            } elseif (isset($groups_per_field[ $field ])) {
269
-                // we have specific shortcodes for a field so we need to use them
270
-                $this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
-                    $groups_per_field[ $field ],
272
-                    $codes_from_objs
273
-                );
274
-            } elseif (empty($config)) {
275
-                // no config so we're assuming we're just going to use the shortcodes from the message type context
276
-                $this->_validators[ $field ]['shortcodes'] = $mt_codes;
277
-            } elseif (isset($config['specific_shortcodes'])) {
278
-                // we have specific shortcodes so we need to use them
279
-                $this->_validators[ $field ]['shortcodes'] = $config['specific_shortcodes'];
280
-            } else {
281
-                // otherwise the shortcodes are what is set by the messenger for that field
282
-                foreach ($config['shortcodes'] as $group) {
283
-                    $this->_validators[ $field ]['shortcodes'] = isset($this->_validators[ $field ]['shortcodes'])
284
-                        ? array_merge($this->_validators[ $field ]['shortcodes'], $codes_from_objs[ $group ])
285
-                        : $codes_from_objs[ $group ];
286
-                }
287
-            }
288
-
289
-            // now let's just make sure that any excluded specific shortcodes are removed.
290
-            $specific_excludes = $this->get_specific_shortcode_excludes();
291
-            if (isset($specific_excludes[ $field ])) {
292
-                foreach ($specific_excludes[ $field ] as $sex) {
293
-                    if (isset($this->_validators[ $field ]['shortcodes'][ $sex ])) {
294
-                        unset($this->_validators[ $field ]['shortcodes'][ $sex ]);
295
-                    }
296
-                }
297
-            }
298
-
299
-            // hey! don't forget to include the type if present!
300
-            $this->_validators[ $field ]['type'] =
301
-                isset($config['type'])
302
-                    ? $config['type']
303
-                    : null;
304
-        }
305
-    }
306
-
307
-
308
-    /**
309
-     * This just returns the validators property that contains information
310
-     * about the various shortcodes and their availability with each field
311
-     *
312
-     * @return array
313
-     */
314
-    public function get_validators()
315
-    {
316
-        return $this->_validators;
317
-    }
318
-
319
-
320
-    /**
321
-     * This simply returns the specific shortcode_excludes property that is set.
322
-     *
323
-     * @return array
324
-     * @since 4.5.0
325
-     */
326
-    public function get_specific_shortcode_excludes()
327
-    {
328
-        // specific validator filter
329
-        $shortcode_excludes = apply_filters(
330
-            'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
331
-            $this->_specific_shortcode_excludes,
332
-            $this->_context
333
-        );
334
-        // global filter
335
-        return apply_filters(
336
-            'FHEE__EE_Messages_Validator__get_specific_shortcode_excludes',
337
-            $shortcode_excludes,
338
-            $this->_context,
339
-            $this
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * This is the main method that handles validation
346
-     * What it does is loop through the _fields (the ones that get validated)
347
-     * and checks them against the shortcodes array for the field and the 'type' indicated by the
348
-     *
349
-     * @return array|bool if errors present we return the array otherwise true
350
-     */
351
-    public function validate()
352
-    {
353
-        // some defaults
354
-        $template_fields = $this->_messenger->get_template_fields();
355
-        // loop through the fields and check!
356
-        foreach ($this->_fields as $field => $value) {
357
-            $this->_errors[ $field ] = [];
358
-            $err_msg                 = '';
359
-            $field_label             = '';
360
-            // if field is not present in the _validators array then we continue
361
-            if (! isset($this->_validators[ $field ])) {
362
-                unset($this->_errors[ $field ]);
363
-                continue;
364
-            }
365
-
366
-            // get the translated field label!
367
-            // first check if it's in the main fields list
368
-            if (isset($template_fields[ $field ])) {
369
-                // most likely the field is found in the 'extra' array.
370
-                $field_label = ! empty($template_fields[ $field ])
371
-                    ? $template_fields[ $field ]['label']
372
-                    : $field;
373
-            }
374
-
375
-            // if field label is empty OR is equal to the current field
376
-            // then we need to loop through the 'extra' fields in the template_fields config (if present)
377
-            if (isset($template_fields['extra']) && (empty($field_label) || $field_label === $field)) {
378
-                foreach ($template_fields['extra'] as $main_field => $secondary_field) {
379
-                    foreach ($secondary_field as $name => $values) {
380
-                        if ($name === $field) {
381
-                            $field_label = $values['label'];
382
-                        }
383
-
384
-                        // if we've got a 'main' secondary field, let's see if that matches what field we're on
385
-                        // which means it contains the label for this field.
386
-                        if ($name === 'main' && $main_field === $field_label) {
387
-                            $field_label = $values['label'];
388
-                        }
389
-                    }
390
-                }
391
-            }
392
-
393
-            // field is present. Let's validate shortcodes first (but only if shortcodes present).
394
-            if (
395
-                isset($this->_validators[ $field ]['shortcodes'])
396
-                && ! empty($this->_validators[ $field ]['shortcodes'])
397
-            ) {
398
-                $invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[ $field ]['shortcodes']);
399
-                // if true then that means there is a returned error message
400
-                // that we'll need to add to the _errors array for this field.
401
-                if ($invalid_shortcodes) {
402
-                    $v_s     = array_keys($this->_validators[ $field ]['shortcodes']);
403
-                    $err_msg = sprintf(
404
-                        esc_html__(
405
-                            '%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
406
-                            'event_espresso'
407
-                        ),
408
-                        '<strong>' . $field_label . '</strong>',
409
-                        $invalid_shortcodes,
410
-                        '<p>',
411
-                        '</p >'
412
-                    );
413
-                    $err_msg .= sprintf(
414
-                        esc_html__('%2$sValid shortcodes for this field are: %1$s%3$s', 'event_espresso'),
415
-                        implode(', ', $v_s),
416
-                        '<strong>',
417
-                        '</strong>'
418
-                    );
419
-                }
420
-            }
421
-
422
-            // if there's a "type" to be validated then let's do that too.
423
-            if (isset($this->_validators[ $field ]['type']) && ! empty($this->_validators[ $field ]['type'])) {
424
-                switch ($this->_validators[ $field ]['type']) {
425
-                    case 'number':
426
-                        if (! is_numeric($value)) {
427
-                            $err_msg .= sprintf(
428
-                                esc_html__(
429
-                                    '%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
430
-                                    'event_espresso'
431
-                                ),
432
-                                $field_label,
433
-                                $value,
434
-                                '<p>',
435
-                                '</p >'
436
-                            );
437
-                        }
438
-                        break;
439
-                    case 'email':
440
-                        $valid_email = $this->_validate_email($value);
441
-                        if (! $valid_email) {
442
-                            $err_msg .= htmlentities(
443
-                                sprintf(
444
-                                    esc_html__(
445
-                                        'The %1$s field has at least one string that is not a valid email address record.  Valid emails are in the format: "Name <[email protected]>" or "[email protected]" and multiple emails can be separated by a comma.',
446
-                                        'event_espresso'
447
-                                    ),
448
-                                    $field_label
449
-                                )
450
-                            );
451
-                        }
452
-                        break;
453
-                    default:
454
-                        break;
455
-                }
456
-            }
457
-
458
-            // if $err_msg isn't empty let's setup the _errors array for this field.
459
-            if (! empty($err_msg)) {
460
-                $this->_errors[ $field ]['msg'] = $err_msg;
461
-            } else {
462
-                unset($this->_errors[ $field ]);
463
-            }
464
-        }
465
-
466
-        // if we have ANY errors, then we want to make sure we return the values
467
-        // for ALL the fields so the user doesn't have to retype them all.
468
-        if (! empty($this->_errors)) {
469
-            foreach ($this->_fields as $field => $value) {
470
-                $this->_errors[ $field ]['value'] = stripslashes($value);
471
-            }
472
-        }
473
-
474
-        // return any errors or just TRUE if everything validates
475
-        return empty($this->_errors)
476
-            ? true
477
-            : $this->_errors;
478
-    }
479
-
480
-
481
-    /**
482
-     * Reassembles and returns an array of valid shortcodes
483
-     * given the array of groups and array of shortcodes indexed by group.
484
-     *
485
-     * @param array $groups          array of shortcode groups that we want shortcodes for
486
-     * @param array $codes_from_objs All the codes available.
487
-     * @return array                   an array of actual shortcodes (that will be used for validation).
488
-     */
489
-    private function _reassemble_valid_shortcodes_from_group($groups, $codes_from_objs)
490
-    {
491
-        $shortcodes = [];
492
-        foreach ($groups as $group) {
493
-            $shortcodes = array_merge($shortcodes, $codes_from_objs[ $group ]);
494
-        }
495
-        return $shortcodes;
496
-    }
497
-
498
-
499
-    /**
500
-     * Validates a string against a list of accepted shortcodes
501
-     * This function takes in an array of shortcodes
502
-     * and makes sure that the given string ONLY contains shortcodes in that array.
503
-     *
504
-     * @param string $value            string to evaluate
505
-     * @param array  $valid_shortcodes array of shortcodes that are acceptable.
506
-     * @return bool|string  return either a list of invalid shortcodes OR false if the shortcodes validate.
507
-     */
508
-    protected function _invalid_shortcodes($value, $valid_shortcodes)
509
-    {
510
-        // first we need to go through the string and get the shortcodes in the string
511
-        preg_match_all('/(\[.+?\])/', $value, $matches);
512
-        $incoming_shortcodes = (array) $matches[0];
513
-
514
-        // get a diff of the shortcodes in the string vs the valid shortcodes
515
-        $diff = array_diff($incoming_shortcodes, array_keys($valid_shortcodes));
516
-
517
-        // we need to account for custom codes so let's loop through the diff and remove any of those type of codes
518
-        foreach ($diff as $ind => $code) {
519
-            if (preg_match('/(\[[A-Za-z0-9\_]+_\*)/', $code)) {
520
-                // strip the shortcode so we just have the BASE string (i.e. [ANSWER_*] )
521
-                $dynamic_sc = preg_replace('/(_\*+.+)/', '_*]', $code);
522
-                // does this exist in the $valid_shortcodes?  If so then unset.
523
-                if (isset($valid_shortcodes[ $dynamic_sc ])) {
524
-                    unset($diff[ $ind ]);
525
-                }
526
-            }
527
-        }
528
-
529
-        if (empty($diff)) {
530
-            return false;
531
-        } //there is no diff, we have no invalid shortcodes, so return
532
-
533
-        // made it here? then let's assemble the error message
534
-        $invalid_shortcodes = implode('</strong>,<strong>', $diff);
535
-        return '<strong>' . $invalid_shortcodes . '</strong>';
536
-    }
537
-
538
-
539
-    /**
540
-     * Validates an incoming string and makes sure we have valid emails in the string.
541
-     *
542
-     * @param string $value incoming value to validate
543
-     * @return bool        true if the string validates, false if it doesn't
544
-     */
545
-    protected function _validate_email($value)
546
-    {
547
-        $validate = true;
548
-        $or_val   = $value;
549
-
550
-        // empty strings will validate because this is how a message template
551
-        // for a particular context can be "turned off" (if there is no email then no message)
552
-        if (empty($value)) {
553
-            return $validate;
554
-        }
555
-
556
-        // first determine if there ARE any shortcodes.
557
-        // If there are shortcodes and then later we find that there were no other valid emails
558
-        // but the field isn't empty...
559
-        // that means we've got extra commas that were left after stripping out shortcodes so probably still valid.
560
-        $has_shortcodes = preg_match('/(\[.+?\])/', $value);
561
-
562
-        // first we need to strip out all the shortcodes!
563
-        $value = preg_replace('/(\[.+?\])/', '', $value);
564
-
565
-        // if original value is not empty and new value is, then we've parsed out a shortcode
566
-        // and we now have an empty string which DOES validate.
567
-        // We also validate complete empty field for email because
568
-        // its possible that this message is being "turned off" for a particular context
569
-
570
-
571
-        if (! empty($or_val) && empty($value)) {
572
-            return $validate;
573
-        }
574
-
575
-        // trim any commas from beginning and end of string ( after whitespace trimmed );
576
-        $value = trim(trim($value), ',');
577
-
578
-
579
-        // next we need to split up the string if its comma delimited.
580
-        $emails = explode(',', $value);
581
-        $empty  = false; // used to indicate that there is an empty comma.
582
-        // now let's loop through the emails and do our checks
583
-        foreach ($emails as $email) {
584
-            if (empty($email)) {
585
-                $empty = true;
586
-                continue;
587
-            }
588
-
589
-            // trim whitespace
590
-            $email = trim($email);
591
-            // either its of type "[email protected]", or its of type "fname lname <[email protected]>"
592
-            if (is_email($email)) {
593
-                continue;
594
-            }
595
-            $matches  = [];
596
-            $validate = (bool) preg_match('/(.*)<(.+)>/', $email, $matches);
597
-            if ($validate && is_email($matches[2])) {
598
-                continue;
599
-            }
600
-            return false;
601
-        }
602
-
603
-        return $empty && ! $has_shortcodes
604
-            ? false
605
-            : $validate;
606
-    }
607
-
608
-
609
-    /**
610
-     * Magic getter
611
-     * Using this to provide back compat with add-ons referencing deprecated properties.
612
-     *
613
-     * @param string $property Property being requested
614
-     * @return mixed
615
-     * @throws Exception
616
-     */
617
-    public function __get($property)
618
-    {
619
-        $expected_properties_map = [
620
-            /**
621
-             * @deprecated 4.9.0
622
-             */
623
-            '_MSGR'   => '_messenger',
624
-            /**
625
-             * @deprecated 4.9.0
626
-             */
627
-            '_MSGTYP' => '_message_type',
628
-        ];
629
-
630
-        if (isset($expected_properties_map[ $property ])) {
631
-            return $this->{$expected_properties_map[ $property ]};
632
-        }
633
-
634
-        throw new Exception(
635
-            sprintf(
636
-                esc_html__('The property %1$s being requested on %2$s does not exist', 'event_espresso'),
637
-                $property,
638
-                get_class($this)
639
-            )
640
-        );
641
-    }
20
+	/**
21
+	 * These properties just hold the name for the Messenger and Message Type (defined by child classes).
22
+	 * These are used for retrieving objects etc.
23
+	 *
24
+	 * @var string
25
+	 */
26
+	protected $_m_name;
27
+
28
+	protected $_mt_name;
29
+
30
+
31
+	/**
32
+	 * This will hold any error messages from the validation process.
33
+	 * The _errors property holds an associative array of error messages
34
+	 * listing the field as the key and the message as the value.
35
+	 *
36
+	 * @var array()
37
+	 */
38
+	private $_errors = [];
39
+
40
+
41
+	/**
42
+	 * holds an array of fields being validated
43
+	 *
44
+	 * @var array
45
+	 */
46
+	protected $_fields;
47
+
48
+
49
+	/**
50
+	 * this will hold the incoming context
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_context;
55
+
56
+
57
+	/**
58
+	 * this holds an array of fields and the relevant validation information
59
+	 * that the incoming fields data get validated against.
60
+	 * This gets setup in the _set_props() method.
61
+	 *
62
+	 * @var array
63
+	 */
64
+	protected $_validators;
65
+
66
+
67
+	/**
68
+	 * holds the messenger object
69
+	 *
70
+	 * @var object
71
+	 */
72
+	protected $_messenger;
73
+
74
+
75
+	/**
76
+	 * holds the message type object
77
+	 *
78
+	 * @var object
79
+	 */
80
+	protected $_message_type;
81
+
82
+
83
+	/**
84
+	 * will hold any valid_shortcode modifications made by the _modify_validator() method.
85
+	 *
86
+	 * @var array
87
+	 */
88
+	protected $_valid_shortcodes_modifier;
89
+
90
+
91
+	/**
92
+	 * There may be times where a message type wants to include a shortcode group but exclude specific
93
+	 * shortcodes.  If that's the case then it can set this property as an array of shortcodes to exclude and
94
+	 * they will not be allowed.
95
+	 * Array should be indexed by field and values are an array of specific shortcodes to exclude.
96
+	 *
97
+	 * @var array
98
+	 */
99
+	protected $_specific_shortcode_excludes = [];
100
+
101
+
102
+	/**
103
+	 * Runs the validator using the incoming fields array as the fields/values to check.
104
+	 *
105
+	 * @param array $fields The fields sent by the EEM object.
106
+	 * @param       $context
107
+	 * @throws EE_Error
108
+	 * @throws ReflectionException
109
+	 */
110
+	public function __construct($fields, $context)
111
+	{
112
+		// check that _m_name and _mt_name have been set by child class otherwise we get out.
113
+		if (empty($this->_m_name) || empty($this->_mt_name)) {
114
+			throw new EE_Error(
115
+				esc_html__(
116
+					'EE_Messages_Validator child classes MUST set the $_m_name and $_mt_name property.  Check that the child class is doing this',
117
+					'event_espresso'
118
+				)
119
+			);
120
+		}
121
+		$this->_fields  = $fields;
122
+		$this->_context = $context;
123
+
124
+		// load messenger and message_type objects and the related shortcode objects.
125
+		$this->_load_objects();
126
+
127
+
128
+		// modify any messenger/message_type specific validation instructions.  This is what child classes define.
129
+		$this->_modify_validator();
130
+
131
+
132
+		// let's set validators property
133
+		$this->_set_validators();
134
+	}
135
+
136
+
137
+	/**
138
+	 * Child classes instantiate this and use it to modify the _validator_config array property
139
+	 * for the messenger using messengers set_validate_config() method.
140
+	 * This is so we can specify specific validation instructions for a messenger/message_type combo
141
+	 * that aren't handled by the defaults setup in the messenger.
142
+	 *
143
+	 * @abstract
144
+	 * @return void
145
+	 */
146
+	abstract protected function _modify_validator();
147
+
148
+
149
+	/**
150
+	 * loads all objects used by validator
151
+	 *
152
+	 * @throws EE_Error
153
+	 */
154
+	private function _load_objects()
155
+	{
156
+		// load messenger
157
+		$messenger = ucwords(str_replace('_', ' ', $this->_m_name));
158
+		$messenger = str_replace(' ', '_', $messenger);
159
+		$messenger = 'EE_' . $messenger . '_messenger';
160
+
161
+		if (! class_exists($messenger)) {
162
+			throw new EE_Error(
163
+				sprintf(
164
+					esc_html__('There is no messenger class for the given string (%s)', 'event_espresso'),
165
+					$this->_m_name
166
+				)
167
+			);
168
+		}
169
+
170
+		$this->_messenger = new $messenger();
171
+
172
+		// load message type
173
+		$message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
174
+		$message_type = str_replace(' ', '_', $message_type);
175
+		$message_type = 'EE_' . $message_type . '_message_type';
176
+
177
+		if (! class_exists($message_type)) {
178
+			throw new EE_Error(
179
+				sprintf(
180
+					esc_html__('There is no message type class for the given string (%s)', 'event_espresso'),
181
+					$this->_mt_name
182
+				)
183
+			);
184
+		}
185
+
186
+		$this->_message_type = new $message_type();
187
+	}
188
+
189
+
190
+	/**
191
+	 * used to set the $_validators property
192
+	 *
193
+	 * @return void
194
+	 * @throws ReflectionException
195
+	 */
196
+	private function _set_validators()
197
+	{
198
+		// let's get all valid shortcodes from mt and message type
199
+		// (messenger will have its set in the _validator_config property for the messenger)
200
+		$mt_codes = $this->_message_type->get_valid_shortcodes();
201
+
202
+
203
+		// get messenger validator_config
204
+		$msgr_validator = $this->_messenger->get_validator_config();
205
+
206
+
207
+		// we only want the valid shortcodes for the given context!
208
+		$context  = $this->_context;
209
+		$mt_codes = $mt_codes[ $context ];
210
+
211
+		// in this first loop we're just getting all shortcode group indexes from the msgr_validator
212
+		// into a single array (so we can get the appropriate shortcode objects for the groups)
213
+		$shortcode_groups = $mt_codes;
214
+		$groups_per_field = [];
215
+
216
+		foreach ($msgr_validator as $field => $config) {
217
+			if (empty($config) || ! isset($config['shortcodes'])) {
218
+				continue;
219
+			}  //Nothing to see here.
220
+			$groups_per_field[ $field ] = array_intersect($config['shortcodes'], $mt_codes);
221
+			$shortcode_groups           = array_merge($config['shortcodes'], $shortcode_groups);
222
+		}
223
+
224
+		$shortcode_groups = array_unique($shortcode_groups);
225
+
226
+		// okay now we've got our groups.
227
+		// Let's get the codes from the objects into an array indexed by group for easy retrieval later.
228
+		$codes_from_objs = [];
229
+
230
+		foreach ($shortcode_groups as $group) {
231
+			$ref       = ucwords(str_replace('_', ' ', $group));
232
+			$ref       = str_replace(' ', '_', $ref);
233
+			$classname = 'EE_' . $ref . '_Shortcodes';
234
+			if (class_exists($classname)) {
235
+				$a                         = new ReflectionClass($classname);
236
+				$obj                       = $a->newInstance();
237
+				$codes_from_objs[ $group ] = $obj->get_shortcodes();
238
+			}
239
+		}
240
+
241
+
242
+		// let's just replace the $mt shortcode group indexes with the actual shortcodes (unique)
243
+		$final_mt_codes = [];
244
+		foreach ($mt_codes as $group) {
245
+			$final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[ $group ]);
246
+		}
247
+
248
+		$mt_codes = $final_mt_codes;
249
+
250
+
251
+		// k now in this next loop we're going to loop through $msgr_validator again
252
+		// and setup the _validators property from the data we've setup so far.
253
+		foreach ($msgr_validator as $field => $config) {
254
+			// if required shortcode is not in our list of codes for the given field, then we skip this field.
255
+			$required = isset($config['required'])
256
+				? array_intersect($config['required'], array_keys($mt_codes))
257
+				: true;
258
+			if (empty($required)) {
259
+				continue;
260
+			}
261
+
262
+			// If we have an override then we use it to indicate the codes we want.
263
+			if (isset($this->_valid_shortcodes_modifier[ $context ][ $field ])) {
264
+				$this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
265
+					$this->_valid_shortcodes_modifier[ $context ][ $field ],
266
+					$codes_from_objs
267
+				);
268
+			} elseif (isset($groups_per_field[ $field ])) {
269
+				// we have specific shortcodes for a field so we need to use them
270
+				$this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
+					$groups_per_field[ $field ],
272
+					$codes_from_objs
273
+				);
274
+			} elseif (empty($config)) {
275
+				// no config so we're assuming we're just going to use the shortcodes from the message type context
276
+				$this->_validators[ $field ]['shortcodes'] = $mt_codes;
277
+			} elseif (isset($config['specific_shortcodes'])) {
278
+				// we have specific shortcodes so we need to use them
279
+				$this->_validators[ $field ]['shortcodes'] = $config['specific_shortcodes'];
280
+			} else {
281
+				// otherwise the shortcodes are what is set by the messenger for that field
282
+				foreach ($config['shortcodes'] as $group) {
283
+					$this->_validators[ $field ]['shortcodes'] = isset($this->_validators[ $field ]['shortcodes'])
284
+						? array_merge($this->_validators[ $field ]['shortcodes'], $codes_from_objs[ $group ])
285
+						: $codes_from_objs[ $group ];
286
+				}
287
+			}
288
+
289
+			// now let's just make sure that any excluded specific shortcodes are removed.
290
+			$specific_excludes = $this->get_specific_shortcode_excludes();
291
+			if (isset($specific_excludes[ $field ])) {
292
+				foreach ($specific_excludes[ $field ] as $sex) {
293
+					if (isset($this->_validators[ $field ]['shortcodes'][ $sex ])) {
294
+						unset($this->_validators[ $field ]['shortcodes'][ $sex ]);
295
+					}
296
+				}
297
+			}
298
+
299
+			// hey! don't forget to include the type if present!
300
+			$this->_validators[ $field ]['type'] =
301
+				isset($config['type'])
302
+					? $config['type']
303
+					: null;
304
+		}
305
+	}
306
+
307
+
308
+	/**
309
+	 * This just returns the validators property that contains information
310
+	 * about the various shortcodes and their availability with each field
311
+	 *
312
+	 * @return array
313
+	 */
314
+	public function get_validators()
315
+	{
316
+		return $this->_validators;
317
+	}
318
+
319
+
320
+	/**
321
+	 * This simply returns the specific shortcode_excludes property that is set.
322
+	 *
323
+	 * @return array
324
+	 * @since 4.5.0
325
+	 */
326
+	public function get_specific_shortcode_excludes()
327
+	{
328
+		// specific validator filter
329
+		$shortcode_excludes = apply_filters(
330
+			'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
331
+			$this->_specific_shortcode_excludes,
332
+			$this->_context
333
+		);
334
+		// global filter
335
+		return apply_filters(
336
+			'FHEE__EE_Messages_Validator__get_specific_shortcode_excludes',
337
+			$shortcode_excludes,
338
+			$this->_context,
339
+			$this
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * This is the main method that handles validation
346
+	 * What it does is loop through the _fields (the ones that get validated)
347
+	 * and checks them against the shortcodes array for the field and the 'type' indicated by the
348
+	 *
349
+	 * @return array|bool if errors present we return the array otherwise true
350
+	 */
351
+	public function validate()
352
+	{
353
+		// some defaults
354
+		$template_fields = $this->_messenger->get_template_fields();
355
+		// loop through the fields and check!
356
+		foreach ($this->_fields as $field => $value) {
357
+			$this->_errors[ $field ] = [];
358
+			$err_msg                 = '';
359
+			$field_label             = '';
360
+			// if field is not present in the _validators array then we continue
361
+			if (! isset($this->_validators[ $field ])) {
362
+				unset($this->_errors[ $field ]);
363
+				continue;
364
+			}
365
+
366
+			// get the translated field label!
367
+			// first check if it's in the main fields list
368
+			if (isset($template_fields[ $field ])) {
369
+				// most likely the field is found in the 'extra' array.
370
+				$field_label = ! empty($template_fields[ $field ])
371
+					? $template_fields[ $field ]['label']
372
+					: $field;
373
+			}
374
+
375
+			// if field label is empty OR is equal to the current field
376
+			// then we need to loop through the 'extra' fields in the template_fields config (if present)
377
+			if (isset($template_fields['extra']) && (empty($field_label) || $field_label === $field)) {
378
+				foreach ($template_fields['extra'] as $main_field => $secondary_field) {
379
+					foreach ($secondary_field as $name => $values) {
380
+						if ($name === $field) {
381
+							$field_label = $values['label'];
382
+						}
383
+
384
+						// if we've got a 'main' secondary field, let's see if that matches what field we're on
385
+						// which means it contains the label for this field.
386
+						if ($name === 'main' && $main_field === $field_label) {
387
+							$field_label = $values['label'];
388
+						}
389
+					}
390
+				}
391
+			}
392
+
393
+			// field is present. Let's validate shortcodes first (but only if shortcodes present).
394
+			if (
395
+				isset($this->_validators[ $field ]['shortcodes'])
396
+				&& ! empty($this->_validators[ $field ]['shortcodes'])
397
+			) {
398
+				$invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[ $field ]['shortcodes']);
399
+				// if true then that means there is a returned error message
400
+				// that we'll need to add to the _errors array for this field.
401
+				if ($invalid_shortcodes) {
402
+					$v_s     = array_keys($this->_validators[ $field ]['shortcodes']);
403
+					$err_msg = sprintf(
404
+						esc_html__(
405
+							'%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
406
+							'event_espresso'
407
+						),
408
+						'<strong>' . $field_label . '</strong>',
409
+						$invalid_shortcodes,
410
+						'<p>',
411
+						'</p >'
412
+					);
413
+					$err_msg .= sprintf(
414
+						esc_html__('%2$sValid shortcodes for this field are: %1$s%3$s', 'event_espresso'),
415
+						implode(', ', $v_s),
416
+						'<strong>',
417
+						'</strong>'
418
+					);
419
+				}
420
+			}
421
+
422
+			// if there's a "type" to be validated then let's do that too.
423
+			if (isset($this->_validators[ $field ]['type']) && ! empty($this->_validators[ $field ]['type'])) {
424
+				switch ($this->_validators[ $field ]['type']) {
425
+					case 'number':
426
+						if (! is_numeric($value)) {
427
+							$err_msg .= sprintf(
428
+								esc_html__(
429
+									'%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
430
+									'event_espresso'
431
+								),
432
+								$field_label,
433
+								$value,
434
+								'<p>',
435
+								'</p >'
436
+							);
437
+						}
438
+						break;
439
+					case 'email':
440
+						$valid_email = $this->_validate_email($value);
441
+						if (! $valid_email) {
442
+							$err_msg .= htmlentities(
443
+								sprintf(
444
+									esc_html__(
445
+										'The %1$s field has at least one string that is not a valid email address record.  Valid emails are in the format: "Name <[email protected]>" or "[email protected]" and multiple emails can be separated by a comma.',
446
+										'event_espresso'
447
+									),
448
+									$field_label
449
+								)
450
+							);
451
+						}
452
+						break;
453
+					default:
454
+						break;
455
+				}
456
+			}
457
+
458
+			// if $err_msg isn't empty let's setup the _errors array for this field.
459
+			if (! empty($err_msg)) {
460
+				$this->_errors[ $field ]['msg'] = $err_msg;
461
+			} else {
462
+				unset($this->_errors[ $field ]);
463
+			}
464
+		}
465
+
466
+		// if we have ANY errors, then we want to make sure we return the values
467
+		// for ALL the fields so the user doesn't have to retype them all.
468
+		if (! empty($this->_errors)) {
469
+			foreach ($this->_fields as $field => $value) {
470
+				$this->_errors[ $field ]['value'] = stripslashes($value);
471
+			}
472
+		}
473
+
474
+		// return any errors or just TRUE if everything validates
475
+		return empty($this->_errors)
476
+			? true
477
+			: $this->_errors;
478
+	}
479
+
480
+
481
+	/**
482
+	 * Reassembles and returns an array of valid shortcodes
483
+	 * given the array of groups and array of shortcodes indexed by group.
484
+	 *
485
+	 * @param array $groups          array of shortcode groups that we want shortcodes for
486
+	 * @param array $codes_from_objs All the codes available.
487
+	 * @return array                   an array of actual shortcodes (that will be used for validation).
488
+	 */
489
+	private function _reassemble_valid_shortcodes_from_group($groups, $codes_from_objs)
490
+	{
491
+		$shortcodes = [];
492
+		foreach ($groups as $group) {
493
+			$shortcodes = array_merge($shortcodes, $codes_from_objs[ $group ]);
494
+		}
495
+		return $shortcodes;
496
+	}
497
+
498
+
499
+	/**
500
+	 * Validates a string against a list of accepted shortcodes
501
+	 * This function takes in an array of shortcodes
502
+	 * and makes sure that the given string ONLY contains shortcodes in that array.
503
+	 *
504
+	 * @param string $value            string to evaluate
505
+	 * @param array  $valid_shortcodes array of shortcodes that are acceptable.
506
+	 * @return bool|string  return either a list of invalid shortcodes OR false if the shortcodes validate.
507
+	 */
508
+	protected function _invalid_shortcodes($value, $valid_shortcodes)
509
+	{
510
+		// first we need to go through the string and get the shortcodes in the string
511
+		preg_match_all('/(\[.+?\])/', $value, $matches);
512
+		$incoming_shortcodes = (array) $matches[0];
513
+
514
+		// get a diff of the shortcodes in the string vs the valid shortcodes
515
+		$diff = array_diff($incoming_shortcodes, array_keys($valid_shortcodes));
516
+
517
+		// we need to account for custom codes so let's loop through the diff and remove any of those type of codes
518
+		foreach ($diff as $ind => $code) {
519
+			if (preg_match('/(\[[A-Za-z0-9\_]+_\*)/', $code)) {
520
+				// strip the shortcode so we just have the BASE string (i.e. [ANSWER_*] )
521
+				$dynamic_sc = preg_replace('/(_\*+.+)/', '_*]', $code);
522
+				// does this exist in the $valid_shortcodes?  If so then unset.
523
+				if (isset($valid_shortcodes[ $dynamic_sc ])) {
524
+					unset($diff[ $ind ]);
525
+				}
526
+			}
527
+		}
528
+
529
+		if (empty($diff)) {
530
+			return false;
531
+		} //there is no diff, we have no invalid shortcodes, so return
532
+
533
+		// made it here? then let's assemble the error message
534
+		$invalid_shortcodes = implode('</strong>,<strong>', $diff);
535
+		return '<strong>' . $invalid_shortcodes . '</strong>';
536
+	}
537
+
538
+
539
+	/**
540
+	 * Validates an incoming string and makes sure we have valid emails in the string.
541
+	 *
542
+	 * @param string $value incoming value to validate
543
+	 * @return bool        true if the string validates, false if it doesn't
544
+	 */
545
+	protected function _validate_email($value)
546
+	{
547
+		$validate = true;
548
+		$or_val   = $value;
549
+
550
+		// empty strings will validate because this is how a message template
551
+		// for a particular context can be "turned off" (if there is no email then no message)
552
+		if (empty($value)) {
553
+			return $validate;
554
+		}
555
+
556
+		// first determine if there ARE any shortcodes.
557
+		// If there are shortcodes and then later we find that there were no other valid emails
558
+		// but the field isn't empty...
559
+		// that means we've got extra commas that were left after stripping out shortcodes so probably still valid.
560
+		$has_shortcodes = preg_match('/(\[.+?\])/', $value);
561
+
562
+		// first we need to strip out all the shortcodes!
563
+		$value = preg_replace('/(\[.+?\])/', '', $value);
564
+
565
+		// if original value is not empty and new value is, then we've parsed out a shortcode
566
+		// and we now have an empty string which DOES validate.
567
+		// We also validate complete empty field for email because
568
+		// its possible that this message is being "turned off" for a particular context
569
+
570
+
571
+		if (! empty($or_val) && empty($value)) {
572
+			return $validate;
573
+		}
574
+
575
+		// trim any commas from beginning and end of string ( after whitespace trimmed );
576
+		$value = trim(trim($value), ',');
577
+
578
+
579
+		// next we need to split up the string if its comma delimited.
580
+		$emails = explode(',', $value);
581
+		$empty  = false; // used to indicate that there is an empty comma.
582
+		// now let's loop through the emails and do our checks
583
+		foreach ($emails as $email) {
584
+			if (empty($email)) {
585
+				$empty = true;
586
+				continue;
587
+			}
588
+
589
+			// trim whitespace
590
+			$email = trim($email);
591
+			// either its of type "[email protected]", or its of type "fname lname <[email protected]>"
592
+			if (is_email($email)) {
593
+				continue;
594
+			}
595
+			$matches  = [];
596
+			$validate = (bool) preg_match('/(.*)<(.+)>/', $email, $matches);
597
+			if ($validate && is_email($matches[2])) {
598
+				continue;
599
+			}
600
+			return false;
601
+		}
602
+
603
+		return $empty && ! $has_shortcodes
604
+			? false
605
+			: $validate;
606
+	}
607
+
608
+
609
+	/**
610
+	 * Magic getter
611
+	 * Using this to provide back compat with add-ons referencing deprecated properties.
612
+	 *
613
+	 * @param string $property Property being requested
614
+	 * @return mixed
615
+	 * @throws Exception
616
+	 */
617
+	public function __get($property)
618
+	{
619
+		$expected_properties_map = [
620
+			/**
621
+			 * @deprecated 4.9.0
622
+			 */
623
+			'_MSGR'   => '_messenger',
624
+			/**
625
+			 * @deprecated 4.9.0
626
+			 */
627
+			'_MSGTYP' => '_message_type',
628
+		];
629
+
630
+		if (isset($expected_properties_map[ $property ])) {
631
+			return $this->{$expected_properties_map[ $property ]};
632
+		}
633
+
634
+		throw new Exception(
635
+			sprintf(
636
+				esc_html__('The property %1$s being requested on %2$s does not exist', 'event_espresso'),
637
+				$property,
638
+				get_class($this)
639
+			)
640
+		);
641
+	}
642 642
 }
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
         // load messenger
157 157
         $messenger = ucwords(str_replace('_', ' ', $this->_m_name));
158 158
         $messenger = str_replace(' ', '_', $messenger);
159
-        $messenger = 'EE_' . $messenger . '_messenger';
159
+        $messenger = 'EE_'.$messenger.'_messenger';
160 160
 
161
-        if (! class_exists($messenger)) {
161
+        if ( ! class_exists($messenger)) {
162 162
             throw new EE_Error(
163 163
                 sprintf(
164 164
                     esc_html__('There is no messenger class for the given string (%s)', 'event_espresso'),
@@ -172,9 +172,9 @@  discard block
 block discarded – undo
172 172
         // load message type
173 173
         $message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
174 174
         $message_type = str_replace(' ', '_', $message_type);
175
-        $message_type = 'EE_' . $message_type . '_message_type';
175
+        $message_type = 'EE_'.$message_type.'_message_type';
176 176
 
177
-        if (! class_exists($message_type)) {
177
+        if ( ! class_exists($message_type)) {
178 178
             throw new EE_Error(
179 179
                 sprintf(
180 180
                     esc_html__('There is no message type class for the given string (%s)', 'event_espresso'),
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 
207 207
         // we only want the valid shortcodes for the given context!
208 208
         $context  = $this->_context;
209
-        $mt_codes = $mt_codes[ $context ];
209
+        $mt_codes = $mt_codes[$context];
210 210
 
211 211
         // in this first loop we're just getting all shortcode group indexes from the msgr_validator
212 212
         // into a single array (so we can get the appropriate shortcode objects for the groups)
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
             if (empty($config) || ! isset($config['shortcodes'])) {
218 218
                 continue;
219 219
             }  //Nothing to see here.
220
-            $groups_per_field[ $field ] = array_intersect($config['shortcodes'], $mt_codes);
220
+            $groups_per_field[$field] = array_intersect($config['shortcodes'], $mt_codes);
221 221
             $shortcode_groups           = array_merge($config['shortcodes'], $shortcode_groups);
222 222
         }
223 223
 
@@ -230,11 +230,11 @@  discard block
 block discarded – undo
230 230
         foreach ($shortcode_groups as $group) {
231 231
             $ref       = ucwords(str_replace('_', ' ', $group));
232 232
             $ref       = str_replace(' ', '_', $ref);
233
-            $classname = 'EE_' . $ref . '_Shortcodes';
233
+            $classname = 'EE_'.$ref.'_Shortcodes';
234 234
             if (class_exists($classname)) {
235 235
                 $a                         = new ReflectionClass($classname);
236 236
                 $obj                       = $a->newInstance();
237
-                $codes_from_objs[ $group ] = $obj->get_shortcodes();
237
+                $codes_from_objs[$group] = $obj->get_shortcodes();
238 238
             }
239 239
         }
240 240
 
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
         // let's just replace the $mt shortcode group indexes with the actual shortcodes (unique)
243 243
         $final_mt_codes = [];
244 244
         foreach ($mt_codes as $group) {
245
-            $final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[ $group ]);
245
+            $final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[$group]);
246 246
         }
247 247
 
248 248
         $mt_codes = $final_mt_codes;
@@ -260,44 +260,44 @@  discard block
 block discarded – undo
260 260
             }
261 261
 
262 262
             // If we have an override then we use it to indicate the codes we want.
263
-            if (isset($this->_valid_shortcodes_modifier[ $context ][ $field ])) {
264
-                $this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
265
-                    $this->_valid_shortcodes_modifier[ $context ][ $field ],
263
+            if (isset($this->_valid_shortcodes_modifier[$context][$field])) {
264
+                $this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
265
+                    $this->_valid_shortcodes_modifier[$context][$field],
266 266
                     $codes_from_objs
267 267
                 );
268
-            } elseif (isset($groups_per_field[ $field ])) {
268
+            } elseif (isset($groups_per_field[$field])) {
269 269
                 // we have specific shortcodes for a field so we need to use them
270
-                $this->_validators[ $field ]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
-                    $groups_per_field[ $field ],
270
+                $this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
+                    $groups_per_field[$field],
272 272
                     $codes_from_objs
273 273
                 );
274 274
             } elseif (empty($config)) {
275 275
                 // no config so we're assuming we're just going to use the shortcodes from the message type context
276
-                $this->_validators[ $field ]['shortcodes'] = $mt_codes;
276
+                $this->_validators[$field]['shortcodes'] = $mt_codes;
277 277
             } elseif (isset($config['specific_shortcodes'])) {
278 278
                 // we have specific shortcodes so we need to use them
279
-                $this->_validators[ $field ]['shortcodes'] = $config['specific_shortcodes'];
279
+                $this->_validators[$field]['shortcodes'] = $config['specific_shortcodes'];
280 280
             } else {
281 281
                 // otherwise the shortcodes are what is set by the messenger for that field
282 282
                 foreach ($config['shortcodes'] as $group) {
283
-                    $this->_validators[ $field ]['shortcodes'] = isset($this->_validators[ $field ]['shortcodes'])
284
-                        ? array_merge($this->_validators[ $field ]['shortcodes'], $codes_from_objs[ $group ])
285
-                        : $codes_from_objs[ $group ];
283
+                    $this->_validators[$field]['shortcodes'] = isset($this->_validators[$field]['shortcodes'])
284
+                        ? array_merge($this->_validators[$field]['shortcodes'], $codes_from_objs[$group])
285
+                        : $codes_from_objs[$group];
286 286
                 }
287 287
             }
288 288
 
289 289
             // now let's just make sure that any excluded specific shortcodes are removed.
290 290
             $specific_excludes = $this->get_specific_shortcode_excludes();
291
-            if (isset($specific_excludes[ $field ])) {
292
-                foreach ($specific_excludes[ $field ] as $sex) {
293
-                    if (isset($this->_validators[ $field ]['shortcodes'][ $sex ])) {
294
-                        unset($this->_validators[ $field ]['shortcodes'][ $sex ]);
291
+            if (isset($specific_excludes[$field])) {
292
+                foreach ($specific_excludes[$field] as $sex) {
293
+                    if (isset($this->_validators[$field]['shortcodes'][$sex])) {
294
+                        unset($this->_validators[$field]['shortcodes'][$sex]);
295 295
                     }
296 296
                 }
297 297
             }
298 298
 
299 299
             // hey! don't forget to include the type if present!
300
-            $this->_validators[ $field ]['type'] =
300
+            $this->_validators[$field]['type'] =
301 301
                 isset($config['type'])
302 302
                     ? $config['type']
303 303
                     : null;
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
     {
328 328
         // specific validator filter
329 329
         $shortcode_excludes = apply_filters(
330
-            'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
330
+            'FHEE__'.get_class($this).'__get_specific_shortcode_excludes;',
331 331
             $this->_specific_shortcode_excludes,
332 332
             $this->_context
333 333
         );
@@ -354,21 +354,21 @@  discard block
 block discarded – undo
354 354
         $template_fields = $this->_messenger->get_template_fields();
355 355
         // loop through the fields and check!
356 356
         foreach ($this->_fields as $field => $value) {
357
-            $this->_errors[ $field ] = [];
357
+            $this->_errors[$field] = [];
358 358
             $err_msg                 = '';
359 359
             $field_label             = '';
360 360
             // if field is not present in the _validators array then we continue
361
-            if (! isset($this->_validators[ $field ])) {
362
-                unset($this->_errors[ $field ]);
361
+            if ( ! isset($this->_validators[$field])) {
362
+                unset($this->_errors[$field]);
363 363
                 continue;
364 364
             }
365 365
 
366 366
             // get the translated field label!
367 367
             // first check if it's in the main fields list
368
-            if (isset($template_fields[ $field ])) {
368
+            if (isset($template_fields[$field])) {
369 369
                 // most likely the field is found in the 'extra' array.
370
-                $field_label = ! empty($template_fields[ $field ])
371
-                    ? $template_fields[ $field ]['label']
370
+                $field_label = ! empty($template_fields[$field])
371
+                    ? $template_fields[$field]['label']
372 372
                     : $field;
373 373
             }
374 374
 
@@ -392,20 +392,20 @@  discard block
 block discarded – undo
392 392
 
393 393
             // field is present. Let's validate shortcodes first (but only if shortcodes present).
394 394
             if (
395
-                isset($this->_validators[ $field ]['shortcodes'])
396
-                && ! empty($this->_validators[ $field ]['shortcodes'])
395
+                isset($this->_validators[$field]['shortcodes'])
396
+                && ! empty($this->_validators[$field]['shortcodes'])
397 397
             ) {
398
-                $invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[ $field ]['shortcodes']);
398
+                $invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[$field]['shortcodes']);
399 399
                 // if true then that means there is a returned error message
400 400
                 // that we'll need to add to the _errors array for this field.
401 401
                 if ($invalid_shortcodes) {
402
-                    $v_s     = array_keys($this->_validators[ $field ]['shortcodes']);
402
+                    $v_s     = array_keys($this->_validators[$field]['shortcodes']);
403 403
                     $err_msg = sprintf(
404 404
                         esc_html__(
405 405
                             '%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
406 406
                             'event_espresso'
407 407
                         ),
408
-                        '<strong>' . $field_label . '</strong>',
408
+                        '<strong>'.$field_label.'</strong>',
409 409
                         $invalid_shortcodes,
410 410
                         '<p>',
411 411
                         '</p >'
@@ -420,10 +420,10 @@  discard block
 block discarded – undo
420 420
             }
421 421
 
422 422
             // if there's a "type" to be validated then let's do that too.
423
-            if (isset($this->_validators[ $field ]['type']) && ! empty($this->_validators[ $field ]['type'])) {
424
-                switch ($this->_validators[ $field ]['type']) {
423
+            if (isset($this->_validators[$field]['type']) && ! empty($this->_validators[$field]['type'])) {
424
+                switch ($this->_validators[$field]['type']) {
425 425
                     case 'number':
426
-                        if (! is_numeric($value)) {
426
+                        if ( ! is_numeric($value)) {
427 427
                             $err_msg .= sprintf(
428 428
                                 esc_html__(
429 429
                                     '%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
                         break;
439 439
                     case 'email':
440 440
                         $valid_email = $this->_validate_email($value);
441
-                        if (! $valid_email) {
441
+                        if ( ! $valid_email) {
442 442
                             $err_msg .= htmlentities(
443 443
                                 sprintf(
444 444
                                     esc_html__(
@@ -456,18 +456,18 @@  discard block
 block discarded – undo
456 456
             }
457 457
 
458 458
             // if $err_msg isn't empty let's setup the _errors array for this field.
459
-            if (! empty($err_msg)) {
460
-                $this->_errors[ $field ]['msg'] = $err_msg;
459
+            if ( ! empty($err_msg)) {
460
+                $this->_errors[$field]['msg'] = $err_msg;
461 461
             } else {
462
-                unset($this->_errors[ $field ]);
462
+                unset($this->_errors[$field]);
463 463
             }
464 464
         }
465 465
 
466 466
         // if we have ANY errors, then we want to make sure we return the values
467 467
         // for ALL the fields so the user doesn't have to retype them all.
468
-        if (! empty($this->_errors)) {
468
+        if ( ! empty($this->_errors)) {
469 469
             foreach ($this->_fields as $field => $value) {
470
-                $this->_errors[ $field ]['value'] = stripslashes($value);
470
+                $this->_errors[$field]['value'] = stripslashes($value);
471 471
             }
472 472
         }
473 473
 
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
     {
491 491
         $shortcodes = [];
492 492
         foreach ($groups as $group) {
493
-            $shortcodes = array_merge($shortcodes, $codes_from_objs[ $group ]);
493
+            $shortcodes = array_merge($shortcodes, $codes_from_objs[$group]);
494 494
         }
495 495
         return $shortcodes;
496 496
     }
@@ -520,8 +520,8 @@  discard block
 block discarded – undo
520 520
                 // strip the shortcode so we just have the BASE string (i.e. [ANSWER_*] )
521 521
                 $dynamic_sc = preg_replace('/(_\*+.+)/', '_*]', $code);
522 522
                 // does this exist in the $valid_shortcodes?  If so then unset.
523
-                if (isset($valid_shortcodes[ $dynamic_sc ])) {
524
-                    unset($diff[ $ind ]);
523
+                if (isset($valid_shortcodes[$dynamic_sc])) {
524
+                    unset($diff[$ind]);
525 525
                 }
526 526
             }
527 527
         }
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 
533 533
         // made it here? then let's assemble the error message
534 534
         $invalid_shortcodes = implode('</strong>,<strong>', $diff);
535
-        return '<strong>' . $invalid_shortcodes . '</strong>';
535
+        return '<strong>'.$invalid_shortcodes.'</strong>';
536 536
     }
537 537
 
538 538
 
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
         // its possible that this message is being "turned off" for a particular context
569 569
 
570 570
 
571
-        if (! empty($or_val) && empty($value)) {
571
+        if ( ! empty($or_val) && empty($value)) {
572 572
             return $validate;
573 573
         }
574 574
 
@@ -627,8 +627,8 @@  discard block
 block discarded – undo
627 627
             '_MSGTYP' => '_message_type',
628 628
         ];
629 629
 
630
-        if (isset($expected_properties_map[ $property ])) {
631
-            return $this->{$expected_properties_map[ $property ]};
630
+        if (isset($expected_properties_map[$property])) {
631
+            return $this->{$expected_properties_map[$property]};
632 632
         }
633 633
 
634 634
         throw new Exception(
Please login to merge, or discard this patch.
core/libraries/rest_api/ModelDataTranslator.php 2 patches
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
         ) {
70 70
             $new_value_maybe_array = [];
71 71
             foreach ($original_value_maybe_array as $array_key => $array_item) {
72
-                $new_value_maybe_array[ $array_key ] = ModelDataTranslator::prepareFieldValueFromJson(
72
+                $new_value_maybe_array[$array_key] = ModelDataTranslator::prepareFieldValueFromJson(
73 73
                     $field_obj,
74 74
                     $array_item,
75 75
                     $requested_version,
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
         if (is_array($original_value_maybe_array)) {
104 104
             $new_value = [];
105 105
             foreach ($original_value_maybe_array as $key => $value) {
106
-                $new_value[ $key ] = ModelDataTranslator::prepareFieldValuesForJson(
106
+                $new_value[$key] = ModelDataTranslator::prepareFieldValuesForJson(
107 107
                     $field_obj,
108 108
                     $value,
109 109
                     $request_version
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
                 '0',
245 245
                 STR_PAD_LEFT
246 246
             );
247
-        return $original_timestamp . $offset_sign . $offset_string;
247
+        return $original_timestamp.$offset_sign.$offset_string;
248 248
     }
249 249
 
250 250
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
                     // first, check if its a MySQL timestamp in GMT
324 324
                     $datetime_obj = DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
325 325
                 }
326
-                if (! $datetime_obj instanceof DateTime) {
326
+                if ( ! $datetime_obj instanceof DateTime) {
327 327
                     // so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
328 328
                     $datetime_obj = $field_obj->prepare_for_set($original_value);
329 329
                 }
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
                         $original_value,
350 350
                         $field_obj->get_name(),
351 351
                         $field_obj->get_model_name(),
352
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
352
+                        $field_obj->get_time_format().' '.$field_obj->get_time_format()
353 353
                     )
354 354
                 );
355 355
             }
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
         }
364 364
         // are we about to send an object? just don't. We have no good way to represent it in JSON.
365 365
         // can't just check using is_object() because that missed PHP incomplete objects
366
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
366
+        if ( ! ModelDataTranslator::isRepresentableInJson($new_value)) {
367 367
             $new_value = [
368 368
                 'error_code'    => 'php_object_not_return',
369 369
                 'error_message' => esc_html__(
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
             if ($query_param_meta->getField() instanceof EE_Model_Field_Base) {
415 415
                 $translated_value = $query_param_meta->determineConditionsQueryParameterValue();
416 416
                 if (
417
-                    (isset($query_param_for_models[ $query_param_meta->getQueryParamKey() ])
417
+                    (isset($query_param_for_models[$query_param_meta->getQueryParamKey()])
418 418
                      && $query_param_meta->isGmtField())
419 419
                     || $translated_value === null
420 420
                 ) {
@@ -423,11 +423,11 @@  discard block
 block discarded – undo
423 423
                     // OR we couldn't create a translated value from their input
424 424
                     continue;
425 425
                 }
426
-                $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $translated_value;
426
+                $query_param_for_models[$query_param_meta->getQueryParamKey()] = $translated_value;
427 427
             } else {
428 428
                 $nested_query_params = $query_param_meta->determineNestedConditionQueryParameters();
429 429
                 if ($nested_query_params) {
430
-                    $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $nested_query_params;
430
+                    $query_param_for_models[$query_param_meta->getQueryParamKey()] = $nested_query_params;
431 431
                 }
432 432
             }
433 433
         }
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
      */
458 458
     public static function removeGmtFromFieldName($field_name)
459 459
     {
460
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
460
+        if ( ! ModelDataTranslator::isGmtDateFieldName($field_name)) {
461 461
             return $field_name;
462 462
         }
463 463
         $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
     {
501 501
         $new_array = [];
502 502
         foreach ($field_names as $key => $field_name) {
503
-            $new_array[ $key ] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
503
+            $new_array[$key] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
504 504
         }
505 505
         return $new_array;
506 506
     }
@@ -517,7 +517,7 @@  discard block
 block discarded – undo
517 517
     {
518 518
         $new_array = [];
519 519
         foreach ($field_names_as_keys as $field_name => $value) {
520
-            $new_array[ ModelDataTranslator::prepareFieldNameFromJson($field_name) ] = $value;
520
+            $new_array[ModelDataTranslator::prepareFieldNameFromJson($field_name)] = $value;
521 521
         }
522 522
         return $new_array;
523 523
     }
@@ -613,10 +613,10 @@  discard block
 block discarded – undo
613 613
                         $requested_version
614 614
                     );
615 615
                 }
616
-                $query_param_for_models[ $query_param_key ] = $translated_value;
616
+                $query_param_for_models[$query_param_key] = $translated_value;
617 617
             } else {
618 618
                 // so it's not for a field, assume it's a logic query param key
619
-                $query_param_for_models[ $query_param_key ] =
619
+                $query_param_for_models[$query_param_key] =
620 620
                     ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
621 621
                         $query_param_value,
622 622
                         $model,
@@ -668,11 +668,11 @@  discard block
 block discarded – undo
668 668
             );
669 669
         }
670 670
         $number_of_parts       = count($query_param_parts);
671
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
671
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
672 672
         $field_name            = $last_query_param_part;
673 673
         if ($number_of_parts !== 1) {
674 674
             // the last part is the column name, and there are only 2parts. therefore...
675
-            $model = EE_Registry::instance()->load_model($query_param_parts[ $number_of_parts - 2 ]);
675
+            $model = EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
676 676
         }
677 677
         try {
678 678
             return $model->field_settings_for($field_name, false);
Please login to merge, or discard this patch.
Indentation   +656 added lines, -656 removed lines patch added patch discarded remove patch
@@ -39,660 +39,660 @@
 block discarded – undo
39 39
 class ModelDataTranslator
40 40
 {
41 41
 
42
-    /**
43
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
44
-     * fields that COULD contain -1; so we use null
45
-     */
46
-    const EE_INF_IN_REST = null;
47
-
48
-
49
-    /**
50
-     * Prepares a possible array of input values from JSON for use by the models
51
-     *
52
-     * @param EE_Model_Field_Base $field_obj
53
-     * @param mixed               $original_value_maybe_array
54
-     * @param string              $requested_version
55
-     * @param string              $timezone_string treat values as being in this timezone
56
-     * @return mixed
57
-     * @throws RestException
58
-     * @throws EE_Error
59
-     */
60
-    public static function prepareFieldValuesFromJson(
61
-        $field_obj,
62
-        $original_value_maybe_array,
63
-        $requested_version,
64
-        $timezone_string = 'UTC'
65
-    ) {
66
-        if (
67
-            is_array($original_value_maybe_array)
68
-            && ! $field_obj instanceof EE_Serialized_Text_Field
69
-        ) {
70
-            $new_value_maybe_array = [];
71
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
72
-                $new_value_maybe_array[ $array_key ] = ModelDataTranslator::prepareFieldValueFromJson(
73
-                    $field_obj,
74
-                    $array_item,
75
-                    $requested_version,
76
-                    $timezone_string
77
-                );
78
-            }
79
-        } else {
80
-            $new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
81
-                $field_obj,
82
-                $original_value_maybe_array,
83
-                $requested_version,
84
-                $timezone_string
85
-            );
86
-        }
87
-        return $new_value_maybe_array;
88
-    }
89
-
90
-
91
-    /**
92
-     * Prepares an array of field values FOR use in JSON/REST API
93
-     *
94
-     * @param EE_Model_Field_Base $field_obj
95
-     * @param mixed               $original_value_maybe_array
96
-     * @param string              $request_version (eg 4.8.36)
97
-     * @return array
98
-     * @throws EE_Error
99
-     * @throws EE_Error
100
-     */
101
-    public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
102
-    {
103
-        if (is_array($original_value_maybe_array)) {
104
-            $new_value = [];
105
-            foreach ($original_value_maybe_array as $key => $value) {
106
-                $new_value[ $key ] = ModelDataTranslator::prepareFieldValuesForJson(
107
-                    $field_obj,
108
-                    $value,
109
-                    $request_version
110
-                );
111
-            }
112
-        } else {
113
-            $new_value = ModelDataTranslator::prepareFieldValueForJson(
114
-                $field_obj,
115
-                $original_value_maybe_array,
116
-                $request_version
117
-            );
118
-        }
119
-        return $new_value;
120
-    }
121
-
122
-
123
-    /**
124
-     * Prepares incoming data from the json or request parameters for the models'
125
-     * "$query_params".
126
-     *
127
-     * @param EE_Model_Field_Base $field_obj
128
-     * @param mixed               $original_value
129
-     * @param string              $requested_version
130
-     * @param string              $timezone_string treat values as being in this timezone
131
-     * @return mixed
132
-     * @throws RestException
133
-     * @throws DomainException
134
-     * @throws EE_Error
135
-     */
136
-    public static function prepareFieldValueFromJson(
137
-        $field_obj,
138
-        $original_value,
139
-        $requested_version,
140
-        $timezone_string = 'UTC'
141
-    ) {
142
-        // check if they accidentally submitted an error value. If so throw an exception
143
-        if (
144
-            is_array($original_value)
145
-            && isset($original_value['error_code'], $original_value['error_message'])
146
-        ) {
147
-            throw new RestException(
148
-                'rest_submitted_error_value',
149
-                sprintf(
150
-                    esc_html__(
151
-                        'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
152
-                        'event_espresso'
153
-                    ),
154
-                    $field_obj->get_name()
155
-                ),
156
-                [
157
-                    'status' => 400,
158
-                ]
159
-            );
160
-        }
161
-        // double-check for serialized PHP. We never accept serialized PHP. No way Jose.
162
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
163
-        $timezone_string =
164
-            $timezone_string !== ''
165
-                ? $timezone_string
166
-                : get_option('timezone_string', '');
167
-        // walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
168
-        // way Jose.
169
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
170
-        if (
171
-            $field_obj instanceof EE_Infinite_Integer_Field
172
-            && in_array($original_value, [null, ''], true)
173
-        ) {
174
-            $new_value = EE_INF;
175
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
176
-            $new_value = rest_parse_date(
177
-                self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
178
-            );
179
-            if ($new_value === false) {
180
-                throw new RestException(
181
-                    'invalid_format_for_timestamp',
182
-                    sprintf(
183
-                        esc_html__(
184
-                            'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
185
-                            'event_espresso'
186
-                        ),
187
-                        'RFC3339',
188
-                        'ISO8601',
189
-                        $original_value
190
-                    ),
191
-                    [
192
-                        'status' => 400,
193
-                    ]
194
-                );
195
-            }
196
-        } elseif ($field_obj instanceof EE_Boolean_Field) {
197
-            // Interpreted the strings "false", "true", "on", "off" appropriately.
198
-            $new_value = filter_var($original_value, FILTER_VALIDATE_BOOLEAN);
199
-        } else {
200
-            $new_value = $original_value;
201
-        }
202
-        return $new_value;
203
-    }
204
-
205
-
206
-    /**
207
-     * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
208
-     * information via details obtained from the host site.
209
-     *
210
-     * @param string            $original_timestamp
211
-     * @param EE_Datetime_Field $datetime_field
212
-     * @param                   $timezone_string
213
-     * @return string
214
-     * @throws DomainException
215
-     */
216
-    private static function getTimestampWithTimezoneOffset(
217
-        $original_timestamp,
218
-        EE_Datetime_Field $datetime_field,
219
-        $timezone_string
220
-    ) {
221
-        // already have timezone information?
222
-        if (preg_match('/Z|([+-])(\d{2}:\d{2})/', $original_timestamp)) {
223
-            // yes, we're ignoring the timezone.
224
-            return $original_timestamp;
225
-        }
226
-        // need to append timezone
227
-        list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
228
-            $datetime_field->get_timezone_offset(
229
-                new DateTimeZone($timezone_string),
230
-                $original_timestamp
231
-            )
232
-        );
233
-        $offset_string =
234
-            str_pad(
235
-                floor($offset_secs / HOUR_IN_SECONDS),
236
-                2,
237
-                '0',
238
-                STR_PAD_LEFT
239
-            )
240
-            . ':'
241
-            . str_pad(
242
-                ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
243
-                2,
244
-                '0',
245
-                STR_PAD_LEFT
246
-            );
247
-        return $original_timestamp . $offset_sign . $offset_string;
248
-    }
249
-
250
-
251
-    /**
252
-     * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
253
-     * think that can happen). If $data is an array, recurses into its keys and values
254
-     *
255
-     * @param mixed $data
256
-     * @return void
257
-     * @throws RestException
258
-     */
259
-    public static function throwExceptionIfContainsSerializedData($data)
260
-    {
261
-        if (is_array($data)) {
262
-            foreach ($data as $key => $value) {
263
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
264
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
265
-            }
266
-        } else {
267
-            if (is_serialized($data) || is_object($data)) {
268
-                throw new RestException(
269
-                    'serialized_data_submission_prohibited',
270
-                    esc_html__(
271
-                    // @codingStandardsIgnoreStart
272
-                        'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
273
-                        // @codingStandardsIgnoreEnd
274
-                        'event_espresso'
275
-                    )
276
-                );
277
-            }
278
-        }
279
-    }
280
-
281
-
282
-    /**
283
-     * determines what's going on with them timezone strings
284
-     *
285
-     * @param int $timezone_offset
286
-     * @return array
287
-     */
288
-    private static function parseTimezoneOffset($timezone_offset)
289
-    {
290
-        $first_char = substr((string) $timezone_offset, 0, 1);
291
-        if ($first_char === '+' || $first_char === '-') {
292
-            $offset_sign = $first_char;
293
-            $offset_secs = substr((string) $timezone_offset, 1);
294
-        } else {
295
-            $offset_sign = '+';
296
-            $offset_secs = $timezone_offset;
297
-        }
298
-        return [$offset_sign, $offset_secs];
299
-    }
300
-
301
-
302
-    /**
303
-     * Prepares a field's value for display in the API
304
-     *
305
-     * @param EE_Model_Field_Base $field_obj
306
-     * @param mixed               $original_value
307
-     * @param string              $requested_version
308
-     * @return mixed
309
-     * @throws EE_Error
310
-     * @throws EE_Error
311
-     */
312
-    public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
313
-    {
314
-        if ($original_value === EE_INF) {
315
-            $new_value = ModelDataTranslator::EE_INF_IN_REST;
316
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
317
-            if (is_string($original_value)) {
318
-                // did they submit a string of a unix timestamp?
319
-                if (is_numeric($original_value)) {
320
-                    $datetime_obj = new DateTime();
321
-                    $datetime_obj->setTimestamp((int) $original_value);
322
-                } else {
323
-                    // first, check if its a MySQL timestamp in GMT
324
-                    $datetime_obj = DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
325
-                }
326
-                if (! $datetime_obj instanceof DateTime) {
327
-                    // so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
328
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
329
-                }
330
-                $original_value = $datetime_obj;
331
-            }
332
-            if ($original_value instanceof DateTime) {
333
-                $new_value = $original_value->format('Y-m-d H:i:s');
334
-            } elseif (is_int($original_value) || is_float($original_value)) {
335
-                $new_value = date('Y-m-d H:i:s', $original_value);
336
-            } elseif ($original_value === null || $original_value === '') {
337
-                $new_value = null;
338
-            } else {
339
-                // so it's not a datetime object, unix timestamp (as string or int),
340
-                // MySQL timestamp, or even a string in the field object's format. So no idea what it is
341
-                throw new EE_Error(
342
-                    sprintf(
343
-                        esc_html__(
344
-                        // @codingStandardsIgnoreStart
345
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
346
-                            // @codingStandardsIgnoreEnd
347
-                            'event_espresso'
348
-                        ),
349
-                        $original_value,
350
-                        $field_obj->get_name(),
351
-                        $field_obj->get_model_name(),
352
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
353
-                    )
354
-                );
355
-            }
356
-            if ($new_value !== null) {
357
-                // phpcs:disable PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
358
-                $new_value = mysql_to_rfc3339($new_value);
359
-                // phpcs:enable
360
-            }
361
-        } else {
362
-            $new_value = $original_value;
363
-        }
364
-        // are we about to send an object? just don't. We have no good way to represent it in JSON.
365
-        // can't just check using is_object() because that missed PHP incomplete objects
366
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
367
-            $new_value = [
368
-                'error_code'    => 'php_object_not_return',
369
-                'error_message' => esc_html__(
370
-                    'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
371
-                    'event_espresso'
372
-                ),
373
-            ];
374
-        }
375
-        return apply_filters(
376
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
377
-            $new_value,
378
-            $field_obj,
379
-            $original_value,
380
-            $requested_version
381
-        );
382
-    }
383
-
384
-
385
-    /**
386
-     * Prepares condition-query-parameters (like what's in where and having) from
387
-     * the format expected in the API to use in the models
388
-     *
389
-     * @param array    $inputted_query_params_of_this_type
390
-     * @param EEM_Base $model
391
-     * @param string   $requested_version
392
-     * @param boolean  $writing whether this data will be written to the DB, or if we're just building a query.
393
-     *                          If we're writing to the DB, we don't expect any operators, or any logic query
394
-     *                          parameters, and we also won't accept serialized data unless the current user has
395
-     *                          unfiltered_html.
396
-     * @return array
397
-     * @throws DomainException
398
-     * @throws EE_Error
399
-     * @throws RestException
400
-     * @throws InvalidDataTypeException
401
-     * @throws InvalidInterfaceException
402
-     * @throws InvalidArgumentException
403
-     */
404
-    public static function prepareConditionsQueryParamsForModels(
405
-        $inputted_query_params_of_this_type,
406
-        EEM_Base $model,
407
-        $requested_version,
408
-        $writing = false
409
-    ) {
410
-        $query_param_for_models = [];
411
-        $context                = new RestIncomingQueryParamContext($model, $requested_version, $writing);
412
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
413
-            $query_param_meta = new RestIncomingQueryParamMetadata($query_param_key, $query_param_value, $context);
414
-            if ($query_param_meta->getField() instanceof EE_Model_Field_Base) {
415
-                $translated_value = $query_param_meta->determineConditionsQueryParameterValue();
416
-                if (
417
-                    (isset($query_param_for_models[ $query_param_meta->getQueryParamKey() ])
418
-                     && $query_param_meta->isGmtField())
419
-                    || $translated_value === null
420
-                ) {
421
-                    // they have already provided a non-gmt field, ignore the gmt one. That's what WP core
422
-                    // currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
423
-                    // OR we couldn't create a translated value from their input
424
-                    continue;
425
-                }
426
-                $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $translated_value;
427
-            } else {
428
-                $nested_query_params = $query_param_meta->determineNestedConditionQueryParameters();
429
-                if ($nested_query_params) {
430
-                    $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $nested_query_params;
431
-                }
432
-            }
433
-        }
434
-        return $query_param_for_models;
435
-    }
436
-
437
-
438
-    /**
439
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
440
-     * gmt date field name
441
-     *
442
-     * @param string $field_name
443
-     * @return boolean
444
-     */
445
-    public static function isGmtDateFieldName($field_name)
446
-    {
447
-        $field_name = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name);
448
-        return substr($field_name, -4, 4) === '_gmt';
449
-    }
450
-
451
-
452
-    /**
453
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
454
-     *
455
-     * @param string $field_name
456
-     * @return string
457
-     */
458
-    public static function removeGmtFromFieldName($field_name)
459
-    {
460
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
461
-            return $field_name;
462
-        }
463
-        $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
464
-            $field_name
465
-        );
466
-        $query_param_sans_gmt_and_sans_stars = substr(
467
-            $query_param_sans_stars,
468
-            0,
469
-            strrpos(
470
-                $field_name,
471
-                '_gmt'
472
-            )
473
-        );
474
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
475
-    }
476
-
477
-
478
-    /**
479
-     * Takes a field name from the REST API and prepares it for the model querying
480
-     *
481
-     * @param string $field_name
482
-     * @return string
483
-     */
484
-    public static function prepareFieldNameFromJson($field_name)
485
-    {
486
-        if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
487
-            return ModelDataTranslator::removeGmtFromFieldName($field_name);
488
-        }
489
-        return $field_name;
490
-    }
491
-
492
-
493
-    /**
494
-     * Takes array of field names from REST API and prepares for models
495
-     *
496
-     * @param array $field_names
497
-     * @return array of field names (possibly include model prefixes)
498
-     */
499
-    public static function prepareFieldNamesFromJson(array $field_names)
500
-    {
501
-        $new_array = [];
502
-        foreach ($field_names as $key => $field_name) {
503
-            $new_array[ $key ] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
504
-        }
505
-        return $new_array;
506
-    }
507
-
508
-
509
-    /**
510
-     * Takes array where array keys are field names (possibly with model path prefixes)
511
-     * from the REST API and prepares them for model querying
512
-     *
513
-     * @param array $field_names_as_keys
514
-     * @return array
515
-     */
516
-    public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
517
-    {
518
-        $new_array = [];
519
-        foreach ($field_names_as_keys as $field_name => $value) {
520
-            $new_array[ ModelDataTranslator::prepareFieldNameFromJson($field_name) ] = $value;
521
-        }
522
-        return $new_array;
523
-    }
524
-
525
-
526
-    /**
527
-     * Prepares an array of model query params for use in the REST API
528
-     *
529
-     * @param array    $model_query_params
530
-     * @param EEM_Base $model
531
-     * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
532
-     *                                     REST API
533
-     * @return array which can be passed into the EE4 REST API when querying a model resource
534
-     * @throws EE_Error
535
-     * @throws ReflectionException
536
-     */
537
-    public static function prepareQueryParamsForRestApi(
538
-        array $model_query_params,
539
-        EEM_Base $model,
540
-        $requested_version = null
541
-    ) {
542
-        if ($requested_version === null) {
543
-            $requested_version = EED_Core_Rest_Api::latest_rest_api_version();
544
-        }
545
-        $rest_query_params = $model_query_params;
546
-        if (isset($model_query_params[0])) {
547
-            $rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
548
-                $model_query_params[0],
549
-                $model,
550
-                $requested_version
551
-            );
552
-            unset($rest_query_params[0]);
553
-        }
554
-        if (isset($model_query_params['having'])) {
555
-            $rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
556
-                $model_query_params['having'],
557
-                $model,
558
-                $requested_version
559
-            );
560
-        }
561
-        return apply_filters(
562
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
563
-            $rest_query_params,
564
-            $model_query_params,
565
-            $model,
566
-            $requested_version
567
-        );
568
-    }
569
-
570
-
571
-    /**
572
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
573
-     *
574
-     * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
575
-     * @param EEM_Base $model
576
-     * @param string   $requested_version                   eg "4.8.36"
577
-     * @return array ready for use in the rest api query params
578
-     * @throws EE_Error
579
-     * @throws RestException if somehow a PHP object were in the query params' values,*@throws
580
-     * @throws ReflectionException
581
-     *                                                      ReflectionException
582
-     *                                                      (which would be really unusual)
583
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
584
-     */
585
-    public static function prepareConditionsQueryParamsForRestApi(
586
-        $inputted_query_params_of_this_type,
587
-        EEM_Base $model,
588
-        $requested_version
589
-    ) {
590
-        $query_param_for_models = [];
591
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
592
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
593
-                ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
594
-                $model
595
-            );
596
-            if ($field instanceof EE_Model_Field_Base) {
597
-                // did they specify an operator?
598
-                if (is_array($query_param_value)) {
599
-                    $op               = $query_param_value[0];
600
-                    $translated_value = [$op];
601
-                    if (isset($query_param_value[1])) {
602
-                        $value               = $query_param_value[1];
603
-                        $translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
604
-                            $field,
605
-                            $value,
606
-                            $requested_version
607
-                        );
608
-                    }
609
-                } else {
610
-                    $translated_value = ModelDataTranslator::prepareFieldValueForJson(
611
-                        $field,
612
-                        $query_param_value,
613
-                        $requested_version
614
-                    );
615
-                }
616
-                $query_param_for_models[ $query_param_key ] = $translated_value;
617
-            } else {
618
-                // so it's not for a field, assume it's a logic query param key
619
-                $query_param_for_models[ $query_param_key ] =
620
-                    ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
621
-                        $query_param_value,
622
-                        $model,
623
-                        $requested_version
624
-                    );
625
-            }
626
-        }
627
-        return $query_param_for_models;
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $condition_query_param_key
633
-     * @return string
634
-     */
635
-    public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
636
-    {
637
-        $pos_of_star = strpos($condition_query_param_key, '*');
638
-        if ($pos_of_star === false) {
639
-            return $condition_query_param_key;
640
-        }
641
-        return substr($condition_query_param_key, 0, $pos_of_star);
642
-    }
643
-
644
-
645
-    /**
646
-     * Takes the input parameter and finds the model field that it indicates.
647
-     *
648
-     * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
649
-     * @param EEM_Base $model
650
-     * @return EE_Model_Field_Base
651
-     * @throws EE_Error
652
-     * @throws ReflectionException
653
-     */
654
-    public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
655
-    {
656
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
657
-        // which will help us find the database table and column
658
-        $query_param_parts = explode('.', $query_param_name);
659
-        if (empty($query_param_parts)) {
660
-            throw new EE_Error(
661
-                sprintf(
662
-                    esc_html__(
663
-                        '_extract_column_name is empty when trying to extract column and table name from %s',
664
-                        'event_espresso'
665
-                    ),
666
-                    $query_param_name
667
-                )
668
-            );
669
-        }
670
-        $number_of_parts       = count($query_param_parts);
671
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
672
-        $field_name            = $last_query_param_part;
673
-        if ($number_of_parts !== 1) {
674
-            // the last part is the column name, and there are only 2parts. therefore...
675
-            $model = EE_Registry::instance()->load_model($query_param_parts[ $number_of_parts - 2 ]);
676
-        }
677
-        try {
678
-            return $model->field_settings_for($field_name, false);
679
-        } catch (EE_Error $e) {
680
-            return null;
681
-        }
682
-    }
683
-
684
-
685
-    /**
686
-     * Returns true if $data can be easily represented in JSON.
687
-     * Basically, objects and resources can't be represented in JSON easily.
688
-     *
689
-     * @param mixed $data
690
-     * @return bool
691
-     */
692
-    protected static function isRepresentableInJson($data)
693
-    {
694
-        return is_scalar($data)
695
-               || is_array($data)
696
-               || is_null($data);
697
-    }
42
+	/**
43
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
44
+	 * fields that COULD contain -1; so we use null
45
+	 */
46
+	const EE_INF_IN_REST = null;
47
+
48
+
49
+	/**
50
+	 * Prepares a possible array of input values from JSON for use by the models
51
+	 *
52
+	 * @param EE_Model_Field_Base $field_obj
53
+	 * @param mixed               $original_value_maybe_array
54
+	 * @param string              $requested_version
55
+	 * @param string              $timezone_string treat values as being in this timezone
56
+	 * @return mixed
57
+	 * @throws RestException
58
+	 * @throws EE_Error
59
+	 */
60
+	public static function prepareFieldValuesFromJson(
61
+		$field_obj,
62
+		$original_value_maybe_array,
63
+		$requested_version,
64
+		$timezone_string = 'UTC'
65
+	) {
66
+		if (
67
+			is_array($original_value_maybe_array)
68
+			&& ! $field_obj instanceof EE_Serialized_Text_Field
69
+		) {
70
+			$new_value_maybe_array = [];
71
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
72
+				$new_value_maybe_array[ $array_key ] = ModelDataTranslator::prepareFieldValueFromJson(
73
+					$field_obj,
74
+					$array_item,
75
+					$requested_version,
76
+					$timezone_string
77
+				);
78
+			}
79
+		} else {
80
+			$new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
81
+				$field_obj,
82
+				$original_value_maybe_array,
83
+				$requested_version,
84
+				$timezone_string
85
+			);
86
+		}
87
+		return $new_value_maybe_array;
88
+	}
89
+
90
+
91
+	/**
92
+	 * Prepares an array of field values FOR use in JSON/REST API
93
+	 *
94
+	 * @param EE_Model_Field_Base $field_obj
95
+	 * @param mixed               $original_value_maybe_array
96
+	 * @param string              $request_version (eg 4.8.36)
97
+	 * @return array
98
+	 * @throws EE_Error
99
+	 * @throws EE_Error
100
+	 */
101
+	public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
102
+	{
103
+		if (is_array($original_value_maybe_array)) {
104
+			$new_value = [];
105
+			foreach ($original_value_maybe_array as $key => $value) {
106
+				$new_value[ $key ] = ModelDataTranslator::prepareFieldValuesForJson(
107
+					$field_obj,
108
+					$value,
109
+					$request_version
110
+				);
111
+			}
112
+		} else {
113
+			$new_value = ModelDataTranslator::prepareFieldValueForJson(
114
+				$field_obj,
115
+				$original_value_maybe_array,
116
+				$request_version
117
+			);
118
+		}
119
+		return $new_value;
120
+	}
121
+
122
+
123
+	/**
124
+	 * Prepares incoming data from the json or request parameters for the models'
125
+	 * "$query_params".
126
+	 *
127
+	 * @param EE_Model_Field_Base $field_obj
128
+	 * @param mixed               $original_value
129
+	 * @param string              $requested_version
130
+	 * @param string              $timezone_string treat values as being in this timezone
131
+	 * @return mixed
132
+	 * @throws RestException
133
+	 * @throws DomainException
134
+	 * @throws EE_Error
135
+	 */
136
+	public static function prepareFieldValueFromJson(
137
+		$field_obj,
138
+		$original_value,
139
+		$requested_version,
140
+		$timezone_string = 'UTC'
141
+	) {
142
+		// check if they accidentally submitted an error value. If so throw an exception
143
+		if (
144
+			is_array($original_value)
145
+			&& isset($original_value['error_code'], $original_value['error_message'])
146
+		) {
147
+			throw new RestException(
148
+				'rest_submitted_error_value',
149
+				sprintf(
150
+					esc_html__(
151
+						'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
152
+						'event_espresso'
153
+					),
154
+					$field_obj->get_name()
155
+				),
156
+				[
157
+					'status' => 400,
158
+				]
159
+			);
160
+		}
161
+		// double-check for serialized PHP. We never accept serialized PHP. No way Jose.
162
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
163
+		$timezone_string =
164
+			$timezone_string !== ''
165
+				? $timezone_string
166
+				: get_option('timezone_string', '');
167
+		// walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
168
+		// way Jose.
169
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
170
+		if (
171
+			$field_obj instanceof EE_Infinite_Integer_Field
172
+			&& in_array($original_value, [null, ''], true)
173
+		) {
174
+			$new_value = EE_INF;
175
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
176
+			$new_value = rest_parse_date(
177
+				self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
178
+			);
179
+			if ($new_value === false) {
180
+				throw new RestException(
181
+					'invalid_format_for_timestamp',
182
+					sprintf(
183
+						esc_html__(
184
+							'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
185
+							'event_espresso'
186
+						),
187
+						'RFC3339',
188
+						'ISO8601',
189
+						$original_value
190
+					),
191
+					[
192
+						'status' => 400,
193
+					]
194
+				);
195
+			}
196
+		} elseif ($field_obj instanceof EE_Boolean_Field) {
197
+			// Interpreted the strings "false", "true", "on", "off" appropriately.
198
+			$new_value = filter_var($original_value, FILTER_VALIDATE_BOOLEAN);
199
+		} else {
200
+			$new_value = $original_value;
201
+		}
202
+		return $new_value;
203
+	}
204
+
205
+
206
+	/**
207
+	 * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
208
+	 * information via details obtained from the host site.
209
+	 *
210
+	 * @param string            $original_timestamp
211
+	 * @param EE_Datetime_Field $datetime_field
212
+	 * @param                   $timezone_string
213
+	 * @return string
214
+	 * @throws DomainException
215
+	 */
216
+	private static function getTimestampWithTimezoneOffset(
217
+		$original_timestamp,
218
+		EE_Datetime_Field $datetime_field,
219
+		$timezone_string
220
+	) {
221
+		// already have timezone information?
222
+		if (preg_match('/Z|([+-])(\d{2}:\d{2})/', $original_timestamp)) {
223
+			// yes, we're ignoring the timezone.
224
+			return $original_timestamp;
225
+		}
226
+		// need to append timezone
227
+		list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
228
+			$datetime_field->get_timezone_offset(
229
+				new DateTimeZone($timezone_string),
230
+				$original_timestamp
231
+			)
232
+		);
233
+		$offset_string =
234
+			str_pad(
235
+				floor($offset_secs / HOUR_IN_SECONDS),
236
+				2,
237
+				'0',
238
+				STR_PAD_LEFT
239
+			)
240
+			. ':'
241
+			. str_pad(
242
+				($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
243
+				2,
244
+				'0',
245
+				STR_PAD_LEFT
246
+			);
247
+		return $original_timestamp . $offset_sign . $offset_string;
248
+	}
249
+
250
+
251
+	/**
252
+	 * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
253
+	 * think that can happen). If $data is an array, recurses into its keys and values
254
+	 *
255
+	 * @param mixed $data
256
+	 * @return void
257
+	 * @throws RestException
258
+	 */
259
+	public static function throwExceptionIfContainsSerializedData($data)
260
+	{
261
+		if (is_array($data)) {
262
+			foreach ($data as $key => $value) {
263
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
264
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
265
+			}
266
+		} else {
267
+			if (is_serialized($data) || is_object($data)) {
268
+				throw new RestException(
269
+					'serialized_data_submission_prohibited',
270
+					esc_html__(
271
+					// @codingStandardsIgnoreStart
272
+						'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
273
+						// @codingStandardsIgnoreEnd
274
+						'event_espresso'
275
+					)
276
+				);
277
+			}
278
+		}
279
+	}
280
+
281
+
282
+	/**
283
+	 * determines what's going on with them timezone strings
284
+	 *
285
+	 * @param int $timezone_offset
286
+	 * @return array
287
+	 */
288
+	private static function parseTimezoneOffset($timezone_offset)
289
+	{
290
+		$first_char = substr((string) $timezone_offset, 0, 1);
291
+		if ($first_char === '+' || $first_char === '-') {
292
+			$offset_sign = $first_char;
293
+			$offset_secs = substr((string) $timezone_offset, 1);
294
+		} else {
295
+			$offset_sign = '+';
296
+			$offset_secs = $timezone_offset;
297
+		}
298
+		return [$offset_sign, $offset_secs];
299
+	}
300
+
301
+
302
+	/**
303
+	 * Prepares a field's value for display in the API
304
+	 *
305
+	 * @param EE_Model_Field_Base $field_obj
306
+	 * @param mixed               $original_value
307
+	 * @param string              $requested_version
308
+	 * @return mixed
309
+	 * @throws EE_Error
310
+	 * @throws EE_Error
311
+	 */
312
+	public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
313
+	{
314
+		if ($original_value === EE_INF) {
315
+			$new_value = ModelDataTranslator::EE_INF_IN_REST;
316
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
317
+			if (is_string($original_value)) {
318
+				// did they submit a string of a unix timestamp?
319
+				if (is_numeric($original_value)) {
320
+					$datetime_obj = new DateTime();
321
+					$datetime_obj->setTimestamp((int) $original_value);
322
+				} else {
323
+					// first, check if its a MySQL timestamp in GMT
324
+					$datetime_obj = DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
325
+				}
326
+				if (! $datetime_obj instanceof DateTime) {
327
+					// so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
328
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
329
+				}
330
+				$original_value = $datetime_obj;
331
+			}
332
+			if ($original_value instanceof DateTime) {
333
+				$new_value = $original_value->format('Y-m-d H:i:s');
334
+			} elseif (is_int($original_value) || is_float($original_value)) {
335
+				$new_value = date('Y-m-d H:i:s', $original_value);
336
+			} elseif ($original_value === null || $original_value === '') {
337
+				$new_value = null;
338
+			} else {
339
+				// so it's not a datetime object, unix timestamp (as string or int),
340
+				// MySQL timestamp, or even a string in the field object's format. So no idea what it is
341
+				throw new EE_Error(
342
+					sprintf(
343
+						esc_html__(
344
+						// @codingStandardsIgnoreStart
345
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
346
+							// @codingStandardsIgnoreEnd
347
+							'event_espresso'
348
+						),
349
+						$original_value,
350
+						$field_obj->get_name(),
351
+						$field_obj->get_model_name(),
352
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
353
+					)
354
+				);
355
+			}
356
+			if ($new_value !== null) {
357
+				// phpcs:disable PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
358
+				$new_value = mysql_to_rfc3339($new_value);
359
+				// phpcs:enable
360
+			}
361
+		} else {
362
+			$new_value = $original_value;
363
+		}
364
+		// are we about to send an object? just don't. We have no good way to represent it in JSON.
365
+		// can't just check using is_object() because that missed PHP incomplete objects
366
+		if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
367
+			$new_value = [
368
+				'error_code'    => 'php_object_not_return',
369
+				'error_message' => esc_html__(
370
+					'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
371
+					'event_espresso'
372
+				),
373
+			];
374
+		}
375
+		return apply_filters(
376
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
377
+			$new_value,
378
+			$field_obj,
379
+			$original_value,
380
+			$requested_version
381
+		);
382
+	}
383
+
384
+
385
+	/**
386
+	 * Prepares condition-query-parameters (like what's in where and having) from
387
+	 * the format expected in the API to use in the models
388
+	 *
389
+	 * @param array    $inputted_query_params_of_this_type
390
+	 * @param EEM_Base $model
391
+	 * @param string   $requested_version
392
+	 * @param boolean  $writing whether this data will be written to the DB, or if we're just building a query.
393
+	 *                          If we're writing to the DB, we don't expect any operators, or any logic query
394
+	 *                          parameters, and we also won't accept serialized data unless the current user has
395
+	 *                          unfiltered_html.
396
+	 * @return array
397
+	 * @throws DomainException
398
+	 * @throws EE_Error
399
+	 * @throws RestException
400
+	 * @throws InvalidDataTypeException
401
+	 * @throws InvalidInterfaceException
402
+	 * @throws InvalidArgumentException
403
+	 */
404
+	public static function prepareConditionsQueryParamsForModels(
405
+		$inputted_query_params_of_this_type,
406
+		EEM_Base $model,
407
+		$requested_version,
408
+		$writing = false
409
+	) {
410
+		$query_param_for_models = [];
411
+		$context                = new RestIncomingQueryParamContext($model, $requested_version, $writing);
412
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
413
+			$query_param_meta = new RestIncomingQueryParamMetadata($query_param_key, $query_param_value, $context);
414
+			if ($query_param_meta->getField() instanceof EE_Model_Field_Base) {
415
+				$translated_value = $query_param_meta->determineConditionsQueryParameterValue();
416
+				if (
417
+					(isset($query_param_for_models[ $query_param_meta->getQueryParamKey() ])
418
+					 && $query_param_meta->isGmtField())
419
+					|| $translated_value === null
420
+				) {
421
+					// they have already provided a non-gmt field, ignore the gmt one. That's what WP core
422
+					// currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
423
+					// OR we couldn't create a translated value from their input
424
+					continue;
425
+				}
426
+				$query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $translated_value;
427
+			} else {
428
+				$nested_query_params = $query_param_meta->determineNestedConditionQueryParameters();
429
+				if ($nested_query_params) {
430
+					$query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $nested_query_params;
431
+				}
432
+			}
433
+		}
434
+		return $query_param_for_models;
435
+	}
436
+
437
+
438
+	/**
439
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
440
+	 * gmt date field name
441
+	 *
442
+	 * @param string $field_name
443
+	 * @return boolean
444
+	 */
445
+	public static function isGmtDateFieldName($field_name)
446
+	{
447
+		$field_name = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name);
448
+		return substr($field_name, -4, 4) === '_gmt';
449
+	}
450
+
451
+
452
+	/**
453
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
454
+	 *
455
+	 * @param string $field_name
456
+	 * @return string
457
+	 */
458
+	public static function removeGmtFromFieldName($field_name)
459
+	{
460
+		if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
461
+			return $field_name;
462
+		}
463
+		$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
464
+			$field_name
465
+		);
466
+		$query_param_sans_gmt_and_sans_stars = substr(
467
+			$query_param_sans_stars,
468
+			0,
469
+			strrpos(
470
+				$field_name,
471
+				'_gmt'
472
+			)
473
+		);
474
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
475
+	}
476
+
477
+
478
+	/**
479
+	 * Takes a field name from the REST API and prepares it for the model querying
480
+	 *
481
+	 * @param string $field_name
482
+	 * @return string
483
+	 */
484
+	public static function prepareFieldNameFromJson($field_name)
485
+	{
486
+		if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
487
+			return ModelDataTranslator::removeGmtFromFieldName($field_name);
488
+		}
489
+		return $field_name;
490
+	}
491
+
492
+
493
+	/**
494
+	 * Takes array of field names from REST API and prepares for models
495
+	 *
496
+	 * @param array $field_names
497
+	 * @return array of field names (possibly include model prefixes)
498
+	 */
499
+	public static function prepareFieldNamesFromJson(array $field_names)
500
+	{
501
+		$new_array = [];
502
+		foreach ($field_names as $key => $field_name) {
503
+			$new_array[ $key ] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
504
+		}
505
+		return $new_array;
506
+	}
507
+
508
+
509
+	/**
510
+	 * Takes array where array keys are field names (possibly with model path prefixes)
511
+	 * from the REST API and prepares them for model querying
512
+	 *
513
+	 * @param array $field_names_as_keys
514
+	 * @return array
515
+	 */
516
+	public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
517
+	{
518
+		$new_array = [];
519
+		foreach ($field_names_as_keys as $field_name => $value) {
520
+			$new_array[ ModelDataTranslator::prepareFieldNameFromJson($field_name) ] = $value;
521
+		}
522
+		return $new_array;
523
+	}
524
+
525
+
526
+	/**
527
+	 * Prepares an array of model query params for use in the REST API
528
+	 *
529
+	 * @param array    $model_query_params
530
+	 * @param EEM_Base $model
531
+	 * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
532
+	 *                                     REST API
533
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
534
+	 * @throws EE_Error
535
+	 * @throws ReflectionException
536
+	 */
537
+	public static function prepareQueryParamsForRestApi(
538
+		array $model_query_params,
539
+		EEM_Base $model,
540
+		$requested_version = null
541
+	) {
542
+		if ($requested_version === null) {
543
+			$requested_version = EED_Core_Rest_Api::latest_rest_api_version();
544
+		}
545
+		$rest_query_params = $model_query_params;
546
+		if (isset($model_query_params[0])) {
547
+			$rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
548
+				$model_query_params[0],
549
+				$model,
550
+				$requested_version
551
+			);
552
+			unset($rest_query_params[0]);
553
+		}
554
+		if (isset($model_query_params['having'])) {
555
+			$rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
556
+				$model_query_params['having'],
557
+				$model,
558
+				$requested_version
559
+			);
560
+		}
561
+		return apply_filters(
562
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
563
+			$rest_query_params,
564
+			$model_query_params,
565
+			$model,
566
+			$requested_version
567
+		);
568
+	}
569
+
570
+
571
+	/**
572
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
573
+	 *
574
+	 * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
575
+	 * @param EEM_Base $model
576
+	 * @param string   $requested_version                   eg "4.8.36"
577
+	 * @return array ready for use in the rest api query params
578
+	 * @throws EE_Error
579
+	 * @throws RestException if somehow a PHP object were in the query params' values,*@throws
580
+	 * @throws ReflectionException
581
+	 *                                                      ReflectionException
582
+	 *                                                      (which would be really unusual)
583
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
584
+	 */
585
+	public static function prepareConditionsQueryParamsForRestApi(
586
+		$inputted_query_params_of_this_type,
587
+		EEM_Base $model,
588
+		$requested_version
589
+	) {
590
+		$query_param_for_models = [];
591
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
592
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
593
+				ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
594
+				$model
595
+			);
596
+			if ($field instanceof EE_Model_Field_Base) {
597
+				// did they specify an operator?
598
+				if (is_array($query_param_value)) {
599
+					$op               = $query_param_value[0];
600
+					$translated_value = [$op];
601
+					if (isset($query_param_value[1])) {
602
+						$value               = $query_param_value[1];
603
+						$translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
604
+							$field,
605
+							$value,
606
+							$requested_version
607
+						);
608
+					}
609
+				} else {
610
+					$translated_value = ModelDataTranslator::prepareFieldValueForJson(
611
+						$field,
612
+						$query_param_value,
613
+						$requested_version
614
+					);
615
+				}
616
+				$query_param_for_models[ $query_param_key ] = $translated_value;
617
+			} else {
618
+				// so it's not for a field, assume it's a logic query param key
619
+				$query_param_for_models[ $query_param_key ] =
620
+					ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
621
+						$query_param_value,
622
+						$model,
623
+						$requested_version
624
+					);
625
+			}
626
+		}
627
+		return $query_param_for_models;
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $condition_query_param_key
633
+	 * @return string
634
+	 */
635
+	public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
636
+	{
637
+		$pos_of_star = strpos($condition_query_param_key, '*');
638
+		if ($pos_of_star === false) {
639
+			return $condition_query_param_key;
640
+		}
641
+		return substr($condition_query_param_key, 0, $pos_of_star);
642
+	}
643
+
644
+
645
+	/**
646
+	 * Takes the input parameter and finds the model field that it indicates.
647
+	 *
648
+	 * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
649
+	 * @param EEM_Base $model
650
+	 * @return EE_Model_Field_Base
651
+	 * @throws EE_Error
652
+	 * @throws ReflectionException
653
+	 */
654
+	public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
655
+	{
656
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
657
+		// which will help us find the database table and column
658
+		$query_param_parts = explode('.', $query_param_name);
659
+		if (empty($query_param_parts)) {
660
+			throw new EE_Error(
661
+				sprintf(
662
+					esc_html__(
663
+						'_extract_column_name is empty when trying to extract column and table name from %s',
664
+						'event_espresso'
665
+					),
666
+					$query_param_name
667
+				)
668
+			);
669
+		}
670
+		$number_of_parts       = count($query_param_parts);
671
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
672
+		$field_name            = $last_query_param_part;
673
+		if ($number_of_parts !== 1) {
674
+			// the last part is the column name, and there are only 2parts. therefore...
675
+			$model = EE_Registry::instance()->load_model($query_param_parts[ $number_of_parts - 2 ]);
676
+		}
677
+		try {
678
+			return $model->field_settings_for($field_name, false);
679
+		} catch (EE_Error $e) {
680
+			return null;
681
+		}
682
+	}
683
+
684
+
685
+	/**
686
+	 * Returns true if $data can be easily represented in JSON.
687
+	 * Basically, objects and resources can't be represented in JSON easily.
688
+	 *
689
+	 * @param mixed $data
690
+	 * @return bool
691
+	 */
692
+	protected static function isRepresentableInJson($data)
693
+	{
694
+		return is_scalar($data)
695
+			   || is_array($data)
696
+			   || is_null($data);
697
+	}
698 698
 }
Please login to merge, or discard this patch.
core/libraries/shortcodes/EE_Attendee_Shortcodes.lib.php 2 patches
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -16,192 +16,192 @@
 block discarded – undo
16 16
 class EE_Attendee_Shortcodes extends EE_Shortcodes
17 17
 {
18 18
 
19
-    /**
20
-     * hold all extra data.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_extra;
25
-
26
-
27
-    /**
28
-     * EE_Attendee_Shortcodes constructor.
29
-     */
30
-    public function __construct()
31
-    {
32
-        parent::__construct();
33
-    }
34
-
35
-
36
-    protected function _init_props()
37
-    {
38
-        $this->label       = esc_html__('Attendee Shortcodes', 'event_espresso');
39
-        $this->description = esc_html__('All shortcodes specific to attendee related data', 'event_espresso');
40
-        $this->_shortcodes = [
41
-            '[FNAME]'                          => esc_html__('First Name of an attendee.', 'event_espresso'),
42
-            '[LNAME]'                          => esc_html__('Last Name of an attendee.', 'event_espresso'),
43
-            '[ATTENDEE_EMAIL]'                 => esc_html__('Email address for the attendee.', 'event_espresso'),
44
-            '[EDIT_ATTENDEE_LINK]'             => esc_html__(
45
-                'Edit Registration Link (typically you\'d only use this for messages going to event administrators)',
46
-                'event_espresso'
47
-            ),
48
-            '[REGISTRATION_ID]'                => esc_html__(
49
-                'Unique Registration ID for the registration',
50
-                'event_espresso'
51
-            ),
52
-            '[REGISTRATION_CODE]'              => esc_html__(
53
-                'Unique Registration Code for the registration',
54
-                'event_espresso'
55
-            ),
56
-            '[REGISTRATION_STATUS_ID]'         => esc_html__(
57
-                'Parses to the registration status for the attendee',
58
-                'event_espresso'
59
-            ),
60
-            '[REGISTRATION_STATUS_LABEL]'      => esc_html__(
61
-                'Parses to the status label for the registrant',
62
-                'event_espresso'
63
-            ),
64
-            '[REGISTRATION_TOTAL_AMOUNT_PAID]' => esc_html__(
65
-                'Parses to the total amount paid for this registration.',
66
-                'event_espresso'
67
-            ),
68
-            '[FRONTEND_EDIT_REG_LINK]'         => esc_html__(
69
-                'Generates a link for the given registration to edit this registration details on the frontend.',
70
-                'event_espresso'
71
-            ),
72
-            '[PHONE_NUMBER]'                   => esc_html__(
73
-                'The Phone Number for the Registration.',
74
-                'event_espresso'
75
-            ),
76
-            '[ADDRESS]'                        => esc_html__('The Address for the Registration', 'event_espresso'),
77
-            '[ADDRESS2]'                       => esc_html__(
78
-                'Whatever was in the address 2 field for the registration.',
79
-                'event_espresso'
80
-            ),
81
-            '[CITY]'                           => esc_html__('The city for the registration.', 'event_espresso'),
82
-            '[ZIP_PC]'                         => esc_html__(
83
-                'The ZIP (or Postal) Code for the Registration.',
84
-                'event_espresso'
85
-            ),
86
-            '[ADDRESS_STATE]'                  => esc_html__(
87
-                'The state/province for the registration.',
88
-                'event_espresso'
89
-            ),
90
-            '[COUNTRY]'                        => esc_html__('The country for the registration.', 'event_espresso'),
91
-        ];
92
-    }
93
-
94
-
95
-    /**
96
-     * handles shortcode parsing
97
-     *
98
-     * @access protected
99
-     * @param string $shortcode the shortcode to be parsed.
100
-     * @return string
101
-     * @throws EE_Error
102
-     * @throws ReflectionException
103
-     */
104
-    protected function _parser($shortcode)
105
-    {
106
-
107
-
108
-        $this->_extra = ! empty($this->_extra_data) && $this->_extra_data['data'] instanceof EE_Messages_Addressee
109
-            ? $this->_extra_data['data']
110
-            : null;
111
-
112
-        // incoming object should only be a registration object.
113
-        $registration = ! $this->_data instanceof EE_Registration
114
-            ? null
115
-            : $this->_data;
116
-
117
-        if (! $registration instanceof EE_Registration) {
118
-            // let's attempt to get the txn_id for the error message.
119
-            $txn_id  = isset($this->_extra->txn) && $this->_extra->txn instanceof EE_Transaction
120
-                ? $this->_extra->txn->ID()
121
-                : esc_html__('Unknown', 'event_espresso');
122
-            $msg     = esc_html__(
123
-                'There is no EE_Registration object in the data sent to the EE_Attendee Shortcode Parser for the messages system.',
124
-                'event_espresso'
125
-            );
126
-            $dev_msg = sprintf(
127
-                esc_html__('The transaction ID for this request is: %s', 'event_espresso'),
128
-                $txn_id
129
-            );
130
-            throw new EE_Error("{$msg}||{$msg} {$dev_msg}");
131
-        }
132
-
133
-        // attendee obj for this registration
134
-        $attendee = isset($this->_extra->registrations[ $registration->ID() ]['att_obj'])
135
-            ? $this->_extra->registrations[ $registration->ID() ]['att_obj']
136
-            : null;
137
-
138
-        if (! $attendee instanceof EE_Attendee) {
139
-            $msg     = esc_html__(
140
-                'There is no EE_Attendee object in the data sent to the EE_Attendee_Shortcode parser for the messages system.',
141
-                'event_espresso'
142
-            );
143
-            $dev_msg = sprintf(
144
-                esc_html__('The registration ID for this request is: %s', 'event_espresso'),
145
-                $registration->ID()
146
-            );
147
-            throw new EE_Error("{$msg}||{$msg} {$dev_msg}");
148
-        }
149
-
150
-        switch ($shortcode) {
151
-            case '[FNAME]':
152
-                return $attendee->fname();
153
-
154
-            case '[LNAME]':
155
-                return $attendee->lname();
156
-
157
-            case '[ATTENDEE_EMAIL]':
158
-                return $attendee->email();
159
-
160
-            case '[EDIT_ATTENDEE_LINK]':
161
-                return $registration->get_admin_edit_url();
162
-
163
-            case '[REGISTRATION_CODE]':
164
-                return $registration->reg_code();
165
-
166
-            case '[REGISTRATION_ID]':
167
-                return $registration->ID();
168
-
169
-            case '[FRONTEND_EDIT_REG_LINK]':
170
-                return $registration->edit_attendee_information_url();
171
-
172
-            case '[PHONE_NUMBER]':
173
-                return $attendee->phone();
174
-
175
-            case '[ADDRESS]':
176
-                return $attendee->address();
177
-
178
-            case '[ADDRESS2]':
179
-                return $attendee->address2();
180
-
181
-            case '[CITY]':
182
-                return $attendee->city();
183
-
184
-            case '[ZIP_PC]':
185
-                return $attendee->zip();
186
-
187
-            case '[ADDRESS_STATE]':
188
-                $state_obj = $attendee->state_obj();
189
-                return $state_obj instanceof EE_State ? $state_obj->name() : '';
190
-
191
-            case '[COUNTRY]':
192
-                $country_obj = $attendee->country_obj();
193
-                return $country_obj instanceof EE_Country ? $country_obj->name() : '';
194
-
195
-            case '[REGISTRATION_STATUS_ID]':
196
-                return $registration->status_ID();
197
-
198
-            case '[REGISTRATION_STATUS_LABEL]':
199
-                return $registration->pretty_status();
200
-
201
-            case '[REGISTRATION_TOTAL_AMOUNT_PAID]':
202
-                return $registration->pretty_paid();
203
-        }
204
-
205
-        return '';
206
-    }
19
+	/**
20
+	 * hold all extra data.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_extra;
25
+
26
+
27
+	/**
28
+	 * EE_Attendee_Shortcodes constructor.
29
+	 */
30
+	public function __construct()
31
+	{
32
+		parent::__construct();
33
+	}
34
+
35
+
36
+	protected function _init_props()
37
+	{
38
+		$this->label       = esc_html__('Attendee Shortcodes', 'event_espresso');
39
+		$this->description = esc_html__('All shortcodes specific to attendee related data', 'event_espresso');
40
+		$this->_shortcodes = [
41
+			'[FNAME]'                          => esc_html__('First Name of an attendee.', 'event_espresso'),
42
+			'[LNAME]'                          => esc_html__('Last Name of an attendee.', 'event_espresso'),
43
+			'[ATTENDEE_EMAIL]'                 => esc_html__('Email address for the attendee.', 'event_espresso'),
44
+			'[EDIT_ATTENDEE_LINK]'             => esc_html__(
45
+				'Edit Registration Link (typically you\'d only use this for messages going to event administrators)',
46
+				'event_espresso'
47
+			),
48
+			'[REGISTRATION_ID]'                => esc_html__(
49
+				'Unique Registration ID for the registration',
50
+				'event_espresso'
51
+			),
52
+			'[REGISTRATION_CODE]'              => esc_html__(
53
+				'Unique Registration Code for the registration',
54
+				'event_espresso'
55
+			),
56
+			'[REGISTRATION_STATUS_ID]'         => esc_html__(
57
+				'Parses to the registration status for the attendee',
58
+				'event_espresso'
59
+			),
60
+			'[REGISTRATION_STATUS_LABEL]'      => esc_html__(
61
+				'Parses to the status label for the registrant',
62
+				'event_espresso'
63
+			),
64
+			'[REGISTRATION_TOTAL_AMOUNT_PAID]' => esc_html__(
65
+				'Parses to the total amount paid for this registration.',
66
+				'event_espresso'
67
+			),
68
+			'[FRONTEND_EDIT_REG_LINK]'         => esc_html__(
69
+				'Generates a link for the given registration to edit this registration details on the frontend.',
70
+				'event_espresso'
71
+			),
72
+			'[PHONE_NUMBER]'                   => esc_html__(
73
+				'The Phone Number for the Registration.',
74
+				'event_espresso'
75
+			),
76
+			'[ADDRESS]'                        => esc_html__('The Address for the Registration', 'event_espresso'),
77
+			'[ADDRESS2]'                       => esc_html__(
78
+				'Whatever was in the address 2 field for the registration.',
79
+				'event_espresso'
80
+			),
81
+			'[CITY]'                           => esc_html__('The city for the registration.', 'event_espresso'),
82
+			'[ZIP_PC]'                         => esc_html__(
83
+				'The ZIP (or Postal) Code for the Registration.',
84
+				'event_espresso'
85
+			),
86
+			'[ADDRESS_STATE]'                  => esc_html__(
87
+				'The state/province for the registration.',
88
+				'event_espresso'
89
+			),
90
+			'[COUNTRY]'                        => esc_html__('The country for the registration.', 'event_espresso'),
91
+		];
92
+	}
93
+
94
+
95
+	/**
96
+	 * handles shortcode parsing
97
+	 *
98
+	 * @access protected
99
+	 * @param string $shortcode the shortcode to be parsed.
100
+	 * @return string
101
+	 * @throws EE_Error
102
+	 * @throws ReflectionException
103
+	 */
104
+	protected function _parser($shortcode)
105
+	{
106
+
107
+
108
+		$this->_extra = ! empty($this->_extra_data) && $this->_extra_data['data'] instanceof EE_Messages_Addressee
109
+			? $this->_extra_data['data']
110
+			: null;
111
+
112
+		// incoming object should only be a registration object.
113
+		$registration = ! $this->_data instanceof EE_Registration
114
+			? null
115
+			: $this->_data;
116
+
117
+		if (! $registration instanceof EE_Registration) {
118
+			// let's attempt to get the txn_id for the error message.
119
+			$txn_id  = isset($this->_extra->txn) && $this->_extra->txn instanceof EE_Transaction
120
+				? $this->_extra->txn->ID()
121
+				: esc_html__('Unknown', 'event_espresso');
122
+			$msg     = esc_html__(
123
+				'There is no EE_Registration object in the data sent to the EE_Attendee Shortcode Parser for the messages system.',
124
+				'event_espresso'
125
+			);
126
+			$dev_msg = sprintf(
127
+				esc_html__('The transaction ID for this request is: %s', 'event_espresso'),
128
+				$txn_id
129
+			);
130
+			throw new EE_Error("{$msg}||{$msg} {$dev_msg}");
131
+		}
132
+
133
+		// attendee obj for this registration
134
+		$attendee = isset($this->_extra->registrations[ $registration->ID() ]['att_obj'])
135
+			? $this->_extra->registrations[ $registration->ID() ]['att_obj']
136
+			: null;
137
+
138
+		if (! $attendee instanceof EE_Attendee) {
139
+			$msg     = esc_html__(
140
+				'There is no EE_Attendee object in the data sent to the EE_Attendee_Shortcode parser for the messages system.',
141
+				'event_espresso'
142
+			);
143
+			$dev_msg = sprintf(
144
+				esc_html__('The registration ID for this request is: %s', 'event_espresso'),
145
+				$registration->ID()
146
+			);
147
+			throw new EE_Error("{$msg}||{$msg} {$dev_msg}");
148
+		}
149
+
150
+		switch ($shortcode) {
151
+			case '[FNAME]':
152
+				return $attendee->fname();
153
+
154
+			case '[LNAME]':
155
+				return $attendee->lname();
156
+
157
+			case '[ATTENDEE_EMAIL]':
158
+				return $attendee->email();
159
+
160
+			case '[EDIT_ATTENDEE_LINK]':
161
+				return $registration->get_admin_edit_url();
162
+
163
+			case '[REGISTRATION_CODE]':
164
+				return $registration->reg_code();
165
+
166
+			case '[REGISTRATION_ID]':
167
+				return $registration->ID();
168
+
169
+			case '[FRONTEND_EDIT_REG_LINK]':
170
+				return $registration->edit_attendee_information_url();
171
+
172
+			case '[PHONE_NUMBER]':
173
+				return $attendee->phone();
174
+
175
+			case '[ADDRESS]':
176
+				return $attendee->address();
177
+
178
+			case '[ADDRESS2]':
179
+				return $attendee->address2();
180
+
181
+			case '[CITY]':
182
+				return $attendee->city();
183
+
184
+			case '[ZIP_PC]':
185
+				return $attendee->zip();
186
+
187
+			case '[ADDRESS_STATE]':
188
+				$state_obj = $attendee->state_obj();
189
+				return $state_obj instanceof EE_State ? $state_obj->name() : '';
190
+
191
+			case '[COUNTRY]':
192
+				$country_obj = $attendee->country_obj();
193
+				return $country_obj instanceof EE_Country ? $country_obj->name() : '';
194
+
195
+			case '[REGISTRATION_STATUS_ID]':
196
+				return $registration->status_ID();
197
+
198
+			case '[REGISTRATION_STATUS_LABEL]':
199
+				return $registration->pretty_status();
200
+
201
+			case '[REGISTRATION_TOTAL_AMOUNT_PAID]':
202
+				return $registration->pretty_paid();
203
+		}
204
+
205
+		return '';
206
+	}
207 207
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
             ? null
115 115
             : $this->_data;
116 116
 
117
-        if (! $registration instanceof EE_Registration) {
117
+        if ( ! $registration instanceof EE_Registration) {
118 118
             // let's attempt to get the txn_id for the error message.
119 119
             $txn_id  = isset($this->_extra->txn) && $this->_extra->txn instanceof EE_Transaction
120 120
                 ? $this->_extra->txn->ID()
@@ -131,12 +131,12 @@  discard block
 block discarded – undo
131 131
         }
132 132
 
133 133
         // attendee obj for this registration
134
-        $attendee = isset($this->_extra->registrations[ $registration->ID() ]['att_obj'])
135
-            ? $this->_extra->registrations[ $registration->ID() ]['att_obj']
134
+        $attendee = isset($this->_extra->registrations[$registration->ID()]['att_obj'])
135
+            ? $this->_extra->registrations[$registration->ID()]['att_obj']
136 136
             : null;
137 137
 
138
-        if (! $attendee instanceof EE_Attendee) {
139
-            $msg     = esc_html__(
138
+        if ( ! $attendee instanceof EE_Attendee) {
139
+            $msg = esc_html__(
140 140
                 'There is no EE_Attendee object in the data sent to the EE_Attendee_Shortcode parser for the messages system.',
141 141
                 'event_espresso'
142 142
             );
Please login to merge, or discard this patch.
core/libraries/shortcodes/EE_Attendee_List_Shortcodes.lib.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
         $att_result    = '';
160 160
         $registrations =
161 161
             isset($this->_extra_data['data']->tickets)
162
-                ? $this->_extra_data['data']->tickets[ $ticket->ID() ]['reg_objs']
162
+                ? $this->_extra_data['data']->tickets[$ticket->ID()]['reg_objs']
163 163
                 : [];
164 164
 
165 165
         // each attendee in this case should be an attendee object.
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
     private function _get_registrations_from_event(EE_Event $event)
186 186
     {
187 187
         return isset($this->_extra_data['data']->events)
188
-            ? $this->_extra_data['data']->events[ $event->ID() ]['reg_objs']
188
+            ? $this->_extra_data['data']->events[$event->ID()]['reg_objs']
189 189
             : [];
190 190
     }
191 191
 }
Please login to merge, or discard this patch.
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -19,173 +19,173 @@
 block discarded – undo
19 19
 class EE_Attendee_List_Shortcodes extends EE_Shortcodes
20 20
 {
21 21
 
22
-    public function __construct()
23
-    {
24
-        parent::__construct();
25
-    }
26
-
27
-
28
-    protected function _init_props()
29
-    {
30
-        $this->label       = esc_html__('Attendee List Shortcodes', 'event_espresso');
31
-        $this->description = esc_html__('All shortcodes specific to attendee lists', 'event_espresso');
32
-        $this->_shortcodes = [
33
-            '[ATTENDEE_LIST]' => esc_html__('Will output a list of attendees', 'event_espresso'),
34
-        ];
35
-    }
36
-
37
-
38
-    /**
39
-     * @param string $shortcode
40
-     * @return string
41
-     * @throws EE_Error
42
-     * @throws ReflectionException
43
-     */
44
-    protected function _parser($shortcode)
45
-    {
46
-        switch ($shortcode) {
47
-            case '[ATTENDEE_LIST]':
48
-                return $this->_get_attendee_list();
49
-        }
50
-        return '';
51
-    }
52
-
53
-
54
-    /**
55
-     * figure out what the incoming data is and then return the appropriate parsed value.
56
-     *
57
-     * @return string
58
-     * @throws EE_Error
59
-     * @throws ReflectionException
60
-     */
61
-    private function _get_attendee_list()
62
-    {
63
-        $this->_validate_list_requirements();
64
-
65
-        if ($this->_data['data'] instanceof EE_Messages_Addressee) {
66
-            return $this->_get_attendee_list_for_main();
67
-        }
68
-        if ($this->_data['data'] instanceof EE_Event) {
69
-            return $this->_get_attendee_list_for_event();
70
-        }
71
-        if ($this->_data['data'] instanceof EE_Ticket) {
72
-            return $this->_get_registration_list_for_ticket();
73
-        }
74
-        // prevent recursive loop
75
-        return '';
76
-    }
77
-
78
-
79
-    /**
80
-     * This returns the parsed attendee list for main template;
81
-     */
82
-    private function _get_attendee_list_for_main()
83
-    {
84
-        $valid_shortcodes = ['attendee', 'event_list', 'ticket_list', 'question_list', 'recipient_details'];
85
-        $template         = $this->_data['template'];
86
-        $data             = $this->_data['data'];
87
-        $attendees        = '';
88
-
89
-
90
-        // now we need to loop through the attendee list and send data to the EE_Parser helper.
91
-        foreach ($data->reg_objs as $registration) {
92
-            $attendees .= $this->_shortcode_helper->parse_attendee_list_template(
93
-                $template,
94
-                $registration,
95
-                $valid_shortcodes,
96
-                $this->_extra_data
97
-            );
98
-        }
99
-
100
-        return $attendees;
101
-    }
102
-
103
-
104
-    /**
105
-     * return parsed list of attendees for an event
106
-     *
107
-     * @return string
108
-     * @throws EE_Error
109
-     * @throws ReflectionException
110
-     */
111
-    private function _get_attendee_list_for_event()
112
-    {
113
-        $valid_shortcodes = ['attendee', 'ticket_list', 'question_list', 'recipient_details'];
114
-        $template         = is_array($this->_data['template']) && isset($this->_data['template']['attendee_list'])
115
-            ? $this->_data['template']['attendee_list']
116
-            : $this->_extra_data['template']['attendee_list'];
117
-        $event            = $this->_data['data'];
118
-
119
-        // let's remove any existing [EVENT_LIST] shortcode from the attendee list template so that we don't get recursion.
120
-        $template = str_replace('[EVENT_LIST]', '', $template);
121
-
122
-        // here we're setting up the attendees for the attendee_list template for THIS event.
123
-        $att_result    = '';
124
-        $registrations = $this->_get_registrations_from_event($event);
125
-
126
-        // each attendee in this case should be an attendee object.
127
-        foreach ($registrations as $registration) {
128
-            $att_result .= $this->_shortcode_helper->parse_attendee_list_template(
129
-                $template,
130
-                $registration,
131
-                $valid_shortcodes,
132
-                $this->_extra_data
133
-            );
134
-        }
135
-
136
-        return $att_result;
137
-    }
138
-
139
-
140
-    /**
141
-     * return parsed list of attendees for a ticket
142
-     *
143
-     * @return string
144
-     */
145
-    private function _get_registration_list_for_ticket()
146
-    {
147
-        $valid_shortcodes = ['attendee', 'event_list', 'question_list', 'recipient_details'];
148
-        $template         = is_array($this->_data['template']) && isset($this->_data['template']['attendee_list'])
149
-            ? $this->_data['template']['attendee_list']
150
-            : $this->_extra_data['template']['attendee_list'];
151
-        $ticket           = $this->_data['data'];
152
-
153
-        // let's remove any existing [TICKET_LIST] (or related) shortcode from the attendee list template so that we don't get recursion.
154
-        $template = str_replace('[TICKET_LIST]', '', $template);
155
-        $template = str_replace('[RECIPIENT_TICKET_LIST]', '', $template);
156
-        $template = str_replace('[PRIMARY_REGISTRANT_TICKET_LIST]', '', $template);
157
-
158
-        // here we're setting up the attendees for the attendee_list template for THIS ticket.
159
-        $att_result    = '';
160
-        $registrations =
161
-            isset($this->_extra_data['data']->tickets)
162
-                ? $this->_extra_data['data']->tickets[ $ticket->ID() ]['reg_objs']
163
-                : [];
164
-
165
-        // each attendee in this case should be an attendee object.
166
-        foreach ($registrations as $registration) {
167
-            $att_result .= $this->_shortcode_helper->parse_attendee_list_template(
168
-                $template,
169
-                $registration,
170
-                $valid_shortcodes,
171
-                $this->_extra_data
172
-            );
173
-        }
174
-
175
-        return $att_result;
176
-    }
177
-
178
-
179
-    /**
180
-     * @param EE_Event $event
181
-     * @return array|mixed
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    private function _get_registrations_from_event(EE_Event $event)
186
-    {
187
-        return isset($this->_extra_data['data']->events)
188
-            ? $this->_extra_data['data']->events[ $event->ID() ]['reg_objs']
189
-            : [];
190
-    }
22
+	public function __construct()
23
+	{
24
+		parent::__construct();
25
+	}
26
+
27
+
28
+	protected function _init_props()
29
+	{
30
+		$this->label       = esc_html__('Attendee List Shortcodes', 'event_espresso');
31
+		$this->description = esc_html__('All shortcodes specific to attendee lists', 'event_espresso');
32
+		$this->_shortcodes = [
33
+			'[ATTENDEE_LIST]' => esc_html__('Will output a list of attendees', 'event_espresso'),
34
+		];
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param string $shortcode
40
+	 * @return string
41
+	 * @throws EE_Error
42
+	 * @throws ReflectionException
43
+	 */
44
+	protected function _parser($shortcode)
45
+	{
46
+		switch ($shortcode) {
47
+			case '[ATTENDEE_LIST]':
48
+				return $this->_get_attendee_list();
49
+		}
50
+		return '';
51
+	}
52
+
53
+
54
+	/**
55
+	 * figure out what the incoming data is and then return the appropriate parsed value.
56
+	 *
57
+	 * @return string
58
+	 * @throws EE_Error
59
+	 * @throws ReflectionException
60
+	 */
61
+	private function _get_attendee_list()
62
+	{
63
+		$this->_validate_list_requirements();
64
+
65
+		if ($this->_data['data'] instanceof EE_Messages_Addressee) {
66
+			return $this->_get_attendee_list_for_main();
67
+		}
68
+		if ($this->_data['data'] instanceof EE_Event) {
69
+			return $this->_get_attendee_list_for_event();
70
+		}
71
+		if ($this->_data['data'] instanceof EE_Ticket) {
72
+			return $this->_get_registration_list_for_ticket();
73
+		}
74
+		// prevent recursive loop
75
+		return '';
76
+	}
77
+
78
+
79
+	/**
80
+	 * This returns the parsed attendee list for main template;
81
+	 */
82
+	private function _get_attendee_list_for_main()
83
+	{
84
+		$valid_shortcodes = ['attendee', 'event_list', 'ticket_list', 'question_list', 'recipient_details'];
85
+		$template         = $this->_data['template'];
86
+		$data             = $this->_data['data'];
87
+		$attendees        = '';
88
+
89
+
90
+		// now we need to loop through the attendee list and send data to the EE_Parser helper.
91
+		foreach ($data->reg_objs as $registration) {
92
+			$attendees .= $this->_shortcode_helper->parse_attendee_list_template(
93
+				$template,
94
+				$registration,
95
+				$valid_shortcodes,
96
+				$this->_extra_data
97
+			);
98
+		}
99
+
100
+		return $attendees;
101
+	}
102
+
103
+
104
+	/**
105
+	 * return parsed list of attendees for an event
106
+	 *
107
+	 * @return string
108
+	 * @throws EE_Error
109
+	 * @throws ReflectionException
110
+	 */
111
+	private function _get_attendee_list_for_event()
112
+	{
113
+		$valid_shortcodes = ['attendee', 'ticket_list', 'question_list', 'recipient_details'];
114
+		$template         = is_array($this->_data['template']) && isset($this->_data['template']['attendee_list'])
115
+			? $this->_data['template']['attendee_list']
116
+			: $this->_extra_data['template']['attendee_list'];
117
+		$event            = $this->_data['data'];
118
+
119
+		// let's remove any existing [EVENT_LIST] shortcode from the attendee list template so that we don't get recursion.
120
+		$template = str_replace('[EVENT_LIST]', '', $template);
121
+
122
+		// here we're setting up the attendees for the attendee_list template for THIS event.
123
+		$att_result    = '';
124
+		$registrations = $this->_get_registrations_from_event($event);
125
+
126
+		// each attendee in this case should be an attendee object.
127
+		foreach ($registrations as $registration) {
128
+			$att_result .= $this->_shortcode_helper->parse_attendee_list_template(
129
+				$template,
130
+				$registration,
131
+				$valid_shortcodes,
132
+				$this->_extra_data
133
+			);
134
+		}
135
+
136
+		return $att_result;
137
+	}
138
+
139
+
140
+	/**
141
+	 * return parsed list of attendees for a ticket
142
+	 *
143
+	 * @return string
144
+	 */
145
+	private function _get_registration_list_for_ticket()
146
+	{
147
+		$valid_shortcodes = ['attendee', 'event_list', 'question_list', 'recipient_details'];
148
+		$template         = is_array($this->_data['template']) && isset($this->_data['template']['attendee_list'])
149
+			? $this->_data['template']['attendee_list']
150
+			: $this->_extra_data['template']['attendee_list'];
151
+		$ticket           = $this->_data['data'];
152
+
153
+		// let's remove any existing [TICKET_LIST] (or related) shortcode from the attendee list template so that we don't get recursion.
154
+		$template = str_replace('[TICKET_LIST]', '', $template);
155
+		$template = str_replace('[RECIPIENT_TICKET_LIST]', '', $template);
156
+		$template = str_replace('[PRIMARY_REGISTRANT_TICKET_LIST]', '', $template);
157
+
158
+		// here we're setting up the attendees for the attendee_list template for THIS ticket.
159
+		$att_result    = '';
160
+		$registrations =
161
+			isset($this->_extra_data['data']->tickets)
162
+				? $this->_extra_data['data']->tickets[ $ticket->ID() ]['reg_objs']
163
+				: [];
164
+
165
+		// each attendee in this case should be an attendee object.
166
+		foreach ($registrations as $registration) {
167
+			$att_result .= $this->_shortcode_helper->parse_attendee_list_template(
168
+				$template,
169
+				$registration,
170
+				$valid_shortcodes,
171
+				$this->_extra_data
172
+			);
173
+		}
174
+
175
+		return $att_result;
176
+	}
177
+
178
+
179
+	/**
180
+	 * @param EE_Event $event
181
+	 * @return array|mixed
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	private function _get_registrations_from_event(EE_Event $event)
186
+	{
187
+		return isset($this->_extra_data['data']->events)
188
+			? $this->_extra_data['data']->events[ $event->ID() ]['reg_objs']
189
+			: [];
190
+	}
191 191
 }
Please login to merge, or discard this patch.