Completed
Branch FET-10304-welcome-to-vue (644299)
by
unknown
94:54 queued 83:07
created
core/db_models/fields/EE_Primary_Key_Field_Base.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -2,24 +2,24 @@
 block discarded – undo
2 2
 
3 3
 abstract class EE_Primary_Key_Field_Base extends EE_Field_With_Model_Name
4 4
 {
5
-    /**
6
-     * Overrides parent so it doesn't need to provide so many non-applicable fields
7
-     *
8
-     * @param string $table_column
9
-     * @param string $nicename
10
-     */
11
-    public function __construct($table_column, $nicename, $default)
12
-    {
13
-        parent::__construct($table_column, $nicename, false, $default, null);
14
-    }
5
+	/**
6
+	 * Overrides parent so it doesn't need to provide so many non-applicable fields
7
+	 *
8
+	 * @param string $table_column
9
+	 * @param string $nicename
10
+	 */
11
+	public function __construct($table_column, $nicename, $default)
12
+	{
13
+		parent::__construct($table_column, $nicename, false, $default, null);
14
+	}
15 15
 
16
-    /**
17
-     * @param $table_alias
18
-     * @param $name
19
-     */
20
-    function _construct_finalize($table_alias, $name, $model_name)
21
-    {
22
-        $this->_model_name_pointed_to = $model_name;
23
-        parent::_construct_finalize($table_alias, $name, $model_name);
24
-    }
16
+	/**
17
+	 * @param $table_alias
18
+	 * @param $name
19
+	 */
20
+	function _construct_finalize($table_alias, $name, $model_name)
21
+	{
22
+		$this->_model_name_pointed_to = $model_name;
23
+		parent::_construct_finalize($table_alias, $name, $model_name);
24
+	}
25 25
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Field_With_Model_Name.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -8,83 +8,83 @@
 block discarded – undo
8 8
  */
9 9
 abstract class EE_Field_With_Model_Name extends EE_Model_Field_Base
10 10
 {
11
-    /**
12
-     * Usually the name of a single model. However, as in the case for custom post types,
13
-     * it can actually be an array of models
14
-     *
15
-     * @var string or array
16
-     */
17
-    protected $_model_name_pointed_to;
11
+	/**
12
+	 * Usually the name of a single model. However, as in the case for custom post types,
13
+	 * it can actually be an array of models
14
+	 *
15
+	 * @var string or array
16
+	 */
17
+	protected $_model_name_pointed_to;
18 18
 
19
-    /**
20
-     * @param string  $table_column  name fo column for field
21
-     * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
-     * @param boolean $nullable
23
-     * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
-     *                               dbe a string
25
-     * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
-     *                               "EEM_"
27
-     */
28
-    function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
-    {
30
-        $this->_model_name_pointed_to = $model_name;
31
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
32
-    }
19
+	/**
20
+	 * @param string  $table_column  name fo column for field
21
+	 * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
+	 * @param boolean $nullable
23
+	 * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
+	 *                               dbe a string
25
+	 * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
+	 *                               "EEM_"
27
+	 */
28
+	function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
+	{
30
+		$this->_model_name_pointed_to = $model_name;
31
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
32
+	}
33 33
 
34
-    /**
35
-     * Returns the name of the model(s) pointed to
36
-     *
37
-     * @deprecated since version 4.6.7
38
-     * @return mixed string or array of strings
39
-     */
40
-    function get_model_name_pointed_to()
41
-    {
42
-        EE_Error::doing_it_wrong('get_model_name_pointed_to',
43
-            __('This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
44
-                'event_espresso'), '4.6.7');
45
-        return $this->_model_name_pointed_to;
46
-    }
34
+	/**
35
+	 * Returns the name of the model(s) pointed to
36
+	 *
37
+	 * @deprecated since version 4.6.7
38
+	 * @return mixed string or array of strings
39
+	 */
40
+	function get_model_name_pointed_to()
41
+	{
42
+		EE_Error::doing_it_wrong('get_model_name_pointed_to',
43
+			__('This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
44
+				'event_espresso'), '4.6.7');
45
+		return $this->_model_name_pointed_to;
46
+	}
47 47
 
48
-    /**
49
-     * Gets the model names pointed to by this field, always as an array
50
-     * (even if there's only one)
51
-     *
52
-     * @return array of model names pointed to by this field
53
-     */
54
-    function get_model_names_pointed_to()
55
-    {
56
-        if (is_array($this->_model_name_pointed_to)) {
57
-            return $this->_model_name_pointed_to;
58
-        } else {
59
-            return array($this->_model_name_pointed_to);
60
-        }
61
-    }
48
+	/**
49
+	 * Gets the model names pointed to by this field, always as an array
50
+	 * (even if there's only one)
51
+	 *
52
+	 * @return array of model names pointed to by this field
53
+	 */
54
+	function get_model_names_pointed_to()
55
+	{
56
+		if (is_array($this->_model_name_pointed_to)) {
57
+			return $this->_model_name_pointed_to;
58
+		} else {
59
+			return array($this->_model_name_pointed_to);
60
+		}
61
+	}
62 62
 
63
-    /**
64
-     * Returns the model's classname (eg EE_Event instead of just Event)
65
-     *
66
-     * @return array
67
-     */
68
-    function get_model_class_names_pointed_to()
69
-    {
70
-        $model_names = array();
71
-        if (is_array($this->_model_name_pointed_to)) {
72
-            foreach ($this->_model_name_pointed_to as $model_name) {
73
-                $model_names[] = "EE_" . $model_name;
74
-            }
75
-        } else {
76
-            $model_names = array("EE_" . $this->_model_name_pointed_to);
77
-        }
78
-        return $model_names;
79
-    }
63
+	/**
64
+	 * Returns the model's classname (eg EE_Event instead of just Event)
65
+	 *
66
+	 * @return array
67
+	 */
68
+	function get_model_class_names_pointed_to()
69
+	{
70
+		$model_names = array();
71
+		if (is_array($this->_model_name_pointed_to)) {
72
+			foreach ($this->_model_name_pointed_to as $model_name) {
73
+				$model_names[] = "EE_" . $model_name;
74
+			}
75
+		} else {
76
+			$model_names = array("EE_" . $this->_model_name_pointed_to);
77
+		}
78
+		return $model_names;
79
+	}
80 80
 
81
-    function is_model_obj_of_type_pointed_to($model_obj_or_ID)
82
-    {
83
-        foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
84
-            if ($model_obj_or_ID instanceof $model_obj_classname) {
85
-                return true;
86
-            }
87
-        }
88
-        return false;
89
-    }
81
+	function is_model_obj_of_type_pointed_to($model_obj_or_ID)
82
+	{
83
+		foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
84
+			if ($model_obj_or_ID instanceof $model_obj_classname) {
85
+				return true;
86
+			}
87
+		}
88
+		return false;
89
+	}
90 90
 }
Please login to merge, or discard this patch.
core/db_models/relations/EE_HABTM_Relation.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -12,203 +12,203 @@
 block discarded – undo
12 12
  */
13 13
 class EE_HABTM_Relation extends EE_Model_Relation_Base
14 14
 {
15
-    /**
16
-     * Model which defines the relation between two other models. Eg, the EE_Event_Question_Group model,
17
-     * which joins EE_Event and EE_Question_Group
18
-     *
19
-     * @var EEM_Base
20
-     */
21
-    protected $_joining_model_name;
22
-
23
-    protected $_model_relation_chain_to_join_model;
24
-
25
-
26
-    /**
27
-     * Object representing the relationship between two models. HasAndBelongsToMany relations always use a join-table
28
-     * (and an ee joining-model.) This knows how to join the models,
29
-     * get related models across the relation, and add-and-remove the relationships.
30
-     *
31
-     * @param bool    $joining_model_name
32
-     * @param boolean $block_deletes                 for this type of relation, we block by default for now. if there
33
-     *                                               are related models across this relation, block (prevent and add an
34
-     *                                               error) the deletion of this model
35
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
36
-     *                                               default
37
-     */
38
-    public function __construct($joining_model_name, $block_deletes = true, $blocking_delete_error_message = '')
39
-    {
40
-        $this->_joining_model_name = $joining_model_name;
41
-        parent::__construct($block_deletes, $blocking_delete_error_message);
42
-    }
43
-
44
-    /**
45
-     * Gets the joining model's object
46
-     *
47
-     * @return EEM_Base
48
-     */
49
-    public function get_join_model()
50
-    {
51
-        return $this->_get_model($this->_joining_model_name);
52
-    }
53
-
54
-
55
-    /**
56
-     * Gets the SQL string for joining the main model's table containing the pk to the join table. Eg "LEFT JOIN
57
-     * real_join_table AS join_table_alias ON this_table_alias.pk = join_table_alias.fk_to_this_table"
58
-     *
59
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
60
-     * @return string of SQL
61
-     * @throws \EE_Error
62
-     */
63
-    public function get_join_to_intermediate_model_statement($model_relation_chain)
64
-    {
65
-        //create sql like
66
-        //LEFT JOIN join_table AS join_table_alias ON this_table_alias.this_table_pk = join_table_alias.join_table_fk_to_this
67
-        //LEFT JOIN other_table AS other_table_alias ON join_table_alias.join_table_fk_to_other = other_table_alias.other_table_pk
68
-        //remember the model relation chain to the JOIN model, because we'll
69
-        //need it for get_join_statement()
70
-        $this->_model_relation_chain_to_join_model = $model_relation_chain;
71
-        $this_table_pk_field                       = $this->get_this_model()->get_primary_key_field();//get_foreign_key_to($this->get_other_model()->get_this_model_name());
72
-        $join_table_fk_field_to_this_table         = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
73
-        $this_table_alias                          = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
74
-                $this->get_this_model()->get_this_model_name()) . $this_table_pk_field->get_table_alias();
75
-
76
-        $join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
77
-                $this->get_join_model()->get_this_model_name()) . $join_table_fk_field_to_this_table->get_table_alias();
78
-        $join_table       = $this->get_join_model()->get_table_for_alias($join_table_alias);
79
-        //phew! ok, we have all the info we need, now we can create the SQL join string
80
-        $SQL = $this->_left_join($join_table, $join_table_alias, $join_table_fk_field_to_this_table->get_table_column(),
81
-                $this_table_alias,
82
-                $this_table_pk_field->get_table_column()) . $this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias);
83
-
84
-        return $SQL;
85
-    }
86
-
87
-
88
-    /**
89
-     * Gets the SQL string for joining the join table to the other model's pk's table. Eg "LEFT JOIN real_other_table
90
-     * AS other_table_alias ON join_table_alias.fk_to_other_table = other_table_alias.pk" If you want to join between
91
-     * modelA -> joinModelAB -> modelB (eg, Event -> Event_Question_Group -> Question_Group), you should prepend the
92
-     * result of this function with results from get_join_to_intermediate_model_statement(), so that you join first to
93
-     * the intermediate join table, and then to the other model's pk's table
94
-     *
95
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
96
-     * @return string of SQL
97
-     * @throws \EE_Error
98
-     */
99
-    public function get_join_statement($model_relation_chain)
100
-    {
101
-        if ($this->_model_relation_chain_to_join_model === null) {
102
-            throw new EE_Error(sprintf(__('When using EE_HABTM_Relation to create a join, you must call get_join_to_intermediate_model_statement BEFORE get_join_statement',
103
-                'event_espresso')));
104
-        }
105
-        $join_table_fk_field_to_this_table  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
106
-        $join_table_alias                   = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($this->_model_relation_chain_to_join_model,
107
-                $this->get_join_model()->get_this_model_name()) . $join_table_fk_field_to_this_table->get_table_alias();
108
-        $other_table_pk_field               = $this->get_other_model()->get_primary_key_field();
109
-        $join_table_fk_field_to_other_table = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
110
-        $other_table_alias                  = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
111
-                $this->get_other_model()->get_this_model_name()) . $other_table_pk_field->get_table_alias();
112
-        $other_table                        = $this->get_other_model()->get_table_for_alias($other_table_alias);
113
-
114
-        $SQL = $this->_left_join($other_table, $other_table_alias, $other_table_pk_field->get_table_column(),
115
-                $join_table_alias,
116
-                $join_table_fk_field_to_other_table->get_table_column()) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
117
-        return $SQL;
118
-    }
119
-
120
-
121
-    /**
122
-     * Ensures there is an entry in the join table between these two models. Feel free to do this manually if you like.
123
-     * If the join table has additional columns (eg, the Event_Question_Group table has a is_primary column), then
124
-     * you'll want to directly use the EEM_Event_Question_Group model to add the entry to the table and set those extra
125
-     * columns' values
126
-     *
127
-     * @param EE_Base_Class|int $this_obj_or_id
128
-     * @param EE_Base_Class|int $other_obj_or_id
129
-     * @param array             $extra_join_model_fields_n_values col=>val pairs that are used as extra conditions for
130
-     *                                                            checking existing values and for setting new rows if
131
-     *                                                            no exact matches.
132
-     * @return EE_Base_Class
133
-     * @throws \EE_Error
134
-     */
135
-    public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array())
136
-    {
137
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
138
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
139
-        //check if such a relationship already exists
140
-        $join_model_fk_to_this_model  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
141
-        $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
142
-
143
-        $cols_n_values = array(
144
-            $join_model_fk_to_this_model->get_name()  => $this_model_obj->ID(),
145
-            $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(),
146
-        );
147
-
148
-        //if $where_query exists lets add them to the query_params.
149
-        if (! empty($extra_join_model_fields_n_values)) {
150
-            //make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name)
151
-            //make sure we strip THIS models name from the query param
152
-            $parsed_query = array();
153
-            foreach ($extra_join_model_fields_n_values as $query_param => $val) {
154
-                $query_param                = str_replace($this->get_join_model()->get_this_model_name() . ".", "",
155
-                    $query_param);
156
-                $parsed_query[$query_param] = $val;
157
-            }
158
-            $cols_n_values = array_merge($cols_n_values, $parsed_query);
159
-        }
160
-
161
-        $query_params = array($cols_n_values);
162
-
163
-
164
-        $existing_entry_in_join_table = $this->get_join_model()->get_one($query_params);
165
-        //if there is already an entry in the join table, indicating a relationship, we're done
166
-        //again, if you want more sophisticated logic or insertions (handling more columns than just 2 foreign keys to
167
-        //the other tables, use the joining model directly!
168
-        if (! $existing_entry_in_join_table) {
169
-            $this->get_join_model()->insert($cols_n_values);
170
-        }
171
-        return $other_model_obj;
172
-    }
173
-
174
-
175
-    /**
176
-     * Deletes any rows in the join table that have foreign keys matching the other model objects specified
177
-     *
178
-     * @param EE_Base_Class|int $this_obj_or_id
179
-     * @param EE_Base_Class|int $other_obj_or_id
180
-     * @param array             $where_query col=>val pairs that are used as extra conditions for checking existing
181
-     *                                       values and for removing existing rows if exact matches exist.
182
-     * @return EE_Base_Class
183
-     * @throws \EE_Error
184
-     */
185
-    public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array())
186
-    {
187
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
188
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
189
-        //check if such a relationship already exists
190
-        $join_model_fk_to_this_model  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
191
-        $join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
192
-
193
-        $cols_n_values = array(
194
-            $join_model_fk_to_this_model->get_name()  => $this_model_obj->ID(),
195
-            $join_model_fk_to_other_model->get_name() => $other_model_obj->ID(),
196
-        );
197
-
198
-        //if $where_query exists lets add them to the query_params.
199
-        if (! empty($where_query)) {
200
-            //make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name)
201
-            //make sure we strip THIS models name from the query param
202
-            $parsed_query = array();
203
-            foreach ($where_query as $query_param => $val) {
204
-                $query_param                = str_replace($this->get_join_model()->get_this_model_name() . ".", "",
205
-                    $query_param);
206
-                $parsed_query[$query_param] = $val;
207
-            }
208
-            $cols_n_values = array_merge($cols_n_values, $parsed_query);
209
-        }
210
-
211
-        $this->get_join_model()->delete(array($cols_n_values));
212
-        return $other_model_obj;
213
-    }
15
+	/**
16
+	 * Model which defines the relation between two other models. Eg, the EE_Event_Question_Group model,
17
+	 * which joins EE_Event and EE_Question_Group
18
+	 *
19
+	 * @var EEM_Base
20
+	 */
21
+	protected $_joining_model_name;
22
+
23
+	protected $_model_relation_chain_to_join_model;
24
+
25
+
26
+	/**
27
+	 * Object representing the relationship between two models. HasAndBelongsToMany relations always use a join-table
28
+	 * (and an ee joining-model.) This knows how to join the models,
29
+	 * get related models across the relation, and add-and-remove the relationships.
30
+	 *
31
+	 * @param bool    $joining_model_name
32
+	 * @param boolean $block_deletes                 for this type of relation, we block by default for now. if there
33
+	 *                                               are related models across this relation, block (prevent and add an
34
+	 *                                               error) the deletion of this model
35
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
36
+	 *                                               default
37
+	 */
38
+	public function __construct($joining_model_name, $block_deletes = true, $blocking_delete_error_message = '')
39
+	{
40
+		$this->_joining_model_name = $joining_model_name;
41
+		parent::__construct($block_deletes, $blocking_delete_error_message);
42
+	}
43
+
44
+	/**
45
+	 * Gets the joining model's object
46
+	 *
47
+	 * @return EEM_Base
48
+	 */
49
+	public function get_join_model()
50
+	{
51
+		return $this->_get_model($this->_joining_model_name);
52
+	}
53
+
54
+
55
+	/**
56
+	 * Gets the SQL string for joining the main model's table containing the pk to the join table. Eg "LEFT JOIN
57
+	 * real_join_table AS join_table_alias ON this_table_alias.pk = join_table_alias.fk_to_this_table"
58
+	 *
59
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
60
+	 * @return string of SQL
61
+	 * @throws \EE_Error
62
+	 */
63
+	public function get_join_to_intermediate_model_statement($model_relation_chain)
64
+	{
65
+		//create sql like
66
+		//LEFT JOIN join_table AS join_table_alias ON this_table_alias.this_table_pk = join_table_alias.join_table_fk_to_this
67
+		//LEFT JOIN other_table AS other_table_alias ON join_table_alias.join_table_fk_to_other = other_table_alias.other_table_pk
68
+		//remember the model relation chain to the JOIN model, because we'll
69
+		//need it for get_join_statement()
70
+		$this->_model_relation_chain_to_join_model = $model_relation_chain;
71
+		$this_table_pk_field                       = $this->get_this_model()->get_primary_key_field();//get_foreign_key_to($this->get_other_model()->get_this_model_name());
72
+		$join_table_fk_field_to_this_table         = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
73
+		$this_table_alias                          = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
74
+				$this->get_this_model()->get_this_model_name()) . $this_table_pk_field->get_table_alias();
75
+
76
+		$join_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
77
+				$this->get_join_model()->get_this_model_name()) . $join_table_fk_field_to_this_table->get_table_alias();
78
+		$join_table       = $this->get_join_model()->get_table_for_alias($join_table_alias);
79
+		//phew! ok, we have all the info we need, now we can create the SQL join string
80
+		$SQL = $this->_left_join($join_table, $join_table_alias, $join_table_fk_field_to_this_table->get_table_column(),
81
+				$this_table_alias,
82
+				$this_table_pk_field->get_table_column()) . $this->get_join_model()->_construct_internal_join_to_table_with_alias($join_table_alias);
83
+
84
+		return $SQL;
85
+	}
86
+
87
+
88
+	/**
89
+	 * Gets the SQL string for joining the join table to the other model's pk's table. Eg "LEFT JOIN real_other_table
90
+	 * AS other_table_alias ON join_table_alias.fk_to_other_table = other_table_alias.pk" If you want to join between
91
+	 * modelA -> joinModelAB -> modelB (eg, Event -> Event_Question_Group -> Question_Group), you should prepend the
92
+	 * result of this function with results from get_join_to_intermediate_model_statement(), so that you join first to
93
+	 * the intermediate join table, and then to the other model's pk's table
94
+	 *
95
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
96
+	 * @return string of SQL
97
+	 * @throws \EE_Error
98
+	 */
99
+	public function get_join_statement($model_relation_chain)
100
+	{
101
+		if ($this->_model_relation_chain_to_join_model === null) {
102
+			throw new EE_Error(sprintf(__('When using EE_HABTM_Relation to create a join, you must call get_join_to_intermediate_model_statement BEFORE get_join_statement',
103
+				'event_espresso')));
104
+		}
105
+		$join_table_fk_field_to_this_table  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
106
+		$join_table_alias                   = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($this->_model_relation_chain_to_join_model,
107
+				$this->get_join_model()->get_this_model_name()) . $join_table_fk_field_to_this_table->get_table_alias();
108
+		$other_table_pk_field               = $this->get_other_model()->get_primary_key_field();
109
+		$join_table_fk_field_to_other_table = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
110
+		$other_table_alias                  = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
111
+				$this->get_other_model()->get_this_model_name()) . $other_table_pk_field->get_table_alias();
112
+		$other_table                        = $this->get_other_model()->get_table_for_alias($other_table_alias);
113
+
114
+		$SQL = $this->_left_join($other_table, $other_table_alias, $other_table_pk_field->get_table_column(),
115
+				$join_table_alias,
116
+				$join_table_fk_field_to_other_table->get_table_column()) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
117
+		return $SQL;
118
+	}
119
+
120
+
121
+	/**
122
+	 * Ensures there is an entry in the join table between these two models. Feel free to do this manually if you like.
123
+	 * If the join table has additional columns (eg, the Event_Question_Group table has a is_primary column), then
124
+	 * you'll want to directly use the EEM_Event_Question_Group model to add the entry to the table and set those extra
125
+	 * columns' values
126
+	 *
127
+	 * @param EE_Base_Class|int $this_obj_or_id
128
+	 * @param EE_Base_Class|int $other_obj_or_id
129
+	 * @param array             $extra_join_model_fields_n_values col=>val pairs that are used as extra conditions for
130
+	 *                                                            checking existing values and for setting new rows if
131
+	 *                                                            no exact matches.
132
+	 * @return EE_Base_Class
133
+	 * @throws \EE_Error
134
+	 */
135
+	public function add_relation_to($this_obj_or_id, $other_obj_or_id, $extra_join_model_fields_n_values = array())
136
+	{
137
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
138
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
139
+		//check if such a relationship already exists
140
+		$join_model_fk_to_this_model  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
141
+		$join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
142
+
143
+		$cols_n_values = array(
144
+			$join_model_fk_to_this_model->get_name()  => $this_model_obj->ID(),
145
+			$join_model_fk_to_other_model->get_name() => $other_model_obj->ID(),
146
+		);
147
+
148
+		//if $where_query exists lets add them to the query_params.
149
+		if (! empty($extra_join_model_fields_n_values)) {
150
+			//make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name)
151
+			//make sure we strip THIS models name from the query param
152
+			$parsed_query = array();
153
+			foreach ($extra_join_model_fields_n_values as $query_param => $val) {
154
+				$query_param                = str_replace($this->get_join_model()->get_this_model_name() . ".", "",
155
+					$query_param);
156
+				$parsed_query[$query_param] = $val;
157
+			}
158
+			$cols_n_values = array_merge($cols_n_values, $parsed_query);
159
+		}
160
+
161
+		$query_params = array($cols_n_values);
162
+
163
+
164
+		$existing_entry_in_join_table = $this->get_join_model()->get_one($query_params);
165
+		//if there is already an entry in the join table, indicating a relationship, we're done
166
+		//again, if you want more sophisticated logic or insertions (handling more columns than just 2 foreign keys to
167
+		//the other tables, use the joining model directly!
168
+		if (! $existing_entry_in_join_table) {
169
+			$this->get_join_model()->insert($cols_n_values);
170
+		}
171
+		return $other_model_obj;
172
+	}
173
+
174
+
175
+	/**
176
+	 * Deletes any rows in the join table that have foreign keys matching the other model objects specified
177
+	 *
178
+	 * @param EE_Base_Class|int $this_obj_or_id
179
+	 * @param EE_Base_Class|int $other_obj_or_id
180
+	 * @param array             $where_query col=>val pairs that are used as extra conditions for checking existing
181
+	 *                                       values and for removing existing rows if exact matches exist.
182
+	 * @return EE_Base_Class
183
+	 * @throws \EE_Error
184
+	 */
185
+	public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array())
186
+	{
187
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
188
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
189
+		//check if such a relationship already exists
190
+		$join_model_fk_to_this_model  = $this->get_join_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
191
+		$join_model_fk_to_other_model = $this->get_join_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
192
+
193
+		$cols_n_values = array(
194
+			$join_model_fk_to_this_model->get_name()  => $this_model_obj->ID(),
195
+			$join_model_fk_to_other_model->get_name() => $other_model_obj->ID(),
196
+		);
197
+
198
+		//if $where_query exists lets add them to the query_params.
199
+		if (! empty($where_query)) {
200
+			//make sure we strip any of the join model names from the $where_query cause we don't need that in here (why? because client code may have used the same conditionals for get_all_related which DOES need the join model name)
201
+			//make sure we strip THIS models name from the query param
202
+			$parsed_query = array();
203
+			foreach ($where_query as $query_param => $val) {
204
+				$query_param                = str_replace($this->get_join_model()->get_this_model_name() . ".", "",
205
+					$query_param);
206
+				$parsed_query[$query_param] = $val;
207
+			}
208
+			$cols_n_values = array_merge($cols_n_values, $parsed_query);
209
+		}
210
+
211
+		$this->get_join_model()->delete(array($cols_n_values));
212
+		return $other_model_obj;
213
+	}
214 214
 }
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +734 added lines, -734 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 EE_Registry::instance()->load_class('Processor_Base');
5 5
 
@@ -16,737 +16,737 @@  discard block
 block discarded – undo
16 16
 class EE_Payment_Processor extends EE_Processor_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_Payment_Processor $_instance
21
-     * @access    private
22
-     */
23
-    private static $_instance;
24
-
25
-
26
-
27
-    /**
28
-     * @singleton method used to instantiate class object
29
-     * @access    public
30
-     * @return EE_Payment_Processor instance
31
-     */
32
-    public static function instance()
33
-    {
34
-        // check if class object is instantiated
35
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
-            self::$_instance = new self();
37
-        }
38
-        return self::$_instance;
39
-    }
40
-
41
-
42
-
43
-    /**
44
-     *private constructor to prevent direct creation
45
-     *
46
-     * @Constructor
47
-     * @access private
48
-     */
49
-    private function __construct()
50
-    {
51
-        do_action('AHEE__EE_Payment_Processor__construct');
52
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
-     * appropriately. Saves the payment that is generated
60
-     *
61
-     * @param EE_Payment_Method    $payment_method
62
-     * @param EE_Transaction       $transaction
63
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
-     *                                           Leave null if payment is for the full amount owing
65
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
-     *                                           Receive_form_submission() should have
67
-     *                                           already been called on the billing form
68
-     *                                           (ie, its inputs should have their normalized values set).
69
-     * @param string               $return_url   string used mostly by offsite gateways to specify
70
-     *                                           where to go AFTER the offsite gateway
71
-     * @param string               $method       like 'CART', indicates who the client who called this was
72
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
-     * @param boolean              $update_txn   whether or not to call
74
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
-     * @return \EE_Payment
77
-     * @throws \EE_Error
78
-     */
79
-    public function process_payment(
80
-        EE_Payment_Method $payment_method,
81
-        EE_Transaction $transaction,
82
-        $amount = null,
83
-        $billing_form = null,
84
-        $return_url = null,
85
-        $method = 'CART',
86
-        $by_admin = false,
87
-        $update_txn = true,
88
-        $cancel_url = ''
89
-    ) {
90
-        if ((float)$amount < 0) {
91
-            throw new EE_Error(
92
-                sprintf(
93
-                    __(
94
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
-                        'event_espresso'
96
-                    ),
97
-                    $amount,
98
-                    $transaction->ID()
99
-                )
100
-            );
101
-        }
102
-        // verify payment method
103
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
-        // verify transaction
105
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
106
-        $transaction->set_payment_method_ID($payment_method->ID());
107
-        // verify payment method type
108
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
-            $payment = $payment_method->type_obj()->process_payment(
110
-                $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
112
-                $billing_form,
113
-                $return_url,
114
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
-                $method,
116
-                $by_admin
117
-            );
118
-            // check if payment method uses an off-site gateway
119
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
-                // don't process payments for off-site gateways yet because no payment has occurred yet
121
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
-            }
123
-            return $payment;
124
-        } else {
125
-            EE_Error::add_error(
126
-                sprintf(
127
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
-                    '<br/>',
129
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
130
-                ), __FILE__, __FUNCTION__, __LINE__
131
-            );
132
-            return null;
133
-        }
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * @param EE_Transaction|int $transaction
140
-     * @param EE_Payment_Method  $payment_method
141
-     * @throws EE_Error
142
-     * @return string
143
-     */
144
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
-    {
146
-        /** @type \EE_Transaction $transaction */
147
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
-        $primary_reg = $transaction->primary_registration();
149
-        if ( ! $primary_reg instanceof EE_Registration) {
150
-            throw new EE_Error(
151
-                sprintf(
152
-                    __(
153
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
-                        "event_espresso"
155
-                    ),
156
-                    $transaction->ID()
157
-                )
158
-            );
159
-        }
160
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
-        $url = add_query_arg(
162
-            array(
163
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
-                'ee_payment_method' => $payment_method->slug(),
165
-            ),
166
-            EE_Registry::instance()->CFG->core->txn_page_url()
167
-        );
168
-        return $url;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
-     * we can easily find what registration the IPN is for and what payment method.
176
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
177
-     * If a payment is found for the IPN info, it is saved.
178
-     *
179
-     * @param array              $_req_data            eg $_REQUEST
180
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
-     * @param boolean            $update_txn           whether or not to call
183
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
-     *                                                 or is processed manually ( false like Mijireh )
186
-     * @throws EE_Error
187
-     * @throws Exception
188
-     * @return EE_Payment
189
-     */
190
-    public function process_ipn(
191
-        $_req_data,
192
-        $transaction = null,
193
-        $payment_method = null,
194
-        $update_txn = true,
195
-        $separate_IPN_request = true
196
-    ) {
197
-        EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
-        EE_Processor_Base::set_IPN($separate_IPN_request);
200
-        $obj_for_log = null;
201
-        if ($transaction instanceof EE_Transaction) {
202
-            $obj_for_log = $transaction;
203
-            if ($payment_method instanceof EE_Payment_Method) {
204
-                $obj_for_log = EEM_Payment::instance()->get_one(
205
-                    array(
206
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
-                        'order_by' => array('PAY_timestamp' => 'desc'),
208
-                    )
209
-                );
210
-            }
211
-        } else if ($payment_method instanceof EE_Payment) {
212
-            $obj_for_log = $payment_method;
213
-        }
214
-        $log = EEM_Change_Log::instance()->log(
215
-            EEM_Change_Log::type_gateway,
216
-            array('IPN data received' => $_req_data),
217
-            $obj_for_log
218
-        );
219
-        try {
220
-            /**
221
-             * @var EE_Payment $payment
222
-             */
223
-            $payment = null;
224
-            if ($transaction && $payment_method) {
225
-                /** @type EE_Transaction $transaction */
226
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
-                /** @type EE_Payment_Method $payment_method */
228
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
-                    try {
231
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
-                        $log->set_object($payment);
233
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
234
-                        EEM_Change_Log::instance()->log(
235
-                            EEM_Change_Log::type_gateway,
236
-                            array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
238
-                                'current_url' => EEH_URL::current_url(),
239
-                                'payment'     => $e->getPaymentProperties(),
240
-                                'IPN_data'    => $e->getIpnData(),
241
-                            ),
242
-                            $obj_for_log
243
-                        );
244
-                        return $e->getPayment();
245
-                    }
246
-                } else {
247
-                    // not a payment
248
-                    EE_Error::add_error(
249
-                        sprintf(
250
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
-                            '<br/>',
252
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
253
-                        ),
254
-                        __FILE__, __FUNCTION__, __LINE__
255
-                    );
256
-                }
257
-            } else {
258
-                //that's actually pretty ok. The IPN just wasn't able
259
-                //to identify which transaction or payment method this was for
260
-                // give all active payment methods a chance to claim it
261
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
-                foreach ($active_payment_methods as $active_payment_method) {
263
-                    try {
264
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
-                        $payment_method = $active_payment_method;
266
-                        EEM_Change_Log::instance()->log(
267
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
-                        );
269
-                        break;
270
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
271
-                        EEM_Change_Log::instance()->log(
272
-                            EEM_Change_Log::type_gateway,
273
-                            array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
275
-                                'current_url' => EEH_URL::current_url(),
276
-                                'payment'     => $e->getPaymentProperties(),
277
-                                'IPN_data'    => $e->getIpnData(),
278
-                            ),
279
-                            $obj_for_log
280
-                        );
281
-                        return $e->getPayment();
282
-                    } catch (EE_Error $e) {
283
-                        //that's fine- it apparently couldn't handle the IPN
284
-                    }
285
-                }
286
-            }
287
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
-            if ($payment instanceof EE_Payment) {
289
-                $payment->save();
290
-                //  update the TXN
291
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
-            } else {
293
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
-                if ($payment_method) {
295
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
-                } elseif ($transaction) {
297
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
-                }
299
-            }
300
-            return $payment;
301
-        } catch (EE_Error $e) {
302
-            do_action(
303
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
-                    print_r($transaction, true),
306
-                    print_r($_req_data, true),
307
-                    $e->getMessage()
308
-                )
309
-            );
310
-            throw $e;
311
-        }
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Removes any non-printable illegal characters from the input,
318
-     * which might cause a raucous when trying to insert into the database
319
-     *
320
-     * @param  array $request_data
321
-     * @return array
322
-     */
323
-    protected function _remove_unusable_characters_from_array(array $request_data)
324
-    {
325
-        $return_data = array();
326
-        foreach ($request_data as $key => $value) {
327
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
-        }
329
-        return $return_data;
330
-    }
331
-
332
-
333
-
334
-    /**
335
-     * Removes any non-printable illegal characters from the input,
336
-     * which might cause a raucous when trying to insert into the database
337
-     *
338
-     * @param string $request_data
339
-     * @return string
340
-     */
341
-    protected function _remove_unusable_characters($request_data)
342
-    {
343
-        return preg_replace('/[^[:print:]]/', '', $request_data);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * Should be called just before displaying the payment attempt results to the user,
350
-     * when the payment attempt has finished. Some payment methods may have special
351
-     * logic to perform here. For example, if process_payment() happens on a special request
352
-     * and then the user is redirected to a page that displays the payment's status, this
353
-     * should be called while loading the page that displays the payment's status. If the user is
354
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
-     * provider.
356
-     *
357
-     * @param EE_Transaction|int $transaction
358
-     * @param bool               $update_txn whether or not to call
359
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
-     * @throws \EE_Error
361
-     * @return EE_Payment
362
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
-     */
365
-    public function finalize_payment_for($transaction, $update_txn = true)
366
-    {
367
-        /** @var $transaction EE_Transaction */
368
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
-        $last_payment_method = $transaction->payment_method();
370
-        if ($last_payment_method instanceof EE_Payment_Method) {
371
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
-            return $payment;
374
-        } else {
375
-            return null;
376
-        }
377
-    }
378
-
379
-
380
-
381
-    /**
382
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
-     *
384
-     * @param EE_Payment_Method $payment_method
385
-     * @param EE_Payment        $payment_to_refund
386
-     * @param array             $refund_info
387
-     * @return EE_Payment
388
-     * @throws \EE_Error
389
-     */
390
-    public function process_refund(
391
-        EE_Payment_Method $payment_method,
392
-        EE_Payment $payment_to_refund,
393
-        $refund_info = array()
394
-    ) {
395
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
-        }
399
-        return $payment_to_refund;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * This should be called each time there may have been an update to a
406
-     * payment on a transaction (ie, we asked for a payment to process a
407
-     * payment for a transaction, or we told a payment method about an IPN, or
408
-     * we told a payment method to
409
-     * "finalize_payment_for" (a transaction), or we told a payment method to
410
-     * process a refund. This should handle firing the correct hooks to
411
-     * indicate
412
-     * what exactly happened and updating the transaction appropriately). This
413
-     * could be integrated directly into EE_Transaction upon save, but we want
414
-     * this logic to be separate from 'normal' plain-jane saving and updating
415
-     * of transactions and payments, and to be tied to payment processing.
416
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
-     * of previous code to decide whether or not to save (because the payment passed into
418
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
-     * in which case we only want that payment object for some temporary usage during this request,
420
-     * but we don't want it to be saved).
421
-     *
422
-     * @param EE_Transaction|int $transaction
423
-     * @param EE_Payment         $payment
424
-     * @param boolean            $update_txn
425
-     *                        whether or not to call
426
-     *                        EE_Transaction_Processor::
427
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
428
-     *                        (you can save 1 DB query if you know you're going
429
-     *                        to save it later instead)
430
-     * @param bool               $IPN
431
-     *                        if processing IPNs or other similar payment
432
-     *                        related activities that occur in alternate
433
-     *                        requests than the main one that is processing the
434
-     *                        TXN, then set this to true to check whether the
435
-     *                        TXN is locked before updating
436
-     * @throws \EE_Error
437
-     */
438
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
-    {
440
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
-        /** @type EE_Transaction $transaction */
442
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
-        // can we freely update the TXN at this moment?
444
-        if ($IPN && $transaction->is_locked()) {
445
-            // don't update the transaction at this exact moment
446
-            // because the TXN is active in another request
447
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
-                time(),
449
-                $transaction->ID(),
450
-                $payment->ID()
451
-            );
452
-        } else {
453
-            // verify payment and that it has been saved
454
-            if ($payment instanceof EE_Payment && $payment->ID()) {
455
-                if (
456
-                    $payment->payment_method() instanceof EE_Payment_Method
457
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
-                ) {
459
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
-                    // update TXN registrations with payment info
461
-                    $this->process_registration_payments($transaction, $payment);
462
-                }
463
-                $do_action = $payment->just_approved()
464
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
-                    : $do_action;
466
-            } else {
467
-                // send out notifications
468
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
-            }
471
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
472
-                /** @type EE_Transaction_Payments $transaction_payments */
473
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
-                // set new value for total paid
475
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
476
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
-                if ($update_txn) {
478
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
479
-                }
480
-            }
481
-            // granular hook for others to use.
482
-            do_action($do_action, $transaction, $payment);
483
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
-            //global hook for others to use.
485
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
-        }
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * update registrations REG_paid field after successful payment and link registrations with payment
493
-     *
494
-     * @param EE_Transaction    $transaction
495
-     * @param EE_Payment        $payment
496
-     * @param EE_Registration[] $registrations
497
-     * @throws \EE_Error
498
-     */
499
-    public function process_registration_payments(
500
-        EE_Transaction $transaction,
501
-        EE_Payment $payment,
502
-        $registrations = array()
503
-    ) {
504
-        // only process if payment was successful
505
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
506
-            return;
507
-        }
508
-        //EEM_Registration::instance()->show_next_x_db_queries();
509
-        if (empty($registrations)) {
510
-            // find registrations with monies owing that can receive a payment
511
-            $registrations = $transaction->registrations(
512
-                array(
513
-                    array(
514
-                        // only these reg statuses can receive payments
515
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
-                        'REG_final_price'  => array('!=', 0),
517
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
518
-                    ),
519
-                )
520
-            );
521
-        }
522
-        // still nothing ??!??
523
-        if (empty($registrations)) {
524
-            return;
525
-        }
526
-        // todo: break out the following logic into a separate strategy class
527
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
528
-        // todo: which would apply payments using the capitalist "first come first paid" approach
529
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
531
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
-        $refund = $payment->is_a_refund();
533
-        // how much is available to apply to registrations?
534
-        $available_payment_amount = abs($payment->amount());
535
-        foreach ($registrations as $registration) {
536
-            if ($registration instanceof EE_Registration) {
537
-                // nothing left?
538
-                if ($available_payment_amount <= 0) {
539
-                    break;
540
-                }
541
-                if ($refund) {
542
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
-                } else {
544
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
-                }
546
-            }
547
-        }
548
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
-            EE_Error::add_attention(
550
-                sprintf(
551
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
-                        'event_espresso'),
553
-                    EEH_Template::format_currency($available_payment_amount),
554
-                    implode(', ', array_keys($registrations)),
555
-                    '<br/>',
556
-                    EEH_Template::format_currency($payment->amount())
557
-                ),
558
-                __FILE__, __FUNCTION__, __LINE__
559
-            );
560
-        }
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * update registration REG_paid field after successful payment and link registration with payment
567
-     *
568
-     * @param EE_Registration $registration
569
-     * @param EE_Payment      $payment
570
-     * @param float           $available_payment_amount
571
-     * @return float
572
-     * @throws \EE_Error
573
-     */
574
-    public function process_registration_payment(
575
-        EE_Registration $registration,
576
-        EE_Payment $payment,
577
-        $available_payment_amount = 0.00
578
-    ) {
579
-        $owing = $registration->final_price() - $registration->paid();
580
-        if ($owing > 0) {
581
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
582
-            $payment_amount = min($available_payment_amount, $owing);
583
-            // update $available_payment_amount
584
-            $available_payment_amount -= $payment_amount;
585
-            //calculate and set new REG_paid
586
-            $registration->set_paid($registration->paid() + $payment_amount);
587
-            // now save it
588
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
589
-        }
590
-        return $available_payment_amount;
591
-    }
592
-
593
-
594
-
595
-    /**
596
-     * update registration REG_paid field after successful payment and link registration with payment
597
-     *
598
-     * @param EE_Registration $registration
599
-     * @param EE_Payment      $payment
600
-     * @param float           $payment_amount
601
-     * @return void
602
-     * @throws \EE_Error
603
-     */
604
-    protected function _apply_registration_payment(
605
-        EE_Registration $registration,
606
-        EE_Payment $payment,
607
-        $payment_amount = 0.00
608
-    ) {
609
-        // find any existing reg payment records for this registration and payment
610
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
-        );
613
-        // if existing registration payment exists
614
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
-            // then update that record
616
-            $existing_reg_payment->set_amount($payment_amount);
617
-            $existing_reg_payment->save();
618
-        } else {
619
-            // or add new relation between registration and payment and set amount
620
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
-            // make it stick
622
-            $registration->save();
623
-        }
624
-    }
625
-
626
-
627
-
628
-    /**
629
-     * update registration REG_paid field after refund and link registration with payment
630
-     *
631
-     * @param EE_Registration $registration
632
-     * @param EE_Payment      $payment
633
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
-     * @return float
635
-     * @throws \EE_Error
636
-     */
637
-    public function process_registration_refund(
638
-        EE_Registration $registration,
639
-        EE_Payment $payment,
640
-        $available_refund_amount = 0.00
641
-    ) {
642
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
-        if ($registration->paid() > 0) {
644
-            // ensure $available_refund_amount is NOT negative
645
-            $available_refund_amount = (float)abs($available_refund_amount);
646
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
647
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
648
-            // update $available_payment_amount
649
-            $available_refund_amount -= $refund_amount;
650
-            //calculate and set new REG_paid
651
-            $registration->set_paid($registration->paid() - $refund_amount);
652
-            // convert payment amount back to a negative value for storage in the db
653
-            $refund_amount = (float)abs($refund_amount) * -1;
654
-            // now save it
655
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
656
-        }
657
-        return $available_refund_amount;
658
-    }
659
-
660
-
661
-
662
-    /**
663
-     * Process payments and transaction after payment process completed.
664
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
-     * if this request happens to be processing an IPN,
666
-     * then we will also set the Payment Options Reg Step to completed,
667
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
-     *
669
-     * @param EE_Transaction $transaction
670
-     * @param EE_Payment     $payment
671
-     * @param bool           $IPN
672
-     * @throws \EE_Error
673
-     */
674
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
-    {
676
-        /** @type EE_Transaction_Processor $transaction_processor */
677
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
-        // is the Payment Options Reg Step completed ?
679
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
-        // if the Payment Options Reg Step is completed...
681
-        $revisit = $payment_options_step_completed === true ? true : false;
682
-        // then this is kinda sorta a revisit with regards to payments at least
683
-        $transaction_processor->set_revisit($revisit);
684
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
-        if (
686
-            $IPN
687
-            && $payment_options_step_completed !== true
688
-            && ($payment->is_approved() || $payment->is_pending())
689
-        ) {
690
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
691
-                'payment_options'
692
-            );
693
-        }
694
-        // maybe update status, but don't save transaction just yet
695
-        $transaction->update_status_based_on_total_paid(false);
696
-        // check if 'finalize_registration' step has been completed...
697
-        $finalized = $transaction->reg_step_completed('finalize_registration');
698
-        //  if this is an IPN and the final step has not been initiated
699
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
700
-            // and if it hasn't already been set as being started...
701
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
-        }
703
-        $transaction->save();
704
-        // because the above will return false if the final step was not fully completed, we need to check again...
705
-        if ($IPN && $finalized !== false) {
706
-            // and if we are all good to go, then send out notifications
707
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
-            //ok, now process the transaction according to the payment
709
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
-        }
711
-        // DEBUG LOG
712
-        $payment_method = $payment->payment_method();
713
-        if ($payment_method instanceof EE_Payment_Method) {
714
-            $payment_method_type_obj = $payment_method->type_obj();
715
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
-                $gateway = $payment_method_type_obj->get_gateway();
717
-                if ($gateway instanceof EE_Gateway) {
718
-                    $gateway->log(
719
-                        array(
720
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
-                            'transaction'           => $transaction->model_field_array(),
722
-                            'finalized'             => $finalized,
723
-                            'IPN'                   => $IPN,
724
-                            'deliver_notifications' => has_filter(
725
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
-                            ),
727
-                        ),
728
-                        $payment
729
-                    );
730
-                }
731
-            }
732
-        }
733
-    }
734
-
735
-
736
-
737
-    /**
738
-     * Force posts to PayPal to use TLS v1.2. See:
739
-     * https://core.trac.wordpress.org/ticket/36320
740
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
741
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
-     * This will affect paypal standard, pro, express, and payflow.
743
-     */
744
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
-    {
746
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
-            //instead of the constant because it might not be defined
749
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
-        }
751
-    }
19
+	/**
20
+	 * @var EE_Payment_Processor $_instance
21
+	 * @access    private
22
+	 */
23
+	private static $_instance;
24
+
25
+
26
+
27
+	/**
28
+	 * @singleton method used to instantiate class object
29
+	 * @access    public
30
+	 * @return EE_Payment_Processor instance
31
+	 */
32
+	public static function instance()
33
+	{
34
+		// check if class object is instantiated
35
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
+			self::$_instance = new self();
37
+		}
38
+		return self::$_instance;
39
+	}
40
+
41
+
42
+
43
+	/**
44
+	 *private constructor to prevent direct creation
45
+	 *
46
+	 * @Constructor
47
+	 * @access private
48
+	 */
49
+	private function __construct()
50
+	{
51
+		do_action('AHEE__EE_Payment_Processor__construct');
52
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
+	 * appropriately. Saves the payment that is generated
60
+	 *
61
+	 * @param EE_Payment_Method    $payment_method
62
+	 * @param EE_Transaction       $transaction
63
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
+	 *                                           Leave null if payment is for the full amount owing
65
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
+	 *                                           Receive_form_submission() should have
67
+	 *                                           already been called on the billing form
68
+	 *                                           (ie, its inputs should have their normalized values set).
69
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
70
+	 *                                           where to go AFTER the offsite gateway
71
+	 * @param string               $method       like 'CART', indicates who the client who called this was
72
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
+	 * @param boolean              $update_txn   whether or not to call
74
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
+	 * @return \EE_Payment
77
+	 * @throws \EE_Error
78
+	 */
79
+	public function process_payment(
80
+		EE_Payment_Method $payment_method,
81
+		EE_Transaction $transaction,
82
+		$amount = null,
83
+		$billing_form = null,
84
+		$return_url = null,
85
+		$method = 'CART',
86
+		$by_admin = false,
87
+		$update_txn = true,
88
+		$cancel_url = ''
89
+	) {
90
+		if ((float)$amount < 0) {
91
+			throw new EE_Error(
92
+				sprintf(
93
+					__(
94
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
+						'event_espresso'
96
+					),
97
+					$amount,
98
+					$transaction->ID()
99
+				)
100
+			);
101
+		}
102
+		// verify payment method
103
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
+		// verify transaction
105
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
106
+		$transaction->set_payment_method_ID($payment_method->ID());
107
+		// verify payment method type
108
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
+			$payment = $payment_method->type_obj()->process_payment(
110
+				$transaction,
111
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
112
+				$billing_form,
113
+				$return_url,
114
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
+				$method,
116
+				$by_admin
117
+			);
118
+			// check if payment method uses an off-site gateway
119
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
+				// don't process payments for off-site gateways yet because no payment has occurred yet
121
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
+			}
123
+			return $payment;
124
+		} else {
125
+			EE_Error::add_error(
126
+				sprintf(
127
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
+					'<br/>',
129
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
130
+				), __FILE__, __FUNCTION__, __LINE__
131
+			);
132
+			return null;
133
+		}
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * @param EE_Transaction|int $transaction
140
+	 * @param EE_Payment_Method  $payment_method
141
+	 * @throws EE_Error
142
+	 * @return string
143
+	 */
144
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
+	{
146
+		/** @type \EE_Transaction $transaction */
147
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
+		$primary_reg = $transaction->primary_registration();
149
+		if ( ! $primary_reg instanceof EE_Registration) {
150
+			throw new EE_Error(
151
+				sprintf(
152
+					__(
153
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
+						"event_espresso"
155
+					),
156
+					$transaction->ID()
157
+				)
158
+			);
159
+		}
160
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
+		$url = add_query_arg(
162
+			array(
163
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
+				'ee_payment_method' => $payment_method->slug(),
165
+			),
166
+			EE_Registry::instance()->CFG->core->txn_page_url()
167
+		);
168
+		return $url;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
+	 * we can easily find what registration the IPN is for and what payment method.
176
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
177
+	 * If a payment is found for the IPN info, it is saved.
178
+	 *
179
+	 * @param array              $_req_data            eg $_REQUEST
180
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
+	 * @param boolean            $update_txn           whether or not to call
183
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
+	 *                                                 or is processed manually ( false like Mijireh )
186
+	 * @throws EE_Error
187
+	 * @throws Exception
188
+	 * @return EE_Payment
189
+	 */
190
+	public function process_ipn(
191
+		$_req_data,
192
+		$transaction = null,
193
+		$payment_method = null,
194
+		$update_txn = true,
195
+		$separate_IPN_request = true
196
+	) {
197
+		EE_Registry::instance()->load_model('Change_Log');
198
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
+		EE_Processor_Base::set_IPN($separate_IPN_request);
200
+		$obj_for_log = null;
201
+		if ($transaction instanceof EE_Transaction) {
202
+			$obj_for_log = $transaction;
203
+			if ($payment_method instanceof EE_Payment_Method) {
204
+				$obj_for_log = EEM_Payment::instance()->get_one(
205
+					array(
206
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
+						'order_by' => array('PAY_timestamp' => 'desc'),
208
+					)
209
+				);
210
+			}
211
+		} else if ($payment_method instanceof EE_Payment) {
212
+			$obj_for_log = $payment_method;
213
+		}
214
+		$log = EEM_Change_Log::instance()->log(
215
+			EEM_Change_Log::type_gateway,
216
+			array('IPN data received' => $_req_data),
217
+			$obj_for_log
218
+		);
219
+		try {
220
+			/**
221
+			 * @var EE_Payment $payment
222
+			 */
223
+			$payment = null;
224
+			if ($transaction && $payment_method) {
225
+				/** @type EE_Transaction $transaction */
226
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
+				/** @type EE_Payment_Method $payment_method */
228
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
+					try {
231
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
+						$log->set_object($payment);
233
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
234
+						EEM_Change_Log::instance()->log(
235
+							EEM_Change_Log::type_gateway,
236
+							array(
237
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
238
+								'current_url' => EEH_URL::current_url(),
239
+								'payment'     => $e->getPaymentProperties(),
240
+								'IPN_data'    => $e->getIpnData(),
241
+							),
242
+							$obj_for_log
243
+						);
244
+						return $e->getPayment();
245
+					}
246
+				} else {
247
+					// not a payment
248
+					EE_Error::add_error(
249
+						sprintf(
250
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
+							'<br/>',
252
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
253
+						),
254
+						__FILE__, __FUNCTION__, __LINE__
255
+					);
256
+				}
257
+			} else {
258
+				//that's actually pretty ok. The IPN just wasn't able
259
+				//to identify which transaction or payment method this was for
260
+				// give all active payment methods a chance to claim it
261
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
+				foreach ($active_payment_methods as $active_payment_method) {
263
+					try {
264
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
+						$payment_method = $active_payment_method;
266
+						EEM_Change_Log::instance()->log(
267
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
+						);
269
+						break;
270
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
271
+						EEM_Change_Log::instance()->log(
272
+							EEM_Change_Log::type_gateway,
273
+							array(
274
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
275
+								'current_url' => EEH_URL::current_url(),
276
+								'payment'     => $e->getPaymentProperties(),
277
+								'IPN_data'    => $e->getIpnData(),
278
+							),
279
+							$obj_for_log
280
+						);
281
+						return $e->getPayment();
282
+					} catch (EE_Error $e) {
283
+						//that's fine- it apparently couldn't handle the IPN
284
+					}
285
+				}
286
+			}
287
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
+			if ($payment instanceof EE_Payment) {
289
+				$payment->save();
290
+				//  update the TXN
291
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
+			} else {
293
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
+				if ($payment_method) {
295
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
+				} elseif ($transaction) {
297
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
+				}
299
+			}
300
+			return $payment;
301
+		} catch (EE_Error $e) {
302
+			do_action(
303
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
+					print_r($transaction, true),
306
+					print_r($_req_data, true),
307
+					$e->getMessage()
308
+				)
309
+			);
310
+			throw $e;
311
+		}
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Removes any non-printable illegal characters from the input,
318
+	 * which might cause a raucous when trying to insert into the database
319
+	 *
320
+	 * @param  array $request_data
321
+	 * @return array
322
+	 */
323
+	protected function _remove_unusable_characters_from_array(array $request_data)
324
+	{
325
+		$return_data = array();
326
+		foreach ($request_data as $key => $value) {
327
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
+		}
329
+		return $return_data;
330
+	}
331
+
332
+
333
+
334
+	/**
335
+	 * Removes any non-printable illegal characters from the input,
336
+	 * which might cause a raucous when trying to insert into the database
337
+	 *
338
+	 * @param string $request_data
339
+	 * @return string
340
+	 */
341
+	protected function _remove_unusable_characters($request_data)
342
+	{
343
+		return preg_replace('/[^[:print:]]/', '', $request_data);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * Should be called just before displaying the payment attempt results to the user,
350
+	 * when the payment attempt has finished. Some payment methods may have special
351
+	 * logic to perform here. For example, if process_payment() happens on a special request
352
+	 * and then the user is redirected to a page that displays the payment's status, this
353
+	 * should be called while loading the page that displays the payment's status. If the user is
354
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
+	 * provider.
356
+	 *
357
+	 * @param EE_Transaction|int $transaction
358
+	 * @param bool               $update_txn whether or not to call
359
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
+	 * @throws \EE_Error
361
+	 * @return EE_Payment
362
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
+	 */
365
+	public function finalize_payment_for($transaction, $update_txn = true)
366
+	{
367
+		/** @var $transaction EE_Transaction */
368
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
+		$last_payment_method = $transaction->payment_method();
370
+		if ($last_payment_method instanceof EE_Payment_Method) {
371
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
+			return $payment;
374
+		} else {
375
+			return null;
376
+		}
377
+	}
378
+
379
+
380
+
381
+	/**
382
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
+	 *
384
+	 * @param EE_Payment_Method $payment_method
385
+	 * @param EE_Payment        $payment_to_refund
386
+	 * @param array             $refund_info
387
+	 * @return EE_Payment
388
+	 * @throws \EE_Error
389
+	 */
390
+	public function process_refund(
391
+		EE_Payment_Method $payment_method,
392
+		EE_Payment $payment_to_refund,
393
+		$refund_info = array()
394
+	) {
395
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
+		}
399
+		return $payment_to_refund;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * This should be called each time there may have been an update to a
406
+	 * payment on a transaction (ie, we asked for a payment to process a
407
+	 * payment for a transaction, or we told a payment method about an IPN, or
408
+	 * we told a payment method to
409
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
410
+	 * process a refund. This should handle firing the correct hooks to
411
+	 * indicate
412
+	 * what exactly happened and updating the transaction appropriately). This
413
+	 * could be integrated directly into EE_Transaction upon save, but we want
414
+	 * this logic to be separate from 'normal' plain-jane saving and updating
415
+	 * of transactions and payments, and to be tied to payment processing.
416
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
+	 * of previous code to decide whether or not to save (because the payment passed into
418
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
+	 * in which case we only want that payment object for some temporary usage during this request,
420
+	 * but we don't want it to be saved).
421
+	 *
422
+	 * @param EE_Transaction|int $transaction
423
+	 * @param EE_Payment         $payment
424
+	 * @param boolean            $update_txn
425
+	 *                        whether or not to call
426
+	 *                        EE_Transaction_Processor::
427
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
428
+	 *                        (you can save 1 DB query if you know you're going
429
+	 *                        to save it later instead)
430
+	 * @param bool               $IPN
431
+	 *                        if processing IPNs or other similar payment
432
+	 *                        related activities that occur in alternate
433
+	 *                        requests than the main one that is processing the
434
+	 *                        TXN, then set this to true to check whether the
435
+	 *                        TXN is locked before updating
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
+	{
440
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
+		/** @type EE_Transaction $transaction */
442
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
+		// can we freely update the TXN at this moment?
444
+		if ($IPN && $transaction->is_locked()) {
445
+			// don't update the transaction at this exact moment
446
+			// because the TXN is active in another request
447
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
+				time(),
449
+				$transaction->ID(),
450
+				$payment->ID()
451
+			);
452
+		} else {
453
+			// verify payment and that it has been saved
454
+			if ($payment instanceof EE_Payment && $payment->ID()) {
455
+				if (
456
+					$payment->payment_method() instanceof EE_Payment_Method
457
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
+				) {
459
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
+					// update TXN registrations with payment info
461
+					$this->process_registration_payments($transaction, $payment);
462
+				}
463
+				$do_action = $payment->just_approved()
464
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
+					: $do_action;
466
+			} else {
467
+				// send out notifications
468
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
+			}
471
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
472
+				/** @type EE_Transaction_Payments $transaction_payments */
473
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
+				// set new value for total paid
475
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
476
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
+				if ($update_txn) {
478
+					$this->_post_payment_processing($transaction, $payment, $IPN);
479
+				}
480
+			}
481
+			// granular hook for others to use.
482
+			do_action($do_action, $transaction, $payment);
483
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
+			//global hook for others to use.
485
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
+		}
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * update registrations REG_paid field after successful payment and link registrations with payment
493
+	 *
494
+	 * @param EE_Transaction    $transaction
495
+	 * @param EE_Payment        $payment
496
+	 * @param EE_Registration[] $registrations
497
+	 * @throws \EE_Error
498
+	 */
499
+	public function process_registration_payments(
500
+		EE_Transaction $transaction,
501
+		EE_Payment $payment,
502
+		$registrations = array()
503
+	) {
504
+		// only process if payment was successful
505
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
506
+			return;
507
+		}
508
+		//EEM_Registration::instance()->show_next_x_db_queries();
509
+		if (empty($registrations)) {
510
+			// find registrations with monies owing that can receive a payment
511
+			$registrations = $transaction->registrations(
512
+				array(
513
+					array(
514
+						// only these reg statuses can receive payments
515
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
+						'REG_final_price'  => array('!=', 0),
517
+						'REG_final_price*' => array('!=', 'REG_paid', true),
518
+					),
519
+				)
520
+			);
521
+		}
522
+		// still nothing ??!??
523
+		if (empty($registrations)) {
524
+			return;
525
+		}
526
+		// todo: break out the following logic into a separate strategy class
527
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
528
+		// todo: which would apply payments using the capitalist "first come first paid" approach
529
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
531
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
+		$refund = $payment->is_a_refund();
533
+		// how much is available to apply to registrations?
534
+		$available_payment_amount = abs($payment->amount());
535
+		foreach ($registrations as $registration) {
536
+			if ($registration instanceof EE_Registration) {
537
+				// nothing left?
538
+				if ($available_payment_amount <= 0) {
539
+					break;
540
+				}
541
+				if ($refund) {
542
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
+				} else {
544
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
+				}
546
+			}
547
+		}
548
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
+			EE_Error::add_attention(
550
+				sprintf(
551
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
+						'event_espresso'),
553
+					EEH_Template::format_currency($available_payment_amount),
554
+					implode(', ', array_keys($registrations)),
555
+					'<br/>',
556
+					EEH_Template::format_currency($payment->amount())
557
+				),
558
+				__FILE__, __FUNCTION__, __LINE__
559
+			);
560
+		}
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * update registration REG_paid field after successful payment and link registration with payment
567
+	 *
568
+	 * @param EE_Registration $registration
569
+	 * @param EE_Payment      $payment
570
+	 * @param float           $available_payment_amount
571
+	 * @return float
572
+	 * @throws \EE_Error
573
+	 */
574
+	public function process_registration_payment(
575
+		EE_Registration $registration,
576
+		EE_Payment $payment,
577
+		$available_payment_amount = 0.00
578
+	) {
579
+		$owing = $registration->final_price() - $registration->paid();
580
+		if ($owing > 0) {
581
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
582
+			$payment_amount = min($available_payment_amount, $owing);
583
+			// update $available_payment_amount
584
+			$available_payment_amount -= $payment_amount;
585
+			//calculate and set new REG_paid
586
+			$registration->set_paid($registration->paid() + $payment_amount);
587
+			// now save it
588
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
589
+		}
590
+		return $available_payment_amount;
591
+	}
592
+
593
+
594
+
595
+	/**
596
+	 * update registration REG_paid field after successful payment and link registration with payment
597
+	 *
598
+	 * @param EE_Registration $registration
599
+	 * @param EE_Payment      $payment
600
+	 * @param float           $payment_amount
601
+	 * @return void
602
+	 * @throws \EE_Error
603
+	 */
604
+	protected function _apply_registration_payment(
605
+		EE_Registration $registration,
606
+		EE_Payment $payment,
607
+		$payment_amount = 0.00
608
+	) {
609
+		// find any existing reg payment records for this registration and payment
610
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
+		);
613
+		// if existing registration payment exists
614
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
+			// then update that record
616
+			$existing_reg_payment->set_amount($payment_amount);
617
+			$existing_reg_payment->save();
618
+		} else {
619
+			// or add new relation between registration and payment and set amount
620
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
+			// make it stick
622
+			$registration->save();
623
+		}
624
+	}
625
+
626
+
627
+
628
+	/**
629
+	 * update registration REG_paid field after refund and link registration with payment
630
+	 *
631
+	 * @param EE_Registration $registration
632
+	 * @param EE_Payment      $payment
633
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
+	 * @return float
635
+	 * @throws \EE_Error
636
+	 */
637
+	public function process_registration_refund(
638
+		EE_Registration $registration,
639
+		EE_Payment $payment,
640
+		$available_refund_amount = 0.00
641
+	) {
642
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
+		if ($registration->paid() > 0) {
644
+			// ensure $available_refund_amount is NOT negative
645
+			$available_refund_amount = (float)abs($available_refund_amount);
646
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
647
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
648
+			// update $available_payment_amount
649
+			$available_refund_amount -= $refund_amount;
650
+			//calculate and set new REG_paid
651
+			$registration->set_paid($registration->paid() - $refund_amount);
652
+			// convert payment amount back to a negative value for storage in the db
653
+			$refund_amount = (float)abs($refund_amount) * -1;
654
+			// now save it
655
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
656
+		}
657
+		return $available_refund_amount;
658
+	}
659
+
660
+
661
+
662
+	/**
663
+	 * Process payments and transaction after payment process completed.
664
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
+	 * if this request happens to be processing an IPN,
666
+	 * then we will also set the Payment Options Reg Step to completed,
667
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
+	 *
669
+	 * @param EE_Transaction $transaction
670
+	 * @param EE_Payment     $payment
671
+	 * @param bool           $IPN
672
+	 * @throws \EE_Error
673
+	 */
674
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
+	{
676
+		/** @type EE_Transaction_Processor $transaction_processor */
677
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
+		// is the Payment Options Reg Step completed ?
679
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
+		// if the Payment Options Reg Step is completed...
681
+		$revisit = $payment_options_step_completed === true ? true : false;
682
+		// then this is kinda sorta a revisit with regards to payments at least
683
+		$transaction_processor->set_revisit($revisit);
684
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
+		if (
686
+			$IPN
687
+			&& $payment_options_step_completed !== true
688
+			&& ($payment->is_approved() || $payment->is_pending())
689
+		) {
690
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
691
+				'payment_options'
692
+			);
693
+		}
694
+		// maybe update status, but don't save transaction just yet
695
+		$transaction->update_status_based_on_total_paid(false);
696
+		// check if 'finalize_registration' step has been completed...
697
+		$finalized = $transaction->reg_step_completed('finalize_registration');
698
+		//  if this is an IPN and the final step has not been initiated
699
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
700
+			// and if it hasn't already been set as being started...
701
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
+		}
703
+		$transaction->save();
704
+		// because the above will return false if the final step was not fully completed, we need to check again...
705
+		if ($IPN && $finalized !== false) {
706
+			// and if we are all good to go, then send out notifications
707
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
+			//ok, now process the transaction according to the payment
709
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
+		}
711
+		// DEBUG LOG
712
+		$payment_method = $payment->payment_method();
713
+		if ($payment_method instanceof EE_Payment_Method) {
714
+			$payment_method_type_obj = $payment_method->type_obj();
715
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
+				$gateway = $payment_method_type_obj->get_gateway();
717
+				if ($gateway instanceof EE_Gateway) {
718
+					$gateway->log(
719
+						array(
720
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
+							'transaction'           => $transaction->model_field_array(),
722
+							'finalized'             => $finalized,
723
+							'IPN'                   => $IPN,
724
+							'deliver_notifications' => has_filter(
725
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
+							),
727
+						),
728
+						$payment
729
+					);
730
+				}
731
+			}
732
+		}
733
+	}
734
+
735
+
736
+
737
+	/**
738
+	 * Force posts to PayPal to use TLS v1.2. See:
739
+	 * https://core.trac.wordpress.org/ticket/36320
740
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
741
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
+	 * This will affect paypal standard, pro, express, and payflow.
743
+	 */
744
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
+	{
746
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
+			//instead of the constant because it might not be defined
749
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
+		}
751
+	}
752 752
 }
Please login to merge, or discard this patch.
core/libraries/payment_methods/EEI_Payment_Method_Interfaces.php 1 patch
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
  *
6 6
  * allows gateways to be used by different systems other than Event Espresso
7 7
  */
8
-interface EEI_Payment extends EEI_Base{
8
+interface EEI_Payment extends EEI_Base {
9 9
 
10 10
 	/**
11 11
 	 * @return string indicating which the payment is approved, pending, cancelled or failed
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 /**
154 154
  * Interface EEI_Payment_Method
155 155
  */
156
-interface EEI_Payment_Method{
156
+interface EEI_Payment_Method {
157 157
 
158 158
 }
159 159
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	 * @param string $model_name
173 173
 	 * @return EE_Log
174 174
 	 */
175
-	public function gateway_log($message,$id,$model_name);
175
+	public function gateway_log($message, $id, $model_name);
176 176
 }
177 177
 
178 178
 
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 2 patches
Indentation   +98 added lines, -100 removed lines patch added patch discarded remove patch
@@ -44,77 +44,76 @@  discard block
 block discarded – undo
44 44
 	 */
45 45
 	protected $_image_url;
46 46
 
47
-    /**
48
-     * gateway URL variable
49
-     *
50
-     * @var string
51
-     */
52
-    protected $_base_gateway_url = '';
53
-
54
-
55
-
56
-    /**
57
-     * EEG_Paypal_Express constructor.
58
-     */
59
-    public function __construct()
60
-    {
61
-        $this->_currencies_supported = array(
62
-            'USD',
63
-            'AUD',
64
-            'BRL',
65
-            'CAD',
66
-            'CZK',
67
-            'DKK',
68
-            'EUR',
69
-            'HKD',
70
-            'HUF',
71
-            'ILS',
72
-            'JPY',
73
-            'MYR',
74
-            'MXN',
75
-            'NOK',
76
-            'NZD',
77
-            'PHP',
78
-            'PLN',
79
-            'GBP',
80
-            'RUB',
81
-            'SGD',
82
-            'SEK',
83
-            'CHF',
84
-            'TWD',
85
-            'THB',
86
-            'TRY'
87
-        );
88
-        parent::__construct();
89
-    }
90
-
91
-
92
-
93
-    /**
94
-	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
47
+	/**
48
+	 * gateway URL variable
49
+	 *
50
+	 * @var string
51
+	 */
52
+	protected $_base_gateway_url = '';
53
+
54
+
55
+
56
+	/**
57
+	 * EEG_Paypal_Express constructor.
58
+	 */
59
+	public function __construct()
60
+	{
61
+		$this->_currencies_supported = array(
62
+			'USD',
63
+			'AUD',
64
+			'BRL',
65
+			'CAD',
66
+			'CZK',
67
+			'DKK',
68
+			'EUR',
69
+			'HKD',
70
+			'HUF',
71
+			'ILS',
72
+			'JPY',
73
+			'MYR',
74
+			'MXN',
75
+			'NOK',
76
+			'NZD',
77
+			'PHP',
78
+			'PLN',
79
+			'GBP',
80
+			'RUB',
81
+			'SGD',
82
+			'SEK',
83
+			'CHF',
84
+			'TWD',
85
+			'THB',
86
+			'TRY'
87
+		);
88
+		parent::__construct();
89
+	}
90
+
95 91
 
92
+
93
+	/**
94
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
96 95
 	 *
97 96
 *@param array $settings_array
98 97
 	 */
99 98
 	public function set_settings( $settings_array ) {
100 99
 		parent::set_settings($settings_array);
101 100
 		// Redirect URL.
102
-        $this->_base_gateway_url = $this->_debug_mode
103
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
104
-            : 'https://api-3t.paypal.com/nvp';
101
+		$this->_base_gateway_url = $this->_debug_mode
102
+			? 'https://api-3t.sandbox.paypal.com/nvp'
103
+			: 'https://api-3t.paypal.com/nvp';
105 104
 	}
106 105
 
107 106
 
108 107
 
109
-    /**
110
-     * @param EEI_Payment $payment
111
-     * @param array       $billing_info
112
-     * @param string      $return_url
113
-     * @param string      $notify_url
114
-     * @param string      $cancel_url
115
-     * @return \EE_Payment|\EEI_Payment
116
-     * @throws \EE_Error
117
-     */
108
+	/**
109
+	 * @param EEI_Payment $payment
110
+	 * @param array       $billing_info
111
+	 * @param string      $return_url
112
+	 * @param string      $notify_url
113
+	 * @param string      $cancel_url
114
+	 * @return \EE_Payment|\EEI_Payment
115
+	 * @throws \EE_Error
116
+	 */
118 117
 	public function set_redirection_info( $payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL ) {
119 118
 		if ( ! $payment instanceof EEI_Payment ) {
120 119
 			$payment->set_gateway_response( __( 'Error. No associated payment was found.', 'event_espresso' ) );
@@ -202,9 +201,9 @@  discard block
 block discarded – undo
202 201
 				$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
203 202
 				// Item quantity.
204 203
 				$token_request_dtls['L_PAYMENTREQUEST_0_QTY'.$item_num] = 1;
205
-                // Digital item is sold.
206
-                $token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
207
-                $item_num++;
204
+				// Digital item is sold.
205
+				$token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
206
+				$item_num++;
208 207
 			}
209 208
 		} else {
210 209
 			// Just one Item.
@@ -272,7 +271,6 @@  discard block
 block discarded – undo
272 271
 
273 272
 
274 273
 	/**
275
-
276 274
 	 *  @param array $update_info {
277 275
 	 *	  @type string $gateway_txn_id
278 276
 	 *	  @type string status an EEMI_Payment status
@@ -292,8 +290,8 @@  discard block
 block discarded – undo
292 290
 				return $payment;
293 291
 			}
294 292
 			$primary_registrant = $transaction->primary_registration();
295
-            $payment_details = $payment->details();
296
-            // Check if we still have the token.
293
+			$payment_details = $payment->details();
294
+			// Check if we still have the token.
297 295
 			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN']) ) {
298 296
 				$payment->set_status( $this->_pay_model->failed_status() );
299 297
 				return $payment;
@@ -402,36 +400,36 @@  discard block
 block discarded – undo
402 400
 	 */
403 401
 	public function _ppExpress_check_response( $request_response ) {
404 402
 		if (empty($request_response['body']) || is_wp_error( $request_response ) ) {
405
-            // If we got here then there was an error in this request.
406
-            return array('status' => false, 'args' => $request_response);
407
-        }
408
-        $response_args = array();
409
-        parse_str( urldecode($request_response['body']), $response_args );
410
-        if ( ! isset($response_args['ACK'])) {
411
-            return array('status' => false, 'args' => $request_response);
412
-        }
413
-        if (
414
-            $response_args['ACK'] === 'Success'
415
-            && (
416
-                isset($response_args['PAYERID'])
417
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
418
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
419
-                || isset($response_args['TOKEN'])
420
-            )
421
-        ) {
422
-            // Response status OK, return response parameters for further processing.
423
-            return array('status' => true, 'args' => $response_args);
424
-        } else {
425
-            $errors = $this->_get_errors($response_args);
426
-            return array('status' => false, 'args' => $errors);
427
-        }
403
+			// If we got here then there was an error in this request.
404
+			return array('status' => false, 'args' => $request_response);
405
+		}
406
+		$response_args = array();
407
+		parse_str( urldecode($request_response['body']), $response_args );
408
+		if ( ! isset($response_args['ACK'])) {
409
+			return array('status' => false, 'args' => $request_response);
410
+		}
411
+		if (
412
+			$response_args['ACK'] === 'Success'
413
+			&& (
414
+				isset($response_args['PAYERID'])
415
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
416
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
417
+				|| isset($response_args['TOKEN'])
418
+			)
419
+		) {
420
+			// Response status OK, return response parameters for further processing.
421
+			return array('status' => true, 'args' => $response_args);
422
+		} else {
423
+			$errors = $this->_get_errors($response_args);
424
+			return array('status' => false, 'args' => $errors);
425
+		}
428 426
 	}
429 427
 
430 428
 
431 429
 	/**
432
-     *  Log a "Cleared" request.
433
-     *
434
-     * @param array $request
430
+	 *  Log a "Cleared" request.
431
+	 *
432
+	 * @param array $request
435 433
 	 * @param EEI_Payment  $payment
436 434
 	 * @param string  		$info
437 435
 	 * @return void
@@ -454,17 +452,17 @@  discard block
 block discarded – undo
454 452
 		$n = 0;
455 453
 		while ( isset($data_array["L_ERRORCODE{$n}"]) ) {
456 454
 			$l_error_code = isset($data_array["L_ERRORCODE{$n}"])
457
-                ? $data_array["L_ERRORCODE{$n}"]
458
-                : '';
455
+				? $data_array["L_ERRORCODE{$n}"]
456
+				: '';
459 457
 			$l_severity_code = isset($data_array["L_SEVERITYCODE{$n}"])
460
-                ? $data_array["L_SEVERITYCODE{$n}"]
461
-                : '';
458
+				? $data_array["L_SEVERITYCODE{$n}"]
459
+				: '';
462 460
 			$l_short_message = isset($data_array["L_SHORTMESSAGE{$n}"])
463
-                ? $data_array["L_SHORTMESSAGE{$n}"]
464
-                : '';
461
+				? $data_array["L_SHORTMESSAGE{$n}"]
462
+				: '';
465 463
 			$l_long_message = isset($data_array["L_LONGMESSAGE{$n}"])
466
-                ? $data_array["L_LONGMESSAGE{$n}"]
467
-                : '';
464
+				? $data_array["L_LONGMESSAGE{$n}"]
465
+				: '';
468 466
 
469 467
 			if ( $n === 0 ) {
470 468
 				$errors = array(
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' )) { exit('NO direct script access allowed'); }
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('NO direct script access allowed'); }
2 2
 
3 3
 /**
4 4
  * ----------------------------------------------
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 	 *
97 97
 *@param array $settings_array
98 98
 	 */
99
-	public function set_settings( $settings_array ) {
99
+	public function set_settings($settings_array) {
100 100
 		parent::set_settings($settings_array);
101 101
 		// Redirect URL.
102 102
         $this->_base_gateway_url = $this->_debug_mode
@@ -115,19 +115,19 @@  discard block
 block discarded – undo
115 115
      * @return \EE_Payment|\EEI_Payment
116 116
      * @throws \EE_Error
117 117
      */
118
-	public function set_redirection_info( $payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL ) {
119
-		if ( ! $payment instanceof EEI_Payment ) {
120
-			$payment->set_gateway_response( __( 'Error. No associated payment was found.', 'event_espresso' ) );
121
-			$payment->set_status( $this->_pay_model->failed_status() );
118
+	public function set_redirection_info($payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL) {
119
+		if ( ! $payment instanceof EEI_Payment) {
120
+			$payment->set_gateway_response(__('Error. No associated payment was found.', 'event_espresso'));
121
+			$payment->set_status($this->_pay_model->failed_status());
122 122
 			return $payment;
123 123
 		}
124 124
 		$transaction = $payment->transaction();
125
-		if ( ! $transaction instanceof EEI_Transaction ) {
126
-			$payment->set_gateway_response( __( 'Could not process this payment because it has no associated transaction.', 'event_espresso' ) );
127
-			$payment->set_status( $this->_pay_model->failed_status() );
125
+		if ( ! $transaction instanceof EEI_Transaction) {
126
+			$payment->set_gateway_response(__('Could not process this payment because it has no associated transaction.', 'event_espresso'));
127
+			$payment->set_status($this->_pay_model->failed_status());
128 128
 			return $payment;
129 129
 		}
130
-		$order_description = substr( $this->_format_order_description($payment), 0, 127 );
130
+		$order_description = substr($this->_format_order_description($payment), 0, 127);
131 131
 		$primary_registration = $transaction->primary_registration();
132 132
 		$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee() : false;
133 133
 		$locale = explode('-', get_bloginfo('language'));
@@ -141,37 +141,37 @@  discard block
 block discarded – undo
141 141
 			'RETURNURL' => $return_url,
142 142
 			'CANCELURL' => $cancel_url,
143 143
 			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
144
-			'SOLUTIONTYPE' => 'Sole',	// Buyer does not need to create a PayPal account to check out. This is referred to as PayPal Account Optional.
145
-			'BUTTONSOURCE' => 'EventEspresso_SP',//EE will blow up if you change this
144
+			'SOLUTIONTYPE' => 'Sole', // Buyer does not need to create a PayPal account to check out. This is referred to as PayPal Account Optional.
145
+			'BUTTONSOURCE' => 'EventEspresso_SP', //EE will blow up if you change this
146 146
 			'LOCALECODE' => $locale[1]	// Locale of the pages displayed by PayPal during Express Checkout.
147 147
 		);
148 148
 
149 149
 		// Show itemized list.
150
-		if ( $this->_money->compare_floats( $payment->amount(), $transaction->total(), '==' ) ) {
150
+		if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
151 151
 			$item_num = 0;
152 152
 			$itemized_sum = 0;
153 153
 			$total_line_items = $transaction->total_line_item();
154 154
 			// Go through each item in the list.
155
-			foreach ( $total_line_items->get_items() as $line_item ) {
156
-				if ( $line_item instanceof EE_Line_Item ) {
155
+			foreach ($total_line_items->get_items() as $line_item) {
156
+				if ($line_item instanceof EE_Line_Item) {
157 157
 					// PayPal doesn't like line items with 0.00 amount, so we may skip those.
158
-					if ( EEH_Money::compare_floats( $line_item->total(), '0.00', '==' ) ) {
158
+					if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
159 159
 						continue;
160 160
 					}
161 161
 
162 162
 					$unit_price = $line_item->unit_price();
163 163
 					$line_item_quantity = $line_item->quantity();
164 164
 					// This is a discount.
165
-					if ( $line_item->is_percent() ) {
165
+					if ($line_item->is_percent()) {
166 166
 						$unit_price = $line_item->total();
167 167
 						$line_item_quantity = 1;
168 168
 					}
169 169
 					// Item Name.
170
-					$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr($this->_format_line_item_name( $line_item, $payment), 0, 127);
170
+					$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr($this->_format_line_item_name($line_item, $payment), 0, 127);
171 171
 					// Item description.
172
-					$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = substr($this->_format_line_item_desc( $line_item, $payment), 0, 127);
172
+					$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = substr($this->_format_line_item_desc($line_item, $payment), 0, 127);
173 173
 					// Cost of individual item.
174
-					$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency( $unit_price );
174
+					$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency($unit_price);
175 175
 					// Item Number.
176 176
 					$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
177 177
 					// Item quantity.
@@ -188,16 +188,16 @@  discard block
 block discarded – undo
188 188
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
189 189
 			$token_request_dtls['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
190 190
 
191
-			$itemized_sum_diff_from_txn_total = round( $transaction->total() - $itemized_sum - $total_line_items->get_total_tax(), 2 );
191
+			$itemized_sum_diff_from_txn_total = round($transaction->total() - $itemized_sum - $total_line_items->get_total_tax(), 2);
192 192
 			// If we were not able to recognize some item like promotion, surcharge or cancellation,
193 193
 			// add the difference as an extra line item.
194
-			if ( $this->_money->compare_floats( $itemized_sum_diff_from_txn_total, 0, '!=' ) ) {
194
+			if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
195 195
 				// Item Name.
196
-				$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr( __( 'Other (promotion/surcharge/cancellation)', 'event_espresso' ), 0, 127 );
196
+				$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr(__('Other (promotion/surcharge/cancellation)', 'event_espresso'), 0, 127);
197 197
 				// Item description.
198 198
 				$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = '';
199 199
 				// Cost of individual item.
200
-				$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency( $itemized_sum_diff_from_txn_total );
200
+				$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency($itemized_sum_diff_from_txn_total);
201 201
 				// Item Number.
202 202
 				$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
203 203
 				// Item quantity.
@@ -209,11 +209,11 @@  discard block
 block discarded – undo
209 209
 		} else {
210 210
 			// Just one Item.
211 211
 			// Item Name.
212
-			$token_request_dtls['L_PAYMENTREQUEST_0_NAME0'] = substr( $this->_format_partial_payment_line_item_name($payment), 0, 127 );
212
+			$token_request_dtls['L_PAYMENTREQUEST_0_NAME0'] = substr($this->_format_partial_payment_line_item_name($payment), 0, 127);
213 213
 			// Item description.
214
-			$token_request_dtls['L_PAYMENTREQUEST_0_DESC0'] = substr( $this->_format_partial_payment_line_item_desc($payment), 0, 127 );
214
+			$token_request_dtls['L_PAYMENTREQUEST_0_DESC0'] = substr($this->_format_partial_payment_line_item_desc($payment), 0, 127);
215 215
 			// Cost of individual item.
216
-			$token_request_dtls['L_PAYMENTREQUEST_0_AMT0'] = $this->format_currency( $payment->amount() );
216
+			$token_request_dtls['L_PAYMENTREQUEST_0_AMT0'] = $this->format_currency($payment->amount());
217 217
 			// Item Number.
218 218
 			$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
219 219
 			// Item quantity.
@@ -221,14 +221,14 @@  discard block
 block discarded – undo
221 221
 			// Digital item is sold.
222 222
 			$token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
223 223
 			// Item's sales S/H and tax amount.
224
-			$token_request_dtls['PAYMENTREQUEST_0_ITEMAMT'] = $this->format_currency( $payment->amount() );
224
+			$token_request_dtls['PAYMENTREQUEST_0_ITEMAMT'] = $this->format_currency($payment->amount());
225 225
 			$token_request_dtls['PAYMENTREQUEST_0_TAXAMT'] = '0';
226 226
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
227 227
 			$token_request_dtls['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
228 228
 		}
229 229
 		// Automatically filling out shipping and contact information.
230
-		if ( $this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee ) {
231
-			$token_request_dtls['NOSHIPPING'] = '2';	//  If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
230
+		if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
231
+			$token_request_dtls['NOSHIPPING'] = '2'; //  If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
232 232
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
233 233
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
234 234
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
@@ -237,34 +237,34 @@  discard block
 block discarded – undo
237 237
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
238 238
 			$token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
239 239
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
240
-		} elseif ( ! $this->_request_shipping_addr ) {
240
+		} elseif ( ! $this->_request_shipping_addr) {
241 241
 			// Do not request shipping details on the PP Checkout page.
242 242
 			$token_request_dtls['NOSHIPPING'] = '1';
243 243
 			$token_request_dtls['REQCONFIRMSHIPPING'] = '0';
244 244
 
245 245
 		}
246 246
 		// Used a business/personal logo on the PayPal page.
247
-		if ( ! empty($this->_image_url) ) {
247
+		if ( ! empty($this->_image_url)) {
248 248
 			$token_request_dtls['LOGOIMG'] = $this->_image_url;
249 249
 		}
250 250
 		// Request PayPal token.
251
-		$token_request_response = $this->_ppExpress_request( $token_request_dtls, 'Payment Token', $payment );
252
-		$token_rstatus = $this->_ppExpress_check_response( $token_request_response );
253
-		$response_args = ( isset($token_rstatus['args']) && is_array($token_rstatus['args']) ) ? $token_rstatus['args'] : array();
254
-		if ( $token_rstatus['status'] ) {
251
+		$token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
252
+		$token_rstatus = $this->_ppExpress_check_response($token_request_response);
253
+		$response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args'])) ? $token_rstatus['args'] : array();
254
+		if ($token_rstatus['status']) {
255 255
 			// We got the Token so we may continue with the payment and redirect the client.
256
-			$payment->set_details( $response_args );
256
+			$payment->set_details($response_args);
257 257
 
258 258
 			$gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
259
-			$payment->set_redirect_url( $gateway_url . '/checkoutnow?useraction=commit&cmd=_express-checkout&token=' . $response_args['TOKEN'] );
259
+			$payment->set_redirect_url($gateway_url.'/checkoutnow?useraction=commit&cmd=_express-checkout&token='.$response_args['TOKEN']);
260 260
 		} else {
261
-			if ( isset($response_args['L_ERRORCODE']) ) {
262
-				$payment->set_gateway_response( $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE'] );
261
+			if (isset($response_args['L_ERRORCODE'])) {
262
+				$payment->set_gateway_response($response_args['L_ERRORCODE'].'; '.$response_args['L_SHORTMESSAGE']);
263 263
 			} else {
264
-				$payment->set_gateway_response( __( 'Error occurred while trying to setup the Express Checkout.', 'event_espresso' ) );
264
+				$payment->set_gateway_response(__('Error occurred while trying to setup the Express Checkout.', 'event_espresso'));
265 265
 			}
266
-			$payment->set_details( $response_args );
267
-			$payment->set_status( $this->_pay_model->failed_status() );
266
+			$payment->set_details($response_args);
267
+			$payment->set_status($this->_pay_model->failed_status());
268 268
 		}
269 269
 
270 270
 		return $payment;
@@ -280,22 +280,22 @@  discard block
 block discarded – undo
280 280
 	 *  @param EEI_Transaction $transaction
281 281
 	 *  @return EEI_Payment
282 282
 	 */
283
-	public function handle_payment_update( $update_info, $transaction ) {
283
+	public function handle_payment_update($update_info, $transaction) {
284 284
 		$payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
285 285
 
286
-		if ( $payment instanceof EEI_Payment ) {
287
-			$this->log( array( 'Return from Authorization' => $update_info ), $payment );
286
+		if ($payment instanceof EEI_Payment) {
287
+			$this->log(array('Return from Authorization' => $update_info), $payment);
288 288
 			$transaction = $payment->transaction();
289
-			if ( ! $transaction instanceof EEI_Transaction ) {
290
-				$payment->set_gateway_response( __( 'Could not process this payment because it has no associated transaction.', 'event_espresso' ) );
291
-				$payment->set_status( $this->_pay_model->failed_status() );
289
+			if ( ! $transaction instanceof EEI_Transaction) {
290
+				$payment->set_gateway_response(__('Could not process this payment because it has no associated transaction.', 'event_espresso'));
291
+				$payment->set_status($this->_pay_model->failed_status());
292 292
 				return $payment;
293 293
 			}
294 294
 			$primary_registrant = $transaction->primary_registration();
295 295
             $payment_details = $payment->details();
296 296
             // Check if we still have the token.
297
-			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN']) ) {
298
-				$payment->set_status( $this->_pay_model->failed_status() );
297
+			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
298
+				$payment->set_status($this->_pay_model->failed_status());
299 299
 				return $payment;
300 300
 			}
301 301
 
@@ -304,10 +304,10 @@  discard block
 block discarded – undo
304 304
 				'TOKEN' => $payment_details['TOKEN']
305 305
 			);
306 306
 			// Request Customer Details.
307
-			$cdetails_request_response = $this->_ppExpress_request( $cdetails_request_dtls, 'Customer Details', $payment );
308
-			$cdetails_rstatus = $this->_ppExpress_check_response( $cdetails_request_response );
309
-			$cdata_response_args = ( isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']) ) ? $cdetails_rstatus['args'] : array();
310
-			if ( $cdetails_rstatus['status'] ) {
307
+			$cdetails_request_response = $this->_ppExpress_request($cdetails_request_dtls, 'Customer Details', $payment);
308
+			$cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
309
+			$cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args'])) ? $cdetails_rstatus['args'] : array();
310
+			if ($cdetails_rstatus['status']) {
311 311
 				// We got the PayerID so now we can Complete the transaction.
312 312
 				$docheckout_request_dtls = array(
313 313
 					'METHOD' => 'DoExpressCheckoutPayment',
@@ -318,39 +318,39 @@  discard block
 block discarded – undo
318 318
 					'PAYMENTREQUEST_0_CURRENCYCODE' => $payment->currency_code()
319 319
 				);
320 320
 				// Payment Checkout/Capture.
321
-				$docheckout_request_response = $this->_ppExpress_request( $docheckout_request_dtls, 'Do Payment', $payment );
322
-				$docheckout_rstatus = $this->_ppExpress_check_response( $docheckout_request_response );
323
-				$docheckout_response_args = ( isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']) ) ? $docheckout_rstatus['args'] : array();
324
-				if ( $docheckout_rstatus['status'] ) {
321
+				$docheckout_request_response = $this->_ppExpress_request($docheckout_request_dtls, 'Do Payment', $payment);
322
+				$docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
323
+				$docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args'])) ? $docheckout_rstatus['args'] : array();
324
+				if ($docheckout_rstatus['status']) {
325 325
 					// All is well, payment approved.
326 326
 					$primary_registration_code = $primary_registrant instanceof EE_Registration ? $primary_registrant->reg_code() : '';
327
-					$payment->set_extra_accntng( $primary_registration_code );
328
-					$payment->set_amount( isset($docheckout_response_args['PAYMENTINFO_0_AMT']) ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT'] : 0 );
329
-					$payment->set_txn_id_chq_nmbr( isset( $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] ) ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] : null );
330
-					$payment->set_details( $cdata_response_args );
331
-					$payment->set_gateway_response( isset( $docheckout_response_args['PAYMENTINFO_0_ACK'] ) ? $docheckout_response_args['PAYMENTINFO_0_ACK'] : '' );
332
-					$payment->set_status( $this->_pay_model->approved_status() );
327
+					$payment->set_extra_accntng($primary_registration_code);
328
+					$payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT']) ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT'] : 0);
329
+					$payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']) ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] : null);
330
+					$payment->set_details($cdata_response_args);
331
+					$payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK']) ? $docheckout_response_args['PAYMENTINFO_0_ACK'] : '');
332
+					$payment->set_status($this->_pay_model->approved_status());
333 333
 				} else {
334
-					if ( isset($docheckout_response_args['L_ERRORCODE']) ) {
335
-						$payment->set_gateway_response( $docheckout_response_args['L_ERRORCODE'] . '; ' . $docheckout_response_args['L_SHORTMESSAGE'] );
334
+					if (isset($docheckout_response_args['L_ERRORCODE'])) {
335
+						$payment->set_gateway_response($docheckout_response_args['L_ERRORCODE'].'; '.$docheckout_response_args['L_SHORTMESSAGE']);
336 336
 					} else {
337
-						$payment->set_gateway_response( __( 'Error occurred while trying to Capture the funds.', 'event_espresso' ) );
337
+						$payment->set_gateway_response(__('Error occurred while trying to Capture the funds.', 'event_espresso'));
338 338
 					}
339
-					$payment->set_details( $docheckout_response_args );
340
-					$payment->set_status( $this->_pay_model->declined_status() );
339
+					$payment->set_details($docheckout_response_args);
340
+					$payment->set_status($this->_pay_model->declined_status());
341 341
 				}
342 342
 			} else {
343
-				if ( isset($cdata_response_args['L_ERRORCODE']) ) {
344
-					$payment->set_gateway_response( $cdata_response_args['L_ERRORCODE'] . '; ' . $cdata_response_args['L_SHORTMESSAGE'] );
343
+				if (isset($cdata_response_args['L_ERRORCODE'])) {
344
+					$payment->set_gateway_response($cdata_response_args['L_ERRORCODE'].'; '.$cdata_response_args['L_SHORTMESSAGE']);
345 345
 				} else {
346
-					$payment->set_gateway_response( __( 'Error occurred while trying to get payment Details from PayPal.', 'event_espresso' ) );
346
+					$payment->set_gateway_response(__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso'));
347 347
 				}
348
-				$payment->set_details( $cdata_response_args );
349
-				$payment->set_status( $this->_pay_model->failed_status() );
348
+				$payment->set_details($cdata_response_args);
349
+				$payment->set_status($this->_pay_model->failed_status());
350 350
 			}
351 351
 		} else {
352
-			$payment->set_gateway_response( __( 'Error occurred while trying to process the payment.', 'event_espresso' ) );
353
-			$payment->set_status( $this->_pay_model->failed_status() );
352
+			$payment->set_gateway_response(__('Error occurred while trying to process the payment.', 'event_espresso'));
353
+			$payment->set_status($this->_pay_model->failed_status());
354 354
 		}
355 355
 
356 356
 		return $payment;
@@ -365,16 +365,16 @@  discard block
 block discarded – undo
365 365
 	 *  @param EEI_Payment  $payment
366 366
 	 *	@return mixed
367 367
 	 */
368
-	public function _ppExpress_request( $request_params, $request_text, $payment ) {
368
+	public function _ppExpress_request($request_params, $request_text, $payment) {
369 369
 		$request_dtls = array(
370 370
 			'VERSION' => '204.0',
371
-			'USER' => urlencode( $this->_api_username ),
372
-			'PWD' => urlencode( $this->_api_password ),
373
-			'SIGNATURE' => urlencode( $this->_api_signature )
371
+			'USER' => urlencode($this->_api_username),
372
+			'PWD' => urlencode($this->_api_password),
373
+			'SIGNATURE' => urlencode($this->_api_signature)
374 374
 		);
375
-		$dtls = array_merge( $request_dtls, $request_params );
375
+		$dtls = array_merge($request_dtls, $request_params);
376 376
 
377
-		$this->_log_clean_request( $dtls, $payment, $request_text . ' Request' );
377
+		$this->_log_clean_request($dtls, $payment, $request_text.' Request');
378 378
 		// Request Customer Details.
379 379
 		$request_response = wp_remote_post(
380 380
 			$this->_base_gateway_url,
@@ -384,11 +384,11 @@  discard block
 block discarded – undo
384 384
 				'httpversion' => '1.1',
385 385
 				'cookies' => array(),
386 386
 				'headers' => array(),
387
-				'body' => http_build_query( $dtls )
387
+				'body' => http_build_query($dtls)
388 388
 			)
389 389
 		);
390 390
 		// Log the response.
391
-		$this->log( array( $request_text . ' Response' => $request_response), $payment );
391
+		$this->log(array($request_text.' Response' => $request_response), $payment);
392 392
 
393 393
 		return $request_response;
394 394
 	}
@@ -400,13 +400,13 @@  discard block
 block discarded – undo
400 400
 	 *	@param mixed        $request_response
401 401
 	 *	@return array
402 402
 	 */
403
-	public function _ppExpress_check_response( $request_response ) {
404
-		if (empty($request_response['body']) || is_wp_error( $request_response ) ) {
403
+	public function _ppExpress_check_response($request_response) {
404
+		if (empty($request_response['body']) || is_wp_error($request_response)) {
405 405
             // If we got here then there was an error in this request.
406 406
             return array('status' => false, 'args' => $request_response);
407 407
         }
408 408
         $response_args = array();
409
-        parse_str( urldecode($request_response['body']), $response_args );
409
+        parse_str(urldecode($request_response['body']), $response_args);
410 410
         if ( ! isset($response_args['ACK'])) {
411 411
             return array('status' => false, 'args' => $request_response);
412 412
         }
@@ -436,10 +436,10 @@  discard block
 block discarded – undo
436 436
 	 * @param string  		$info
437 437
 	 * @return void
438 438
 	 */
439
-	private function _log_clean_request($request, $payment, $info ) {
439
+	private function _log_clean_request($request, $payment, $info) {
440 440
 		$cleaned_request_data = $request;
441 441
 		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
442
-		$this->log( array($info => $cleaned_request_data), $payment );
442
+		$this->log(array($info => $cleaned_request_data), $payment);
443 443
 	}
444 444
 
445 445
 
@@ -449,10 +449,10 @@  discard block
 block discarded – undo
449 449
 	 *  @param array	$data_array
450 450
 	 *  @return array
451 451
 	 */
452
-	private function _get_errors( $data_array ) {
452
+	private function _get_errors($data_array) {
453 453
 		$errors = array();
454 454
 		$n = 0;
455
-		while ( isset($data_array["L_ERRORCODE{$n}"]) ) {
455
+		while (isset($data_array["L_ERRORCODE{$n}"])) {
456 456
 			$l_error_code = isset($data_array["L_ERRORCODE{$n}"])
457 457
                 ? $data_array["L_ERRORCODE{$n}"]
458 458
                 : '';
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
                 ? $data_array["L_LONGMESSAGE{$n}"]
467 467
                 : '';
468 468
 
469
-			if ( $n === 0 ) {
469
+			if ($n === 0) {
470 470
 				$errors = array(
471 471
 					'L_ERRORCODE' => $l_error_code,
472 472
 					'L_SHORTMESSAGE' => $l_short_message,
@@ -474,10 +474,10 @@  discard block
 block discarded – undo
474 474
 					'L_SEVERITYCODE' => $l_severity_code
475 475
 				);
476 476
 			} else {
477
-				$errors['L_ERRORCODE'] .= ', ' . $l_error_code;
478
-				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
479
-				$errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
480
-				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
477
+				$errors['L_ERRORCODE'] .= ', '.$l_error_code;
478
+				$errors['L_SHORTMESSAGE'] .= ', '.$l_short_message;
479
+				$errors['L_LONGMESSAGE'] .= ', '.$l_long_message;
480
+				$errors['L_SEVERITYCODE'] .= ', '.$l_severity_code;
481 481
 			}
482 482
 
483 483
 			$n++;
Please login to merge, or discard this patch.
attendee_information/EE_SPCO_Reg_Step_Attendee_Information.class.php 2 patches
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -1,16 +1,16 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('No direct script access allowed'); }
2 2
  /**
3
- *
4
- * Class EE_SPCO_Reg_Step_Attendee_Information
5
- *
6
- * Description
7
- *
8
- * @package 			Event Espresso
9
- * @subpackage 	core
10
- * @author 				Brent Christensen
11
- * @since 				4.5.0
12
- *
13
- */
3
+  *
4
+  * Class EE_SPCO_Reg_Step_Attendee_Information
5
+  *
6
+  * Description
7
+  *
8
+  * @package 			Event Espresso
9
+  * @subpackage 	core
10
+  * @author 				Brent Christensen
11
+  * @since 				4.5.0
12
+  *
13
+  */
14 14
 class EE_SPCO_Reg_Step_Attendee_Information extends EE_SPCO_Reg_Step {
15 15
 
16 16
 	/**
@@ -135,33 +135,33 @@  discard block
 block discarded – undo
135 135
 					$registration instanceof EE_Registration
136 136
 					&& $this->checkout->visit_allows_processing_of_this_registration( $registration )
137 137
 				) {
138
-                    $attendee_reg_form = $this->_registrations_reg_form($registration);
139
-                    if ($attendee_reg_form instanceof EE_Form_Section_Proper) {
140
-                        $subsections[$registration->reg_url_link()] = $attendee_reg_form;
141
-                        if ( ! $this->checkout->admin_request) {
142
-                            $template_args['registrations'][$registration->reg_url_link()] = $registration;
143
-                            $template_args['ticket_count'][$registration->ticket()->ID()] = isset(
144
-                                $template_args['ticket_count'][$registration->ticket()->ID()]
145
-                            )
146
-                                ? $template_args['ticket_count'][$registration->ticket()->ID()] + 1
147
-                                : 1;
148
-                            $ticket_line_item = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
149
-                                $this->checkout->cart->get_grand_total(),
150
-                                'Ticket',
151
-                                array($registration->ticket()->ID())
152
-                            );
153
-                            $ticket_line_item = is_array($ticket_line_item)
154
-                                ? reset($ticket_line_item)
155
-                                : $ticket_line_item;
156
-                            $template_args['ticket_line_item'][$registration->ticket()
157
-                                                                            ->ID()] = $Line_Item_Display->display_line_item(
158
-                                $ticket_line_item
159
-                            );
160
-                        }
161
-                    }
162
-                    if ($registration->is_primary_registrant()) {
163
-                        $primary_registrant = $registration->reg_url_link();
164
-                    }
138
+					$attendee_reg_form = $this->_registrations_reg_form($registration);
139
+					if ($attendee_reg_form instanceof EE_Form_Section_Proper) {
140
+						$subsections[$registration->reg_url_link()] = $attendee_reg_form;
141
+						if ( ! $this->checkout->admin_request) {
142
+							$template_args['registrations'][$registration->reg_url_link()] = $registration;
143
+							$template_args['ticket_count'][$registration->ticket()->ID()] = isset(
144
+								$template_args['ticket_count'][$registration->ticket()->ID()]
145
+							)
146
+								? $template_args['ticket_count'][$registration->ticket()->ID()] + 1
147
+								: 1;
148
+							$ticket_line_item = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
149
+								$this->checkout->cart->get_grand_total(),
150
+								'Ticket',
151
+								array($registration->ticket()->ID())
152
+							);
153
+							$ticket_line_item = is_array($ticket_line_item)
154
+								? reset($ticket_line_item)
155
+								: $ticket_line_item;
156
+							$template_args['ticket_line_item'][$registration->ticket()
157
+																			->ID()] = $Line_Item_Display->display_line_item(
158
+								$ticket_line_item
159
+							);
160
+						}
161
+					}
162
+					if ($registration->is_primary_registrant()) {
163
+						$primary_registrant = $registration->reg_url_link();
164
+					}
165 165
 				}
166 166
 			}
167 167
 			// print_copy_info ?
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 				// generate hidden input
174 174
 				if (
175 175
 					isset( $subsections[ $primary_registrant ] )
176
-				     && $subsections[ $primary_registrant ] instanceof EE_Form_Section_Proper
176
+					 && $subsections[ $primary_registrant ] instanceof EE_Form_Section_Proper
177 177
 				) {
178 178
 					$subsections[ $primary_registrant ]->add_subsections( $copy_options, 'primary_registrant', false );
179 179
 				}
@@ -208,35 +208,35 @@  discard block
 block discarded – undo
208 208
 	 */
209 209
 	private function _registrations_reg_form( EE_Registration $registration ) {
210 210
 		static $attendee_nmbr = 1;
211
-        $form_args = array();
211
+		$form_args = array();
212 212
 		// verify that registration has valid event
213 213
 		if ( $registration->event() instanceof EE_Event ) {
214 214
 			$question_groups = $registration->event()->question_groups(
215
-                array(
216
-                    array(
217
-                        'Event.EVT_ID'                     => $registration->event()->ID(),
218
-                        'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false
219
-                    ),
220
-                    'order_by' => array('QSG_order' => 'ASC')
221
-                )
222
-            );
215
+				array(
216
+					array(
217
+						'Event.EVT_ID'                     => $registration->event()->ID(),
218
+						'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false
219
+					),
220
+					'order_by' => array('QSG_order' => 'ASC')
221
+				)
222
+			);
223 223
 			if ( $question_groups ) {
224
-                // array of params to pass to parent constructor
225
-                $form_args = array(
226
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
227
-                    'html_class'      => 'ee-reg-form-attendee-dv',
228
-                    'html_style'      => $this->checkout->admin_request
229
-                        ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
230
-                        : '',
231
-                    'subsections'     => array(),
232
-                    'layout_strategy' => new EE_Fieldset_Section_Layout(
233
-                        array(
234
-                            'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
235
-                            'legend_text'  => sprintf(__('Attendee %d', 'event_espresso'), $attendee_nmbr)
236
-                        )
237
-                    )
238
-                );
239
-                foreach ( $question_groups as $question_group ) {
224
+				// array of params to pass to parent constructor
225
+				$form_args = array(
226
+					'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
227
+					'html_class'      => 'ee-reg-form-attendee-dv',
228
+					'html_style'      => $this->checkout->admin_request
229
+						? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
230
+						: '',
231
+					'subsections'     => array(),
232
+					'layout_strategy' => new EE_Fieldset_Section_Layout(
233
+						array(
234
+							'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
235
+							'legend_text'  => sprintf(__('Attendee %d', 'event_espresso'), $attendee_nmbr)
236
+						)
237
+					)
238
+				);
239
+				foreach ( $question_groups as $question_group ) {
240 240
 					if ( $question_group instanceof EE_Question_Group ) {
241 241
 						$form_args['subsections'][ $question_group->identifier() ] = $this->_question_group_reg_form(
242 242
 							$registration,
@@ -244,19 +244,19 @@  discard block
 block discarded – undo
244 244
 						);
245 245
 					}
246 246
 				}
247
-                // add hidden input
248
-                $form_args['subsections']['additional_attendee_reg_info'] = $this->_additional_attendee_reg_info_input(
249
-                    $registration
250
-                );
251
-                // if we have question groups for additional attendees, then display the copy options
247
+				// add hidden input
248
+				$form_args['subsections']['additional_attendee_reg_info'] = $this->_additional_attendee_reg_info_input(
249
+					$registration
250
+				);
251
+				// if we have question groups for additional attendees, then display the copy options
252 252
 				$this->_print_copy_info = $attendee_nmbr > 1 ? true : $this->_print_copy_info;
253
-                if ($registration->is_primary_registrant()) {
254
-                    // generate hidden input
255
-                    $form_args['subsections']['primary_registrant'] = $this->_additional_primary_registrant_inputs($registration);
256
-                }
257
-            }
253
+				if ($registration->is_primary_registrant()) {
254
+					// generate hidden input
255
+					$form_args['subsections']['primary_registrant'] = $this->_additional_primary_registrant_inputs($registration);
256
+				}
257
+			}
258 258
 		}
259
-        $attendee_nmbr++;
259
+		$attendee_nmbr++;
260 260
 		return ! empty($form_args) ? new EE_Form_Section_Proper( $form_args ) : null;
261 261
 	}
262 262
 
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 					if ( isset( $valid_data[ $reg_url_link ] ) ) {
890 890
 						// do we need to copy basic info from primary attendee ?
891 891
 						$copy_primary = isset( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] )
892
-						                && absint( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] ) === 0
892
+										&& absint( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] ) === 0
893 893
 							? true
894 894
 							: false;
895 895
 						// filter form input data for this registration
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
 			? $form_input
1065 1065
 			: $form_input . '-' . $registration->reg_url_link();
1066 1066
 		$answer_is_obj = isset( $this->_registration_answers[ $answer_cache_id ] )
1067
-		                 && $this->_registration_answers[ $answer_cache_id ] instanceof EE_Answer
1067
+						 && $this->_registration_answers[ $answer_cache_id ] instanceof EE_Answer
1068 1068
 			? true
1069 1069
 			: false;
1070 1070
 		//rename form_inputs if they are EE_Attendee properties
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
 		// then attempt to copy them from the primary attendee
1185 1185
 		if (
1186 1186
 			$this->checkout->primary_attendee_obj instanceof EE_Attendee
1187
-            && ! isset( $attendee_data['ATT_fname'], $attendee_data['ATT_email'] )
1187
+			&& ! isset( $attendee_data['ATT_fname'], $attendee_data['ATT_email'] )
1188 1188
 		) {
1189 1189
 			return $this->checkout->primary_attendee_obj;
1190 1190
 		}
@@ -1302,7 +1302,7 @@  discard block
 block discarded – undo
1302 1302
 		}
1303 1303
 		foreach ( $critical_attendee_details as $critical_attendee_detail ) {
1304 1304
 			if ( ! isset( $attendee_data[ $critical_attendee_detail ] )
1305
-			     || empty( $attendee_data[ $critical_attendee_detail ] )
1305
+				 || empty( $attendee_data[ $critical_attendee_detail ] )
1306 1306
 			) {
1307 1307
 				$attendee_data[ $critical_attendee_detail ] = $this->checkout->primary_attendee_obj->get(
1308 1308
 					$critical_attendee_detail
Please login to merge, or discard this patch.
Spacing   +211 added lines, -212 removed lines patch added patch discarded remove patch
@@ -41,21 +41,21 @@  discard block
 block discarded – undo
41 41
 	 * @access    public
42 42
 	 * @param    EE_Checkout $checkout
43 43
 	 */
44
-	public function __construct( EE_Checkout $checkout ) {
44
+	public function __construct(EE_Checkout $checkout) {
45 45
 		$this->_slug = 'attendee_information';
46 46
 		$this->_name = __('Attendee Information', 'event_espresso');
47
-		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'attendee_info_main.template.php';
47
+		$this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'attendee_info_main.template.php';
48 48
 		$this->checkout = $checkout;
49 49
 		$this->_reset_success_message();
50 50
 		$this->set_instructions(
51
-			__( 'Please answer the following registration questions before proceeding.', 'event_espresso' )
51
+			__('Please answer the following registration questions before proceeding.', 'event_espresso')
52 52
 		);
53 53
 	}
54 54
 
55 55
 
56 56
 
57 57
 	public function translate_js_strings() {
58
-		EE_Registry::$i18n_js_strings['required_field'] = __( ' is a required question.', 'event_espresso' );
58
+		EE_Registry::$i18n_js_strings['required_field'] = __(' is a required question.', 'event_espresso');
59 59
 		EE_Registry::$i18n_js_strings['required_multi_field'] = __(
60 60
 			' is a required question. Please enter a value for at least one of the options.',
61 61
 			'event_espresso'
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 		// calculate taxes
116 116
 		$Line_Item_Display->display_line_item(
117 117
 			$this->checkout->cart->get_grand_total(),
118
-			array( 'set_tax_rate' => true )
118
+			array('set_tax_rate' => true)
119 119
 		);
120 120
 		/** @var $subsections EE_Form_Section_Proper[] */
121 121
 		$subsections = array(
@@ -127,13 +127,13 @@  discard block
 block discarded – undo
127 127
 			'ticket_count' 	=> array()
128 128
 		);
129 129
 		// grab the saved registrations from the transaction
130
-		$registrations = $this->checkout->transaction->registrations( $this->checkout->reg_cache_where_params );
131
-		if ( $registrations ) {
132
-			foreach ( $registrations as $registration ) {
130
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
131
+		if ($registrations) {
132
+			foreach ($registrations as $registration) {
133 133
 				// can this registration be processed during this visit ?
134 134
 				if (
135 135
 					$registration instanceof EE_Registration
136
-					&& $this->checkout->visit_allows_processing_of_this_registration( $registration )
136
+					&& $this->checkout->visit_allows_processing_of_this_registration($registration)
137 137
 				) {
138 138
                     $attendee_reg_form = $this->_registrations_reg_form($registration);
139 139
                     if ($attendee_reg_form instanceof EE_Form_Section_Proper) {
@@ -165,17 +165,17 @@  discard block
 block discarded – undo
165 165
 				}
166 166
 			}
167 167
 			// print_copy_info ?
168
-			if ( $primary_registrant && ! $this->checkout->admin_request && count( $registrations ) > 1 ) {
168
+			if ($primary_registrant && ! $this->checkout->admin_request && count($registrations) > 1) {
169 169
 				// TODO: add admin option for toggling copy attendee info, then use that value to change $this->_print_copy_info
170 170
 				$copy_options['spco_copy_attendee_chk'] = $this->_print_copy_info
171 171
 					? $this->_copy_attendee_info_form()
172 172
 					: $this->_auto_copy_attendee_info();
173 173
 				// generate hidden input
174 174
 				if (
175
-					isset( $subsections[ $primary_registrant ] )
176
-				     && $subsections[ $primary_registrant ] instanceof EE_Form_Section_Proper
175
+					isset($subsections[$primary_registrant])
176
+				     && $subsections[$primary_registrant] instanceof EE_Form_Section_Proper
177 177
 				) {
178
-					$subsections[ $primary_registrant ]->add_subsections( $copy_options, 'primary_registrant', false );
178
+					$subsections[$primary_registrant]->add_subsections($copy_options, 'primary_registrant', false);
179 179
 				}
180 180
 			}
181 181
 
@@ -187,8 +187,7 @@  discard block
 block discarded – undo
187 187
 				'html_id' 					=> $this->reg_form_name(),
188 188
 				'subsections' 			=> $subsections,
189 189
 				'layout_strategy'		=> $this->checkout->admin_request ?
190
-					new EE_Div_Per_Section_Layout() :
191
-					new EE_Template_Layout(
190
+					new EE_Div_Per_Section_Layout() : new EE_Template_Layout(
192 191
 						array(
193 192
 							'layout_template_file' 	=> $this->_template, // layout_template
194 193
 							'template_args' 				=> $template_args
@@ -206,11 +205,11 @@  discard block
 block discarded – undo
206 205
 	 * @return EE_Form_Section_Proper
207 206
 	 * @throws \EE_Error
208 207
 	 */
209
-	private function _registrations_reg_form( EE_Registration $registration ) {
208
+	private function _registrations_reg_form(EE_Registration $registration) {
210 209
 		static $attendee_nmbr = 1;
211 210
         $form_args = array();
212 211
 		// verify that registration has valid event
213
-		if ( $registration->event() instanceof EE_Event ) {
212
+		if ($registration->event() instanceof EE_Event) {
214 213
 			$question_groups = $registration->event()->question_groups(
215 214
                 array(
216 215
                     array(
@@ -220,10 +219,10 @@  discard block
 block discarded – undo
220 219
                     'order_by' => array('QSG_order' => 'ASC')
221 220
                 )
222 221
             );
223
-			if ( $question_groups ) {
222
+			if ($question_groups) {
224 223
                 // array of params to pass to parent constructor
225 224
                 $form_args = array(
226
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
225
+                    'html_id'         => 'ee-registration-'.$registration->reg_url_link(),
227 226
                     'html_class'      => 'ee-reg-form-attendee-dv',
228 227
                     'html_style'      => $this->checkout->admin_request
229 228
                         ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
@@ -236,9 +235,9 @@  discard block
 block discarded – undo
236 235
                         )
237 236
                     )
238 237
                 );
239
-                foreach ( $question_groups as $question_group ) {
240
-					if ( $question_group instanceof EE_Question_Group ) {
241
-						$form_args['subsections'][ $question_group->identifier() ] = $this->_question_group_reg_form(
238
+                foreach ($question_groups as $question_group) {
239
+					if ($question_group instanceof EE_Question_Group) {
240
+						$form_args['subsections'][$question_group->identifier()] = $this->_question_group_reg_form(
242 241
 							$registration,
243 242
 							$question_group
244 243
 						);
@@ -257,7 +256,7 @@  discard block
 block discarded – undo
257 256
             }
258 257
 		}
259 258
         $attendee_nmbr++;
260
-		return ! empty($form_args) ? new EE_Form_Section_Proper( $form_args ) : null;
259
+		return ! empty($form_args) ? new EE_Form_Section_Proper($form_args) : null;
261 260
 	}
262 261
 
263 262
 
@@ -278,7 +277,7 @@  discard block
 block discarded – undo
278 277
 		// generate hidden input
279 278
 		return new EE_Hidden_Input(
280 279
 			array(
281
-				'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
280
+				'html_id' => 'additional-attendee-reg-info-'.$registration->reg_url_link(),
282 281
 				'default' => $additional_attendee_reg_info
283 282
 			)
284 283
 		);
@@ -292,26 +291,26 @@  discard block
 block discarded – undo
292 291
 	 * @return EE_Form_Section_Proper
293 292
 	 * @throws \EE_Error
294 293
 	 */
295
-	private function _question_group_reg_form( EE_Registration $registration, EE_Question_Group $question_group ){
294
+	private function _question_group_reg_form(EE_Registration $registration, EE_Question_Group $question_group) {
296 295
 		// array of params to pass to parent constructor
297 296
 		$form_args = array(
298
-			'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier(),
297
+			'html_id'         => 'ee-reg-form-qstn-grp-'.$question_group->identifier(),
299 298
 			'html_class'      => $this->checkout->admin_request
300 299
 				? 'form-table ee-reg-form-qstn-grp-dv'
301 300
 				: 'ee-reg-form-qstn-grp-dv',
302
-			'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-lbl',
301
+			'html_label_id'   => 'ee-reg-form-qstn-grp-'.$question_group->identifier().'-lbl',
303 302
 			'subsections'     => array(
304
-				'reg_form_qstn_grp_hdr' => $this->_question_group_header( $question_group )
303
+				'reg_form_qstn_grp_hdr' => $this->_question_group_header($question_group)
305 304
 			),
306 305
 			'layout_strategy' => $this->checkout->admin_request
307 306
 				? new EE_Admin_Two_Column_Layout()
308 307
 				: new EE_Div_Per_Section_Layout()
309 308
 		);
310 309
 		// where params
311
-		$query_params = array( 'QST_deleted' => 0 );
310
+		$query_params = array('QST_deleted' => 0);
312 311
 		// don't load admin only questions on the frontend
313
-		if ( ! $this->checkout->admin_request ) {
314
-			$query_params['QST_admin_only'] = array( '!=', true );
312
+		if ( ! $this->checkout->admin_request) {
313
+			$query_params['QST_admin_only'] = array('!=', true);
315 314
 		}
316 315
 		$questions = $question_group->get_many_related(
317 316
 			'Question',
@@ -333,10 +332,10 @@  discard block
 block discarded – undo
333 332
 			)
334 333
 		);
335 334
 		// loop thru questions
336
-		foreach ( $questions as $question ) {
337
-			if( $question instanceof EE_Question ){
335
+		foreach ($questions as $question) {
336
+			if ($question instanceof EE_Question) {
338 337
 				$identifier = $question->is_system_question() ? $question->system_ID() : $question->ID();
339
-				$form_args['subsections'][ $identifier ] = $this->reg_form_question( $registration, $question );
338
+				$form_args['subsections'][$identifier] = $this->reg_form_question($registration, $question);
340 339
 			}
341 340
 		}
342 341
 		$form_args['subsections'] = apply_filters(
@@ -357,7 +356,7 @@  discard block
 block discarded – undo
357 356
 			)
358 357
 		);
359 358
 //		d( $form_args );
360
-		$question_group_reg_form = new EE_Form_Section_Proper( $form_args );
359
+		$question_group_reg_form = new EE_Form_Section_Proper($form_args);
361 360
 		return apply_filters(
362 361
 			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
363 362
 			$question_group_reg_form,
@@ -374,11 +373,11 @@  discard block
 block discarded – undo
374 373
 	 * @param EE_Question_Group $question_group
375 374
 	 * @return 	EE_Form_Section_HTML
376 375
 	 */
377
-	private function _question_group_header( EE_Question_Group $question_group ){
376
+	private function _question_group_header(EE_Question_Group $question_group) {
378 377
 		$html = '';
379 378
 		// group_name
380
-		if ( $question_group->show_group_name() && $question_group->name() !== '' ) {
381
-			if ( $this->checkout->admin_request ) {
379
+		if ($question_group->show_group_name() && $question_group->name() !== '') {
380
+			if ($this->checkout->admin_request) {
382 381
 				$html .= EEH_HTML::br();
383 382
 				$html .= EEH_HTML::h3(
384 383
 					$question_group->name(),
@@ -392,7 +391,7 @@  discard block
 block discarded – undo
392 391
 			}
393 392
 		}
394 393
 		// group_desc
395
-		if ( $question_group->show_group_desc() && $question_group->desc() !== '' ) {
394
+		if ($question_group->show_group_desc() && $question_group->desc() !== '') {
396 395
 			$html .= EEH_HTML::p(
397 396
 				$question_group->desc(),
398 397
 				'',
@@ -402,7 +401,7 @@  discard block
 block discarded – undo
402 401
 			);
403 402
 
404 403
 		}
405
-		return new EE_Form_Section_HTML( $html );
404
+		return new EE_Form_Section_HTML($html);
406 405
 	}
407 406
 
408 407
 
@@ -412,7 +411,7 @@  discard block
 block discarded – undo
412 411
 	 * @return    EE_Form_Section_Proper
413 412
 	 * @throws \EE_Error
414 413
 	 */
415
-	private function _copy_attendee_info_form(){
414
+	private function _copy_attendee_info_form() {
416 415
 		// array of params to pass to parent constructor
417 416
 		return new EE_Form_Section_Proper(
418 417
 			array(
@@ -441,7 +440,7 @@  discard block
 block discarded – undo
441 440
 	private function _auto_copy_attendee_info() {
442 441
 		return new EE_Form_Section_HTML(
443 442
 			EEH_Template::locate_template(
444
-				SPCO_REG_STEPS_PATH . $this->_slug . DS . '_auto_copy_attendee_info.template.php',
443
+				SPCO_REG_STEPS_PATH.$this->_slug.DS.'_auto_copy_attendee_info.template.php',
445 444
 				apply_filters(
446 445
 					'FHEE__EE_SPCO_Reg_Step_Attendee_Information__auto_copy_attendee_info__template_args',
447 446
 					array()
@@ -465,32 +464,32 @@  discard block
 block discarded – undo
465 464
 		$copy_attendee_info_inputs = array();
466 465
 		$prev_ticket = NULL;
467 466
 		// grab the saved registrations from the transaction
468
-		$registrations = $this->checkout->transaction->registrations( $this->checkout->reg_cache_where_params );
469
-		foreach ( $registrations as $registration ) {
467
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
468
+		foreach ($registrations as $registration) {
470 469
 			// for all  attendees other than the primary attendee
471
-			if ( $registration instanceof EE_Registration && ! $registration->is_primary_registrant() ) {
470
+			if ($registration instanceof EE_Registration && ! $registration->is_primary_registrant()) {
472 471
 				// if this is a new ticket OR if this is the very first additional attendee after the primary attendee
473
-				if ( $registration->ticket()->ID() !== $prev_ticket ) {
472
+				if ($registration->ticket()->ID() !== $prev_ticket) {
474 473
 					$item_name = $registration->ticket()->name();
475 474
 					$item_name .= $registration->ticket()->description() !== ''
476
-						? ' - ' . $registration->ticket()->description()
475
+						? ' - '.$registration->ticket()->description()
477 476
 						: '';
478
-					$copy_attendee_info_inputs[ 'spco_copy_attendee_chk[ticket-' . $registration->ticket()->ID() . ']' ] = new EE_Form_Section_HTML(
479
-						'<h6 class="spco-copy-attendee-event-hdr">' . $item_name . '</h6>'
477
+					$copy_attendee_info_inputs['spco_copy_attendee_chk[ticket-'.$registration->ticket()->ID().']'] = new EE_Form_Section_HTML(
478
+						'<h6 class="spco-copy-attendee-event-hdr">'.$item_name.'</h6>'
480 479
 					);
481 480
 					$prev_ticket = $registration->ticket()->ID();
482 481
 				}
483 482
 
484
-				$copy_attendee_info_inputs[ 'spco_copy_attendee_chk[' . $registration->ID() . ']' ] = new
483
+				$copy_attendee_info_inputs['spco_copy_attendee_chk['.$registration->ID().']'] = new
485 484
 				EE_Checkbox_Multi_Input(
486 485
 					array(
487 486
 						$registration->ID() => sprintf(
488
-							__( 'Attendee #%s', 'event_espresso' ),
487
+							__('Attendee #%s', 'event_espresso'),
489 488
 							$registration->count()
490 489
 						)
491 490
 					),
492 491
 					array(
493
-						'html_id'                 => 'spco-copy-attendee-chk-' . $registration->reg_url_link(),
492
+						'html_id'                 => 'spco-copy-attendee-chk-'.$registration->reg_url_link(),
494 493
 						'html_class'              => 'spco-copy-attendee-chk ee-do-not-validate',
495 494
 						'display_html_label_text' => false
496 495
 					)
@@ -510,7 +509,7 @@  discard block
 block discarded – undo
510 509
 	 * @return    EE_Form_Input_Base
511 510
 	 * @throws \EE_Error
512 511
 	 */
513
-	private function _additional_primary_registrant_inputs( EE_Registration $registration ){
512
+	private function _additional_primary_registrant_inputs(EE_Registration $registration) {
514 513
 		// generate hidden input
515 514
 		return new EE_Hidden_Input(
516 515
 			array(
@@ -529,7 +528,7 @@  discard block
 block discarded – undo
529 528
 	 * @return    EE_Form_Input_Base
530 529
 	 * @throws \EE_Error
531 530
 	 */
532
-	public function reg_form_question( EE_Registration $registration, EE_Question $question ){
531
+	public function reg_form_question(EE_Registration $registration, EE_Question $question) {
533 532
 
534 533
 		// if this question was for an attendee detail, then check for that answer
535 534
 		$answer_value = EEM_Answer::instance()->get_attendee_property_answer_value(
@@ -538,32 +537,32 @@  discard block
 block discarded – undo
538 537
 		);
539 538
 		$answer = $answer_value === null
540 539
 			? EEM_Answer::instance()->get_one(
541
-				array( array( 'QST_ID' => $question->ID(), 'REG_ID' => $registration->ID() ) )
540
+				array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
542 541
 			)
543 542
 			: null;
544 543
 		// if NOT returning to edit an existing registration
545 544
 		// OR if this question is for an attendee property
546 545
 		// OR we still don't have an EE_Answer object
547
-		if( $answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link() ) {
546
+		if ($answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link()) {
548 547
 			// create an EE_Answer object for storing everything in
549
-			$answer = EE_Answer::new_instance ( array(
548
+			$answer = EE_Answer::new_instance(array(
550 549
 				'QST_ID'=> $question->ID(),
551 550
 				'REG_ID'=> $registration->ID()
552 551
 			));
553 552
 		}
554 553
 		// verify instance
555
-		if( $answer instanceof EE_Answer ){
556
-			if ( ! empty( $answer_value )) {
557
-				$answer->set( 'ANS_value', $answer_value );
554
+		if ($answer instanceof EE_Answer) {
555
+			if ( ! empty($answer_value)) {
556
+				$answer->set('ANS_value', $answer_value);
558 557
 			}
559
-			$answer->cache( 'Question', $question );
558
+			$answer->cache('Question', $question);
560 559
 			//remember system ID had a bug where sometimes it could be null
561
-			$answer_cache_id =$question->is_system_question()
562
-				? $question->system_ID() . '-' . $registration->reg_url_link()
563
-				: $question->ID() . '-' . $registration->reg_url_link();
564
-			$registration->cache( 'Answer', $answer, $answer_cache_id );
560
+			$answer_cache_id = $question->is_system_question()
561
+				? $question->system_ID().'-'.$registration->reg_url_link()
562
+				: $question->ID().'-'.$registration->reg_url_link();
563
+			$registration->cache('Answer', $answer, $answer_cache_id);
565 564
 		}
566
-		return $this->_generate_question_input( $registration, $question, $answer );
565
+		return $this->_generate_question_input($registration, $question, $answer);
567 566
 
568 567
 	}
569 568
 
@@ -576,46 +575,46 @@  discard block
 block discarded – undo
576 575
 	 * @return EE_Form_Input_Base
577 576
 	 * @throws \EE_Error
578 577
 	 */
579
-	private function _generate_question_input( EE_Registration $registration, EE_Question $question, $answer ){
578
+	private function _generate_question_input(EE_Registration $registration, EE_Question $question, $answer) {
580 579
 		$identifier = $question->is_system_question() ? $question->system_ID() : $question->ID();
581
-		$this->_required_questions[ $identifier ] = $question->required() ? true : false;
580
+		$this->_required_questions[$identifier] = $question->required() ? true : false;
582 581
 		add_filter(
583 582
 			'FHEE__EE_Question__generate_form_input__country_options',
584
-			array( $this, 'use_cached_countries_for_form_input' ),
583
+			array($this, 'use_cached_countries_for_form_input'),
585 584
 			10,
586 585
 			4
587 586
 		);
588 587
 		add_filter(
589 588
 			'FHEE__EE_Question__generate_form_input__state_options',
590
-			array( $this, 'use_cached_states_for_form_input' ),
589
+			array($this, 'use_cached_states_for_form_input'),
591 590
 			10,
592 591
 			4
593 592
 		);
594 593
 		$input_constructor_args = array(
595
-			'html_name'     => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
596
-			'html_id'       => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
597
-			'html_class'    => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
598
-			'html_label_id' => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
594
+			'html_name'     => 'ee_reg_qstn['.$registration->ID().']['.$identifier.']',
595
+			'html_id'       => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
596
+			'html_class'    => 'ee-reg-qstn ee-reg-qstn-'.$identifier,
597
+			'html_label_id' => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
599 598
 			'html_label_class'	=> 'ee-reg-qstn',
600 599
 		);
601
-		$input_constructor_args['html_label_id'] 	.= '-lbl';
602
-		if ( $answer instanceof EE_Answer && $answer->ID() ) {
603
-			$input_constructor_args[ 'html_name' ] .= '[' . $answer->ID() . ']';
604
-			$input_constructor_args[ 'html_id' ] .= '-' . $answer->ID();
605
-			$input_constructor_args[ 'html_label_id' ] .= '-' . $answer->ID();
600
+		$input_constructor_args['html_label_id'] .= '-lbl';
601
+		if ($answer instanceof EE_Answer && $answer->ID()) {
602
+			$input_constructor_args['html_name'] .= '['.$answer->ID().']';
603
+			$input_constructor_args['html_id'] .= '-'.$answer->ID();
604
+			$input_constructor_args['html_label_id'] .= '-'.$answer->ID();
606 605
 		}
607
-		$form_input =  $question->generate_form_input(
606
+		$form_input = $question->generate_form_input(
608 607
 			$registration,
609 608
 			$answer,
610 609
 			$input_constructor_args
611 610
 		);
612 611
 		remove_filter(
613 612
 			'FHEE__EE_Question__generate_form_input__country_options',
614
-			array( $this, 'use_cached_countries_for_form_input' )
613
+			array($this, 'use_cached_countries_for_form_input')
615 614
 		);
616 615
 		remove_filter(
617 616
 			'FHEE__EE_Question__generate_form_input__state_options',
618
-			array( $this, 'use_cached_states_for_form_input' )
617
+			array($this, 'use_cached_states_for_form_input')
619 618
 		);
620 619
 		return $form_input;
621 620
 	}
@@ -637,22 +636,22 @@  discard block
 block discarded – undo
637 636
 		\EE_Registration $registration = null,
638 637
 		\EE_Answer $answer = null
639 638
 	) {
640
-		$country_options = array( '' => '' );
639
+		$country_options = array('' => '');
641 640
 		// get possibly cached list of countries
642 641
 		$countries = $this->checkout->action === 'process_reg_step'
643 642
 			? EEM_Country::instance()->get_all_countries()
644 643
 			: EEM_Country::instance()->get_all_active_countries();
645
-		if ( ! empty( $countries )) {
646
-			foreach( $countries as $country ){
647
-				if ( $country instanceof EE_Country ) {
648
-					$country_options[ $country->ID() ] = $country->name();
644
+		if ( ! empty($countries)) {
645
+			foreach ($countries as $country) {
646
+				if ($country instanceof EE_Country) {
647
+					$country_options[$country->ID()] = $country->name();
649 648
 				}
650 649
 			}
651 650
 		}
652
-		if( $question instanceof EE_Question
653
-			&& $registration instanceof EE_Registration ) {
651
+		if ($question instanceof EE_Question
652
+			&& $registration instanceof EE_Registration) {
654 653
 			$answer = EEM_Answer::instance()->get_one(
655
-				array( array( 'QST_ID' => $question->ID(), 'REG_ID' => $registration->ID() ) )
654
+				array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
656 655
 			);
657 656
 		} else {
658 657
 			$answer = EE_Answer::new_instance();
@@ -685,14 +684,14 @@  discard block
 block discarded – undo
685 684
 		\EE_Registration $registration = null,
686 685
 		\EE_Answer $answer = null
687 686
 	) {
688
-		$state_options = array( '' => array( '' => ''));
687
+		$state_options = array('' => array('' => ''));
689 688
 		$states = $this->checkout->action === 'process_reg_step'
690 689
 			? EEM_State::instance()->get_all_states()
691 690
 			: EEM_State::instance()->get_all_active_states();
692
-		if ( ! empty( $states )) {
693
-			foreach( $states as $state ){
694
-				if ( $state instanceof EE_State ) {
695
-					$state_options[ $state->country()->name() ][ $state->ID() ] = $state->name();
691
+		if ( ! empty($states)) {
692
+			foreach ($states as $state) {
693
+				if ($state instanceof EE_State) {
694
+					$state_options[$state->country()->name()][$state->ID()] = $state->name();
696 695
 				}
697 696
 			}
698 697
 		}
@@ -720,24 +719,24 @@  discard block
 block discarded – undo
720 719
 	 * @throws \EE_Error
721 720
 	 */
722 721
 	public function process_reg_step() {
723
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
722
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
724 723
 		// grab validated data from form
725 724
 		$valid_data = $this->checkout->current_step->valid_data();
726 725
 		// EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
727 726
 		// EEH_Debug_Tools::printr( $valid_data, '$valid_data', __FILE__, __LINE__ );
728 727
 		// if we don't have any $valid_data then something went TERRIBLY WRONG !!!
729
-		if ( empty( $valid_data ))  {
728
+		if (empty($valid_data)) {
730 729
 			EE_Error::add_error(
731
-				__( 'No valid question responses were received.', 'event_espresso' ),
730
+				__('No valid question responses were received.', 'event_espresso'),
732 731
 				__FILE__,
733 732
 				__FUNCTION__,
734 733
 				__LINE__
735 734
 			);
736 735
 			return false;
737 736
 		}
738
-		if ( ! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg ) {
737
+		if ( ! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg) {
739 738
 			EE_Error::add_error(
740
-				__( 'A valid transaction could not be initiated for processing your registrations.', 'event_espresso' ),
739
+				__('A valid transaction could not be initiated for processing your registrations.', 'event_espresso'),
741 740
 				__FILE__,
742 741
 				__FUNCTION__,
743 742
 				__LINE__
@@ -745,11 +744,11 @@  discard block
 block discarded – undo
745 744
 			return false;
746 745
 		}
747 746
 		// get cached registrations
748
-		$registrations = $this->checkout->transaction->registrations( $this->checkout->reg_cache_where_params );
747
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
749 748
 		// verify we got the goods
750
-		if ( empty( $registrations )) {
749
+		if (empty($registrations)) {
751 750
 			EE_Error::add_error(
752
-				__( 'Your form data could not be applied to any valid registrations.', 'event_espresso' ),
751
+				__('Your form data could not be applied to any valid registrations.', 'event_espresso'),
753 752
 				__FILE__,
754 753
 				__FUNCTION__,
755 754
 				__LINE__
@@ -757,15 +756,15 @@  discard block
 block discarded – undo
757 756
 			return false;
758 757
 		}
759 758
 		// extract attendee info from form data and save to model objects
760
-		$registrations_processed = $this->_process_registrations( $registrations, $valid_data );
759
+		$registrations_processed = $this->_process_registrations($registrations, $valid_data);
761 760
 		// if first pass thru SPCO,
762 761
 		// then let's check processed registrations against the total number of tickets in the cart
763
-		if ( $registrations_processed === false ) {
762
+		if ($registrations_processed === false) {
764 763
 			// but return immediately if the previous step exited early due to errors
765 764
 			return false;
766
-		} else if ( ! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count ) {
765
+		} else if ( ! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count) {
767 766
 			// generate a correctly translated string for all possible singular/plural combinations
768
-			if ( $this->checkout->total_ticket_count === 1 && $registrations_processed !== 1 ) {
767
+			if ($this->checkout->total_ticket_count === 1 && $registrations_processed !== 1) {
769 768
 				$error_msg = sprintf(
770 769
 					__(
771 770
 						'There was %1$d ticket in the Event Queue, but %2$ds registrations were processed',
@@ -774,7 +773,7 @@  discard block
 block discarded – undo
774 773
 					$this->checkout->total_ticket_count,
775 774
 					$registrations_processed
776 775
 				);
777
-			} else if ( $this->checkout->total_ticket_count !== 1 && $registrations_processed === 1 ) {
776
+			} else if ($this->checkout->total_ticket_count !== 1 && $registrations_processed === 1) {
778 777
 				$error_msg = sprintf(
779 778
 					__(
780 779
 						'There was a total of %1$d tickets in the Event Queue, but only %2$ds registration was processed',
@@ -793,17 +792,17 @@  discard block
 block discarded – undo
793 792
 					$registrations_processed
794 793
 				);
795 794
 			}
796
-			EE_Error::add_error( $error_msg, __FILE__, __FUNCTION__, __LINE__ );
795
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
797 796
 			return false;
798 797
 		}
799 798
 		// mark this reg step as completed
800 799
 		$this->set_completed();
801 800
 		$this->_set_success_message(
802
-			__( 'The Attendee Information Step has been successfully completed.', 'event_espresso' )
801
+			__('The Attendee Information Step has been successfully completed.', 'event_espresso')
803 802
 		);
804 803
 		//do action in case a plugin wants to do something with the data submitted in step 1.
805 804
 		//passes EE_Single_Page_Checkout, and it's posted data
806
-		do_action( 'AHEE__EE_Single_Page_Checkout__process_attendee_information__end', $this, $valid_data );
805
+		do_action('AHEE__EE_Single_Page_Checkout__process_attendee_information__end', $this, $valid_data);
807 806
 		return true;
808 807
 	}
809 808
 
@@ -817,9 +816,9 @@  discard block
 block discarded – undo
817 816
 	 * @return boolean | int
818 817
 	 * @throws \EE_Error
819 818
 	 */
820
-	private function _process_registrations( $registrations = array(), $valid_data = array() ) {
819
+	private function _process_registrations($registrations = array(), $valid_data = array()) {
821 820
 		// load resources and set some defaults
822
-		EE_Registry::instance()->load_model( 'Attendee' );
821
+		EE_Registry::instance()->load_model('Attendee');
823 822
 		// holder for primary registrant attendee object
824 823
 		$this->checkout->primary_attendee_obj = NULL;
825 824
 		// array for tracking reg form data for the primary registrant
@@ -836,9 +835,9 @@  discard block
 block discarded – undo
836 835
 		// attendee counter
837 836
 		$att_nmbr = 0;
838 837
 		// grab the saved registrations from the transaction
839
-		foreach ( $registrations  as $registration ) {
838
+		foreach ($registrations  as $registration) {
840 839
 			// verify EE_Registration object
841
-			if ( ! $registration instanceof EE_Registration ) {
840
+			if ( ! $registration instanceof EE_Registration) {
842 841
 				EE_Error::add_error(
843 842
 					__(
844 843
 						'An invalid Registration object was discovered when attempting to process your registration information.',
@@ -853,12 +852,12 @@  discard block
 block discarded – undo
853 852
 			/** @var string $reg_url_link */
854 853
 			$reg_url_link = $registration->reg_url_link();
855 854
 			// reg_url_link exists ?
856
-			if ( ! empty( $reg_url_link ) ) {
855
+			if ( ! empty($reg_url_link)) {
857 856
 				// should this registration be processed during this visit ?
858
-				if ( $this->checkout->visit_allows_processing_of_this_registration( $registration ) ) {
857
+				if ($this->checkout->visit_allows_processing_of_this_registration($registration)) {
859 858
 					// if NOT revisiting, then let's save the registration now,
860 859
 					// so that we have a REG_ID to use when generating other objects
861
-					if ( ! $this->checkout->revisit ) {
860
+					if ( ! $this->checkout->revisit) {
862 861
 						$registration->save();
863 862
 					}
864 863
 					/**
@@ -868,7 +867,7 @@  discard block
 block discarded – undo
868 867
 					 * @var bool   if true is returned by the plugin then the
869 868
 					 *      		registration processing is halted.
870 869
 					 */
871
-					if ( apply_filters(
870
+					if (apply_filters(
872 871
 						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___process_registrations__pre_registration_process',
873 872
 						false,
874 873
 						$att_nmbr,
@@ -876,38 +875,38 @@  discard block
 block discarded – undo
876 875
 						$registrations,
877 876
 						$valid_data,
878 877
 						$this
879
-					) ) {
878
+					)) {
880 879
 						return false;
881 880
 					}
882 881
 
883 882
 					// Houston, we have a registration!
884 883
 					$att_nmbr++;
885
-					$this->_attendee_data[ $reg_url_link ] = array();
884
+					$this->_attendee_data[$reg_url_link] = array();
886 885
 					// grab any existing related answer objects
887 886
 					$this->_registration_answers = $registration->answers();
888 887
 					// unset( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] );
889
-					if ( isset( $valid_data[ $reg_url_link ] ) ) {
888
+					if (isset($valid_data[$reg_url_link])) {
890 889
 						// do we need to copy basic info from primary attendee ?
891
-						$copy_primary = isset( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] )
892
-						                && absint( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] ) === 0
890
+						$copy_primary = isset($valid_data[$reg_url_link]['additional_attendee_reg_info'])
891
+						                && absint($valid_data[$reg_url_link]['additional_attendee_reg_info']) === 0
893 892
 							? true
894 893
 							: false;
895 894
 						// filter form input data for this registration
896
-						$valid_data[ $reg_url_link ] = (array)apply_filters(
895
+						$valid_data[$reg_url_link] = (array) apply_filters(
897 896
 							'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
898
-							$valid_data[ $reg_url_link ]
897
+							$valid_data[$reg_url_link]
899 898
 						);
900 899
 						// EEH_Debug_Tools::printr( $valid_data[ $reg_url_link ], '$valid_data[ $reg_url_link ]', __FILE__, __LINE__ );
901
-						if ( isset( $valid_data['primary_attendee'] )) {
902
-							$primary_registrant['line_item_id'] =  ! empty( $valid_data['primary_attendee'] )
900
+						if (isset($valid_data['primary_attendee'])) {
901
+							$primary_registrant['line_item_id'] = ! empty($valid_data['primary_attendee'])
903 902
 								? $valid_data['primary_attendee']
904 903
 								: false;
905
-							unset( $valid_data['primary_attendee'] );
904
+							unset($valid_data['primary_attendee']);
906 905
 						}
907 906
 						// now loop through our array of valid post data && process attendee reg forms
908
-						foreach ( $valid_data[ $reg_url_link ] as $form_section => $form_inputs ) {
909
-							if ( ! in_array( $form_section, $non_input_form_sections )) {
910
-								foreach ( $form_inputs as $form_input => $input_value ) {
907
+						foreach ($valid_data[$reg_url_link] as $form_section => $form_inputs) {
908
+							if ( ! in_array($form_section, $non_input_form_sections)) {
909
+								foreach ($form_inputs as $form_input => $input_value) {
911 910
 									// \EEH_Debug_Tools::printr( $input_value, $form_input, __FILE__, __LINE__ );
912 911
 									// check for critical inputs
913 912
 									if (
@@ -921,16 +920,16 @@  discard block
 block discarded – undo
921 920
 									// store a bit of data about the primary attendee
922 921
 									if (
923 922
 										$att_nmbr === 1
924
-										&& ! empty( $input_value )
923
+										&& ! empty($input_value)
925 924
 										&& $reg_url_link === $primary_registrant['line_item_id']
926 925
 									) {
927
-										$primary_registrant[ $form_input ] = $input_value;
926
+										$primary_registrant[$form_input] = $input_value;
928 927
 									} else if (
929 928
 										$copy_primary
930 929
 										&& $input_value === null
931
-										&& isset( $primary_registrant[ $form_input ] )
930
+										&& isset($primary_registrant[$form_input])
932 931
 									) {
933
-										$input_value = $primary_registrant[ $form_input ];
932
+										$input_value = $primary_registrant[$form_input];
934 933
 									}
935 934
 									// now attempt to save the input data
936 935
 									if (
@@ -972,55 +971,55 @@  discard block
 block discarded – undo
972 971
 						// have we met before?
973 972
 						$attendee = $this->_find_existing_attendee(
974 973
 							$registration,
975
-							$this->_attendee_data[ $reg_url_link ]
974
+							$this->_attendee_data[$reg_url_link]
976 975
 						);
977 976
 						// did we find an already existing record for this attendee ?
978
-						if ( $attendee instanceof EE_Attendee ) {
977
+						if ($attendee instanceof EE_Attendee) {
979 978
 							$attendee = $this->_update_existing_attendee_data(
980 979
 								$attendee,
981
-								$this->_attendee_data[ $reg_url_link ]
980
+								$this->_attendee_data[$reg_url_link]
982 981
 							);
983 982
 						} else {
984 983
 							// ensure critical details are set for additional attendees
985
-							$this->_attendee_data[ $reg_url_link ] = $att_nmbr > 1
984
+							$this->_attendee_data[$reg_url_link] = $att_nmbr > 1
986 985
 								? $this->_copy_critical_attendee_details_from_primary_registrant(
987
-									$this->_attendee_data[ $reg_url_link ]
986
+									$this->_attendee_data[$reg_url_link]
988 987
 								)
989
-								: $this->_attendee_data[ $reg_url_link ];
988
+								: $this->_attendee_data[$reg_url_link];
990 989
 							$attendee = $this->_create_new_attendee(
991 990
 								$registration,
992
-								$this->_attendee_data[ $reg_url_link ]
991
+								$this->_attendee_data[$reg_url_link]
993 992
 							);
994 993
 						}
995 994
 						// who's #1 ?
996
-						if ( $att_nmbr === 1 ) {
995
+						if ($att_nmbr === 1) {
997 996
 							$this->checkout->primary_attendee_obj = $attendee;
998 997
 						}
999 998
 					}
1000 999
 					// EEH_Debug_Tools::printr( $attendee, '$attendee', __FILE__, __LINE__ );
1001 1000
 					// add relation to registration, set attendee ID, and cache attendee
1002
-					$this->_associate_attendee_with_registration( $registration, $attendee );
1001
+					$this->_associate_attendee_with_registration($registration, $attendee);
1003 1002
 					// \EEH_Debug_Tools::printr( $registration, '$registration', __FILE__, __LINE__ );
1004
-					if ( ! $registration->attendee() instanceof EE_Attendee ) {
1005
-						EE_Error::add_error( sprintf( __( 'Registration %s has an invalid or missing Attendee object.', 'event_espresso' ), $reg_url_link ), __FILE__, __FUNCTION__, __LINE__ );
1003
+					if ( ! $registration->attendee() instanceof EE_Attendee) {
1004
+						EE_Error::add_error(sprintf(__('Registration %s has an invalid or missing Attendee object.', 'event_espresso'), $reg_url_link), __FILE__, __FUNCTION__, __LINE__);
1006 1005
 						return false;
1007 1006
 					}
1008 1007
 					/** @type EE_Registration_Processor $registration_processor */
1009
-					$registration_processor = EE_Registry::instance()->load_class( 'Registration_Processor' );
1008
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1010 1009
 					// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
1011
-					$registration_processor->toggle_incomplete_registration_status_to_default( $registration, false );
1010
+					$registration_processor->toggle_incomplete_registration_status_to_default($registration, false);
1012 1011
 					// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1013 1012
 					$this->checkout->transaction->toggle_failed_transaction_status();
1014 1013
 					// if we've gotten this far, then let's save what we have
1015 1014
 					$registration->save();
1016 1015
 					// add relation between TXN and registration
1017
-					$this->_associate_registration_with_transaction( $registration );
1016
+					$this->_associate_registration_with_transaction($registration);
1018 1017
 				} // end of if ( ! $this->checkout->revisit || $this->checkout->primary_revisit || ( $this->checkout->revisit && $this->checkout->reg_url_link == $reg_url_link )) {
1019 1018
 
1020
-			}  else {
1021
-				EE_Error::add_error( __( 'An invalid or missing line item ID was encountered while attempting to process the registration form.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
1019
+			} else {
1020
+				EE_Error::add_error(__('An invalid or missing line item ID was encountered while attempting to process the registration form.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1022 1021
 				// remove malformed data
1023
-				unset( $valid_data[ $reg_url_link ] );
1022
+				unset($valid_data[$reg_url_link]);
1024 1023
 				return false;
1025 1024
 			}
1026 1025
 
@@ -1049,26 +1048,26 @@  discard block
 block discarded – undo
1049 1048
 		// \EEH_Debug_Tools::printr( $input_value, '$input_value', __FILE__, __LINE__ );
1050 1049
 		// allow for plugins to hook in and do their own processing of the form input.
1051 1050
 		// For plugins to bypass normal processing here, they just need to return a boolean value.
1052
-		if ( apply_filters(
1051
+		if (apply_filters(
1053 1052
 			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___save_registration_form_input',
1054 1053
 			false,
1055 1054
 			$registration,
1056 1055
 			$form_input,
1057 1056
 			$input_value,
1058 1057
 			$this
1059
-		) ) {
1058
+		)) {
1060 1059
 			return true;
1061 1060
 		}
1062 1061
 		// $answer_cache_id is the key used to find the EE_Answer we want
1063 1062
 		$answer_cache_id = $this->checkout->reg_url_link
1064 1063
 			? $form_input
1065
-			: $form_input . '-' . $registration->reg_url_link();
1066
-		$answer_is_obj = isset( $this->_registration_answers[ $answer_cache_id ] )
1067
-		                 && $this->_registration_answers[ $answer_cache_id ] instanceof EE_Answer
1064
+			: $form_input.'-'.$registration->reg_url_link();
1065
+		$answer_is_obj = isset($this->_registration_answers[$answer_cache_id])
1066
+		                 && $this->_registration_answers[$answer_cache_id] instanceof EE_Answer
1068 1067
 			? true
1069 1068
 			: false;
1070 1069
 		//rename form_inputs if they are EE_Attendee properties
1071
-		switch( (string)$form_input ) {
1070
+		switch ((string) $form_input) {
1072 1071
 
1073 1072
 			case 'state' :
1074 1073
 			case 'STA_ID' :
@@ -1083,32 +1082,32 @@  discard block
 block discarded – undo
1083 1082
 				break;
1084 1083
 
1085 1084
 			default :
1086
-				$ATT_input = 'ATT_' . $form_input;
1085
+				$ATT_input = 'ATT_'.$form_input;
1087 1086
 				//EEH_Debug_Tools::printr( $ATT_input, '$ATT_input', __FILE__, __LINE__ );
1088
-				$attendee_property = EEM_Attendee::instance()->has_field( $ATT_input ) ? true : false;
1089
-				$form_input = $attendee_property ? 'ATT_' . $form_input : $form_input;
1087
+				$attendee_property = EEM_Attendee::instance()->has_field($ATT_input) ? true : false;
1088
+				$form_input = $attendee_property ? 'ATT_'.$form_input : $form_input;
1090 1089
 		}
1091 1090
 		// EEH_Debug_Tools::printr( $answer_cache_id, '$answer_cache_id', __FILE__, __LINE__ );
1092 1091
 		// EEH_Debug_Tools::printr( $attendee_property, '$attendee_property', __FILE__, __LINE__ );
1093 1092
 		// EEH_Debug_Tools::printr( $answer_is_obj, '$answer_is_obj', __FILE__, __LINE__ );
1094 1093
 		// if this form input has a corresponding attendee property
1095
-		if ( $attendee_property ) {
1096
-			$this->_attendee_data[ $registration->reg_url_link() ][ $form_input ] = $input_value;
1097
-			if ( $answer_is_obj ) {
1094
+		if ($attendee_property) {
1095
+			$this->_attendee_data[$registration->reg_url_link()][$form_input] = $input_value;
1096
+			if ($answer_is_obj) {
1098 1097
 				// and delete the corresponding answer since we won't be storing this data in that object
1099
-				$registration->_remove_relation_to( $this->_registration_answers[ $answer_cache_id ], 'Answer' );
1100
-				$this->_registration_answers[ $answer_cache_id ]->delete_permanently();
1098
+				$registration->_remove_relation_to($this->_registration_answers[$answer_cache_id], 'Answer');
1099
+				$this->_registration_answers[$answer_cache_id]->delete_permanently();
1101 1100
 			}
1102 1101
 			return true;
1103
-		} elseif ( $answer_is_obj ) {
1102
+		} elseif ($answer_is_obj) {
1104 1103
 			// save this data to the answer object
1105
-			$this->_registration_answers[ $answer_cache_id ]->set_value( $input_value );
1106
-			$result = $this->_registration_answers[ $answer_cache_id ]->save();
1104
+			$this->_registration_answers[$answer_cache_id]->set_value($input_value);
1105
+			$result = $this->_registration_answers[$answer_cache_id]->save();
1107 1106
 			return $result !== false ? true : false;
1108 1107
 		} else {
1109
-			foreach ( $this->_registration_answers as $answer ) {
1110
-				if ( $answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id ) {
1111
-					$answer->set_value( $input_value );
1108
+			foreach ($this->_registration_answers as $answer) {
1109
+				if ($answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id) {
1110
+					$answer->set_value($input_value);
1112 1111
 					$result = $answer->save();
1113 1112
 					return $result !== false ? true : false;
1114 1113
 				}
@@ -1130,15 +1129,15 @@  discard block
 block discarded – undo
1130 1129
 		$form_input = '',
1131 1130
 		$input_value = ''
1132 1131
 	) {
1133
-		if ( empty( $input_value ) ) {
1132
+		if (empty($input_value)) {
1134 1133
 			// if the form input isn't marked as being required, then just return
1135
-			if ( ! isset( $this->_required_questions[ $form_input ] ) || ! $this->_required_questions[ $form_input ] ) {
1134
+			if ( ! isset($this->_required_questions[$form_input]) || ! $this->_required_questions[$form_input]) {
1136 1135
 				return true;
1137 1136
 			}
1138
-			switch ( $form_input ) {
1137
+			switch ($form_input) {
1139 1138
 				case 'fname' :
1140 1139
 					EE_Error::add_error(
1141
-						__( 'First Name is a required value.', 'event_espresso' ),
1140
+						__('First Name is a required value.', 'event_espresso'),
1142 1141
 						__FILE__,
1143 1142
 						__FUNCTION__,
1144 1143
 						__LINE__
@@ -1147,7 +1146,7 @@  discard block
 block discarded – undo
1147 1146
 					break;
1148 1147
 				case 'lname' :
1149 1148
 					EE_Error::add_error(
1150
-						__( 'Last Name is a required value.', 'event_espresso' ),
1149
+						__('Last Name is a required value.', 'event_espresso'),
1151 1150
 						__FILE__,
1152 1151
 						__FUNCTION__,
1153 1152
 						__LINE__
@@ -1156,7 +1155,7 @@  discard block
 block discarded – undo
1156 1155
 					break;
1157 1156
 				case 'email' :
1158 1157
 					EE_Error::add_error(
1159
-						__( 'Please enter a valid email address.', 'event_espresso' ),
1158
+						__('Please enter a valid email address.', 'event_espresso'),
1160 1159
 						__FILE__,
1161 1160
 						__FUNCTION__,
1162 1161
 						__LINE__
@@ -1178,30 +1177,30 @@  discard block
 block discarded – undo
1178 1177
 	 * @return boolean|EE_Attendee
1179 1178
 	 * @throws \EE_Error
1180 1179
 	 */
1181
-	private function _find_existing_attendee( EE_Registration $registration, $attendee_data = array() ) {
1180
+	private function _find_existing_attendee(EE_Registration $registration, $attendee_data = array()) {
1182 1181
 		$existing_attendee = null;
1183 1182
 		// if none of the critical properties are set in the incoming attendee data...
1184 1183
 		// then attempt to copy them from the primary attendee
1185 1184
 		if (
1186 1185
 			$this->checkout->primary_attendee_obj instanceof EE_Attendee
1187
-            && ! isset( $attendee_data['ATT_fname'], $attendee_data['ATT_email'] )
1186
+            && ! isset($attendee_data['ATT_fname'], $attendee_data['ATT_email'])
1188 1187
 		) {
1189 1188
 			return $this->checkout->primary_attendee_obj;
1190 1189
 		}
1191 1190
 		// does this attendee already exist in the db ?
1192 1191
 		// we're searching using a combination of first name, last name, AND email address
1193
-		$ATT_fname = isset( $attendee_data['ATT_fname'] ) && ! empty( $attendee_data['ATT_fname'] )
1192
+		$ATT_fname = isset($attendee_data['ATT_fname']) && ! empty($attendee_data['ATT_fname'])
1194 1193
 			? $attendee_data['ATT_fname']
1195 1194
 			: '';
1196
-		$ATT_lname = isset( $attendee_data['ATT_lname'] ) && ! empty( $attendee_data['ATT_lname'] )
1195
+		$ATT_lname = isset($attendee_data['ATT_lname']) && ! empty($attendee_data['ATT_lname'])
1197 1196
 			? $attendee_data['ATT_lname']
1198 1197
 			: '';
1199
-		$ATT_email = isset( $attendee_data['ATT_email'] ) && ! empty( $attendee_data['ATT_email'] )
1198
+		$ATT_email = isset($attendee_data['ATT_email']) && ! empty($attendee_data['ATT_email'])
1200 1199
 			? $attendee_data['ATT_email']
1201 1200
 			: '';
1202 1201
 		// but only if those have values
1203
-		if ( $ATT_fname && $ATT_lname && $ATT_email ) {
1204
-			$existing_attendee = EEM_Attendee::instance()->find_existing_attendee( array(
1202
+		if ($ATT_fname && $ATT_lname && $ATT_email) {
1203
+			$existing_attendee = EEM_Attendee::instance()->find_existing_attendee(array(
1205 1204
 				'ATT_fname' => $ATT_fname,
1206 1205
 				'ATT_lname' => $ATT_lname,
1207 1206
 				'ATT_email' => $ATT_email
@@ -1225,13 +1224,13 @@  discard block
 block discarded – undo
1225 1224
 	 * @return \EE_Attendee
1226 1225
 	 * @throws \EE_Error
1227 1226
 	 */
1228
-	private function _update_existing_attendee_data( EE_Attendee $existing_attendee, $attendee_data = array() ) {
1227
+	private function _update_existing_attendee_data(EE_Attendee $existing_attendee, $attendee_data = array()) {
1229 1228
 		// first remove fname, lname, and email from attendee data
1230
-		$dont_set = array( 'ATT_fname', 'ATT_lname', 'ATT_email' );
1229
+		$dont_set = array('ATT_fname', 'ATT_lname', 'ATT_email');
1231 1230
 		// now loop thru what's left and add to attendee CPT
1232
-		foreach ( $attendee_data as $property_name => $property_value ) {
1233
-			if ( ! in_array( $property_name, $dont_set ) && EEM_Attendee::instance()->has_field( $property_name )) {
1234
-				$existing_attendee->set( $property_name, $property_value );
1231
+		foreach ($attendee_data as $property_name => $property_value) {
1232
+			if ( ! in_array($property_name, $dont_set) && EEM_Attendee::instance()->has_field($property_name)) {
1233
+				$existing_attendee->set($property_name, $property_value);
1235 1234
 			}
1236 1235
 		}
1237 1236
 		// better save that now
@@ -1249,11 +1248,11 @@  discard block
 block discarded – undo
1249 1248
 	 * @return void
1250 1249
 	 * @throws \EE_Error
1251 1250
 	 */
1252
-	private function _associate_attendee_with_registration( EE_Registration $registration, EE_Attendee $attendee ) {
1251
+	private function _associate_attendee_with_registration(EE_Registration $registration, EE_Attendee $attendee) {
1253 1252
 		// add relation to attendee
1254
-		$registration->_add_relation_to( $attendee, 'Attendee' );
1255
-		$registration->set_attendee_id( $attendee->ID() );
1256
-		$registration->update_cache_after_object_save( 'Attendee', $attendee );
1253
+		$registration->_add_relation_to($attendee, 'Attendee');
1254
+		$registration->set_attendee_id($attendee->ID());
1255
+		$registration->update_cache_after_object_save('Attendee', $attendee);
1257 1256
 	}
1258 1257
 
1259 1258
 
@@ -1265,10 +1264,10 @@  discard block
 block discarded – undo
1265 1264
 	 * @return void
1266 1265
 	 * @throws \EE_Error
1267 1266
 	 */
1268
-	private function _associate_registration_with_transaction( EE_Registration $registration ) {
1267
+	private function _associate_registration_with_transaction(EE_Registration $registration) {
1269 1268
 		// add relation to attendee
1270
-		$this->checkout->transaction->_add_relation_to( $registration, 'Registration' );
1271
-		$this->checkout->transaction->update_cache_after_object_save( 'Registration', $registration );
1269
+		$this->checkout->transaction->_add_relation_to($registration, 'Registration');
1270
+		$this->checkout->transaction->update_cache_after_object_save('Registration', $registration);
1272 1271
 	}
1273 1272
 
1274 1273
 
@@ -1281,14 +1280,14 @@  discard block
 block discarded – undo
1281 1280
 	 * @return array
1282 1281
 	 * @throws \EE_Error
1283 1282
 	 */
1284
-	private function _copy_critical_attendee_details_from_primary_registrant( $attendee_data = array() ) {
1283
+	private function _copy_critical_attendee_details_from_primary_registrant($attendee_data = array()) {
1285 1284
 		// bare minimum critical details include first name, last name, email address
1286
-		$critical_attendee_details = array( 'ATT_fname', 'ATT_lname', 'ATT_email' );
1285
+		$critical_attendee_details = array('ATT_fname', 'ATT_lname', 'ATT_email');
1287 1286
 		// add address info to critical details?
1288
-		if ( apply_filters(
1287
+		if (apply_filters(
1289 1288
 			'FHEE__EE_SPCO_Reg_Step_Attendee_Information__merge_address_details_with_critical_attendee_details',
1290 1289
 			false
1291
-		) ) {
1290
+		)) {
1292 1291
 			$address_details = array(
1293 1292
 				'ATT_address',
1294 1293
 				'ATT_address2',
@@ -1298,13 +1297,13 @@  discard block
 block discarded – undo
1298 1297
 				'ATT_zip',
1299 1298
 				'ATT_phone'
1300 1299
 			);
1301
-			$critical_attendee_details = array_merge( $critical_attendee_details, $address_details );
1300
+			$critical_attendee_details = array_merge($critical_attendee_details, $address_details);
1302 1301
 		}
1303
-		foreach ( $critical_attendee_details as $critical_attendee_detail ) {
1304
-			if ( ! isset( $attendee_data[ $critical_attendee_detail ] )
1305
-			     || empty( $attendee_data[ $critical_attendee_detail ] )
1302
+		foreach ($critical_attendee_details as $critical_attendee_detail) {
1303
+			if ( ! isset($attendee_data[$critical_attendee_detail])
1304
+			     || empty($attendee_data[$critical_attendee_detail])
1306 1305
 			) {
1307
-				$attendee_data[ $critical_attendee_detail ] = $this->checkout->primary_attendee_obj->get(
1306
+				$attendee_data[$critical_attendee_detail] = $this->checkout->primary_attendee_obj->get(
1308 1307
 					$critical_attendee_detail
1309 1308
 				);
1310 1309
 			}
@@ -1322,11 +1321,11 @@  discard block
 block discarded – undo
1322 1321
 	 * @return \EE_Attendee
1323 1322
 	 * @throws \EE_Error
1324 1323
 	 */
1325
-	private function _create_new_attendee( EE_Registration $registration, $attendee_data = array() ) {
1324
+	private function _create_new_attendee(EE_Registration $registration, $attendee_data = array()) {
1326 1325
 		// create new attendee object
1327
-		$new_attendee = EE_Attendee::new_instance( $attendee_data );
1326
+		$new_attendee = EE_Attendee::new_instance($attendee_data);
1328 1327
 		// set author to event creator
1329
-		$new_attendee->set( 'ATT_author', $registration->event()->wp_user() );
1328
+		$new_attendee->set('ATT_author', $registration->event()->wp_user());
1330 1329
 		$new_attendee->save();
1331 1330
 		return $new_attendee;
1332 1331
 	}
@@ -1343,7 +1342,7 @@  discard block
 block discarded – undo
1343 1342
 	 */
1344 1343
 	public function update_reg_step() {
1345 1344
 		// save everything
1346
-		if ( $this->process_reg_step() ) {
1345
+		if ($this->process_reg_step()) {
1347 1346
 			$this->checkout->redirect = true;
1348 1347
 			$this->checkout->redirect_url = add_query_arg(
1349 1348
 				array(
@@ -1352,7 +1351,7 @@  discard block
 block discarded – undo
1352 1351
 				),
1353 1352
 				$this->checkout->thank_you_page_url
1354 1353
 			);
1355
-			$this->checkout->json_response->set_redirect_url( $this->checkout->redirect_url );
1354
+			$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1356 1355
 			return true;
1357 1356
 		}
1358 1357
 		return false;
Please login to merge, or discard this patch.
modules/ticket_selector/EED_Ticket_Selector.module.php 2 patches
Indentation   +1207 added lines, -1207 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,1218 +14,1218 @@  discard block
 block discarded – undo
14 14
 class EED_Ticket_Selector extends EED_Module
15 15
 {
16 16
 
17
-    const debug = false;    //	true false
18
-
19
-    /**
20
-     * event that ticket selector is being generated for
21
-     *
22
-     * @access protected
23
-     * @var \EE_Event
24
-     */
25
-    protected static $_event;
26
-
27
-    /**
28
-     * array of datetimes and the spaces available for them
29
-     *
30
-     * @access private
31
-     * @var array
32
-     */
33
-    private static $_available_spaces = array();
34
-
35
-    /**
36
-     * max attendees that can register for event at one time
37
-     *
38
-     * @access private
39
-     * @var int
40
-     */
41
-    private static $_max_atndz = EE_INF;
42
-
43
-
44
-
45
-    /**
46
-     * Used to flag when the ticket selector is being called from an external iframe.
47
-     *
48
-     * @var bool
49
-     */
50
-    protected static $_in_iframe = false;
51
-
52
-
53
-
54
-    /**
55
-     * @return EED_Ticket_Selector
56
-     */
57
-    public static function instance()
58
-    {
59
-        return parent::get_instance(__CLASS__);
60
-    }
61
-
62
-
63
-
64
-    protected function set_config()
65
-    {
66
-        $this->set_config_section('template_settings');
67
-        $this->set_config_class('EE_Ticket_Selector_Config');
68
-        $this->set_config_name('EED_Ticket_Selector');
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     *    set_hooks - for hooking into EE Core, other modules, etc
75
-     *
76
-     * @access    public
77
-     * @return    void
78
-     */
79
-    public static function set_hooks()
80
-    {
81
-        // routing
82
-        EE_Config::register_route('iframe', 'EED_Ticket_Selector', 'ticket_selector_iframe', 'ticket_selector');
83
-        EE_Config::register_route('process_ticket_selections', 'EED_Ticket_Selector', 'process_ticket_selections');
84
-        EE_Config::register_route('cancel_ticket_selections', 'EED_Ticket_Selector', 'cancel_ticket_selections');
85
-        add_action('wp_loaded', array('EED_Ticket_Selector', 'set_definitions'), 2);
86
-        add_action('AHEE_event_details_header_bottom', array('EED_Ticket_Selector', 'display_ticket_selector'), 10, 1);
87
-        add_action('wp_enqueue_scripts', array('EED_Ticket_Selector', 'load_tckt_slctr_assets'), 10);
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
94
-     *
95
-     * @access    public
96
-     * @return    void
97
-     */
98
-    public static function set_hooks_admin()
99
-    {
100
-        add_action('wp_loaded', array('EED_Ticket_Selector', 'set_definitions'), 2);
101
-        //add button for iframe code to event editor.
102
-        add_filter('get_sample_permalink_html', array('EED_Ticket_Selector', 'iframe_code_button'), 10, 2);
103
-        add_action('admin_enqueue_scripts', array('EED_Ticket_Selector', 'load_tckt_slctr_assets_admin'), 10);
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     *    set_definitions
110
-     *
111
-     * @access    public
112
-     * @return    void
113
-     */
114
-    public static function set_definitions()
115
-    {
116
-        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
117
-        define('TICKET_SELECTOR_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)) . 'templates' . DS);
118
-        //if config is not set, initialize
119
-        //If config is not set, set it.
120
-        if (EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector === null) {
121
-            EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector = new EE_Ticket_Selector_Config();
122
-        }
123
-        EE_Registry::$i18n_js_strings['ts_embed_iframe_title'] = __('Copy and Paste the following:', 'event_espresso');
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     *    gets the ball rolling
130
-     *
131
-     * @access public
132
-     * @param    WP $WP
133
-     * @return void
134
-     */
135
-    public function run($WP)
136
-    {
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * ticket_selector_iframe
143
-     *
144
-     * @access    public
145
-     * @return    void
146
-     * @throws \EE_Error
147
-     */
148
-    public function ticket_selector_iframe()
149
-    {
150
-        self::$_in_iframe = true;
151
-        /** @type EEM_Event $EEM_Event */
152
-        $EEM_Event = EE_Registry::instance()->load_model('Event');
153
-        $event = $EEM_Event->get_one_by_ID(
154
-            EE_Registry::instance()->REQ->get('event', 0)
155
-        );
156
-        EE_Registry::instance()->REQ->set_espresso_page(true);
157
-        $template_args['ticket_selector'] = EED_Ticket_Selector::display_ticket_selector($event);
158
-        $template_args['css'] = apply_filters(
159
-            'FHEE__EED_Ticket_Selector__ticket_selector_iframe__css',
160
-            array(
161
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_embed.css?ver=' . EVENT_ESPRESSO_VERSION,
162
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css?ver=' . EVENT_ESPRESSO_VERSION,
163
-                includes_url('css/dashicons.min.css?ver=' . $GLOBALS['wp_version']),
164
-                EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
165
-            )
166
-        );
167
-        EE_Registry::$i18n_js_strings['ticket_selector_iframe'] = true;
168
-        EE_Registry::$i18n_js_strings['EEDTicketSelectorMsg'] = esc_html__('Please choose at least one ticket before continuing.',
169
-            'event_espresso');
170
-        $template_args['eei18n'] = apply_filters(
171
-            'FHEE__EED_Ticket_Selector__ticket_selector_iframe__eei18n_js_strings',
172
-            EE_Registry::localize_i18n_js_strings()
173
-        );
174
-        $template_args['js'] = apply_filters(
175
-            'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js',
176
-            array(
177
-                includes_url('js/jquery/jquery.js?ver=' . $GLOBALS['wp_version']),
178
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . EVENT_ESPRESSO_VERSION,
179
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_iframe_embed.js?ver=' . EVENT_ESPRESSO_VERSION,
180
-            )
181
-        );
182
-        $template_args['notices'] = EEH_Template::display_template(
183
-            EE_TEMPLATES . 'espresso-ajax-notices.template.php',
184
-            array(),
185
-            true
186
-        );
187
-        EEH_Template::display_template(
188
-            TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart_iframe.template.php',
189
-            $template_args
190
-        );
191
-        exit;
192
-    }
193
-
194
-
195
-
196
-    /**
197
-     * Adds an iframe embed code button to the Event editor.
198
-     *
199
-     * @param string $permalink_string The current html string for the permalink section.
200
-     * @param int    $id               The post id for the event.
201
-     * @return string The new html string for the permalink area.
202
-     */
203
-    public static function iframe_code_button($permalink_string, $id )
204
-    {
205
-        //make sure this is ONLY when editing and the event id has been set.
206
-        if ( ! empty($id)) {
207
-            $post = get_post($id);
208
-            //if NOT event then let's get out.
209
-            if ($post->post_type !== 'espresso_events') {
210
-                return $permalink_string;
211
-            }
212
-            $permalink_string .= '<a id="js-ticket-selector-embed-trigger" class="button button-small" href="#"  tabindex="-1">'
213
-                                 . __('Embed', 'event_espresso')
214
-                                 . '</a> ';
215
-            $ticket_selector_url = add_query_arg(array('ticket_selector' => 'iframe', 'event' => $id), site_url());
216
-            $iframe_string = esc_html(
217
-                '<iframe src="' . $ticket_selector_url . '" width="100%" height="100%"></iframe>'
218
-            );
219
-            $permalink_string .= '
17
+	const debug = false;    //	true false
18
+
19
+	/**
20
+	 * event that ticket selector is being generated for
21
+	 *
22
+	 * @access protected
23
+	 * @var \EE_Event
24
+	 */
25
+	protected static $_event;
26
+
27
+	/**
28
+	 * array of datetimes and the spaces available for them
29
+	 *
30
+	 * @access private
31
+	 * @var array
32
+	 */
33
+	private static $_available_spaces = array();
34
+
35
+	/**
36
+	 * max attendees that can register for event at one time
37
+	 *
38
+	 * @access private
39
+	 * @var int
40
+	 */
41
+	private static $_max_atndz = EE_INF;
42
+
43
+
44
+
45
+	/**
46
+	 * Used to flag when the ticket selector is being called from an external iframe.
47
+	 *
48
+	 * @var bool
49
+	 */
50
+	protected static $_in_iframe = false;
51
+
52
+
53
+
54
+	/**
55
+	 * @return EED_Ticket_Selector
56
+	 */
57
+	public static function instance()
58
+	{
59
+		return parent::get_instance(__CLASS__);
60
+	}
61
+
62
+
63
+
64
+	protected function set_config()
65
+	{
66
+		$this->set_config_section('template_settings');
67
+		$this->set_config_class('EE_Ticket_Selector_Config');
68
+		$this->set_config_name('EED_Ticket_Selector');
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 *    set_hooks - for hooking into EE Core, other modules, etc
75
+	 *
76
+	 * @access    public
77
+	 * @return    void
78
+	 */
79
+	public static function set_hooks()
80
+	{
81
+		// routing
82
+		EE_Config::register_route('iframe', 'EED_Ticket_Selector', 'ticket_selector_iframe', 'ticket_selector');
83
+		EE_Config::register_route('process_ticket_selections', 'EED_Ticket_Selector', 'process_ticket_selections');
84
+		EE_Config::register_route('cancel_ticket_selections', 'EED_Ticket_Selector', 'cancel_ticket_selections');
85
+		add_action('wp_loaded', array('EED_Ticket_Selector', 'set_definitions'), 2);
86
+		add_action('AHEE_event_details_header_bottom', array('EED_Ticket_Selector', 'display_ticket_selector'), 10, 1);
87
+		add_action('wp_enqueue_scripts', array('EED_Ticket_Selector', 'load_tckt_slctr_assets'), 10);
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
94
+	 *
95
+	 * @access    public
96
+	 * @return    void
97
+	 */
98
+	public static function set_hooks_admin()
99
+	{
100
+		add_action('wp_loaded', array('EED_Ticket_Selector', 'set_definitions'), 2);
101
+		//add button for iframe code to event editor.
102
+		add_filter('get_sample_permalink_html', array('EED_Ticket_Selector', 'iframe_code_button'), 10, 2);
103
+		add_action('admin_enqueue_scripts', array('EED_Ticket_Selector', 'load_tckt_slctr_assets_admin'), 10);
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 *    set_definitions
110
+	 *
111
+	 * @access    public
112
+	 * @return    void
113
+	 */
114
+	public static function set_definitions()
115
+	{
116
+		define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
117
+		define('TICKET_SELECTOR_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)) . 'templates' . DS);
118
+		//if config is not set, initialize
119
+		//If config is not set, set it.
120
+		if (EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector === null) {
121
+			EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector = new EE_Ticket_Selector_Config();
122
+		}
123
+		EE_Registry::$i18n_js_strings['ts_embed_iframe_title'] = __('Copy and Paste the following:', 'event_espresso');
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 *    gets the ball rolling
130
+	 *
131
+	 * @access public
132
+	 * @param    WP $WP
133
+	 * @return void
134
+	 */
135
+	public function run($WP)
136
+	{
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * ticket_selector_iframe
143
+	 *
144
+	 * @access    public
145
+	 * @return    void
146
+	 * @throws \EE_Error
147
+	 */
148
+	public function ticket_selector_iframe()
149
+	{
150
+		self::$_in_iframe = true;
151
+		/** @type EEM_Event $EEM_Event */
152
+		$EEM_Event = EE_Registry::instance()->load_model('Event');
153
+		$event = $EEM_Event->get_one_by_ID(
154
+			EE_Registry::instance()->REQ->get('event', 0)
155
+		);
156
+		EE_Registry::instance()->REQ->set_espresso_page(true);
157
+		$template_args['ticket_selector'] = EED_Ticket_Selector::display_ticket_selector($event);
158
+		$template_args['css'] = apply_filters(
159
+			'FHEE__EED_Ticket_Selector__ticket_selector_iframe__css',
160
+			array(
161
+				TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_embed.css?ver=' . EVENT_ESPRESSO_VERSION,
162
+				TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css?ver=' . EVENT_ESPRESSO_VERSION,
163
+				includes_url('css/dashicons.min.css?ver=' . $GLOBALS['wp_version']),
164
+				EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
165
+			)
166
+		);
167
+		EE_Registry::$i18n_js_strings['ticket_selector_iframe'] = true;
168
+		EE_Registry::$i18n_js_strings['EEDTicketSelectorMsg'] = esc_html__('Please choose at least one ticket before continuing.',
169
+			'event_espresso');
170
+		$template_args['eei18n'] = apply_filters(
171
+			'FHEE__EED_Ticket_Selector__ticket_selector_iframe__eei18n_js_strings',
172
+			EE_Registry::localize_i18n_js_strings()
173
+		);
174
+		$template_args['js'] = apply_filters(
175
+			'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js',
176
+			array(
177
+				includes_url('js/jquery/jquery.js?ver=' . $GLOBALS['wp_version']),
178
+				EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . EVENT_ESPRESSO_VERSION,
179
+				TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_iframe_embed.js?ver=' . EVENT_ESPRESSO_VERSION,
180
+			)
181
+		);
182
+		$template_args['notices'] = EEH_Template::display_template(
183
+			EE_TEMPLATES . 'espresso-ajax-notices.template.php',
184
+			array(),
185
+			true
186
+		);
187
+		EEH_Template::display_template(
188
+			TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart_iframe.template.php',
189
+			$template_args
190
+		);
191
+		exit;
192
+	}
193
+
194
+
195
+
196
+	/**
197
+	 * Adds an iframe embed code button to the Event editor.
198
+	 *
199
+	 * @param string $permalink_string The current html string for the permalink section.
200
+	 * @param int    $id               The post id for the event.
201
+	 * @return string The new html string for the permalink area.
202
+	 */
203
+	public static function iframe_code_button($permalink_string, $id )
204
+	{
205
+		//make sure this is ONLY when editing and the event id has been set.
206
+		if ( ! empty($id)) {
207
+			$post = get_post($id);
208
+			//if NOT event then let's get out.
209
+			if ($post->post_type !== 'espresso_events') {
210
+				return $permalink_string;
211
+			}
212
+			$permalink_string .= '<a id="js-ticket-selector-embed-trigger" class="button button-small" href="#"  tabindex="-1">'
213
+								 . __('Embed', 'event_espresso')
214
+								 . '</a> ';
215
+			$ticket_selector_url = add_query_arg(array('ticket_selector' => 'iframe', 'event' => $id), site_url());
216
+			$iframe_string = esc_html(
217
+				'<iframe src="' . $ticket_selector_url . '" width="100%" height="100%"></iframe>'
218
+			);
219
+			$permalink_string .= '
220 220
 <div id="js-ts-iframe" style="display:none">
221 221
 	<div style="width:100%; height: 500px;">
222 222
 		' . $iframe_string . '
223 223
 	</div>
224 224
 </div>';
225
-        }
226
-        return $permalink_string;
227
-    }
228
-
229
-
230
-
231
-    /**
232
-     *    finds and sets the EE_Event object for use throughout class
233
-     *
234
-     * @access    public
235
-     * @param    mixed $event
236
-     * @return    bool
237
-     */
238
-    protected static function set_event($event = null)
239
-    {
240
-        if ($event === null) {
241
-            global $post;
242
-            $event = $post;
243
-        }
244
-        if ($event instanceof EE_Event) {
245
-            self::$_event = $event;
246
-        } else if ($event instanceof WP_Post ) {
247
-            if ( isset($event->EE_Event) && $event->EE_Event instanceof EE_Event) {
248
-                self::$_event = $event->EE_Event;
249
-            } else if ( $event->post_type === 'espresso_events') {
250
-                $event->EE_Event = EEM_Event::instance()->instantiate_class_from_post_object($event);
251
-                self::$_event = $event->EE_Event;
252
-            }
253
-        } else {
254
-            $user_msg = __('No Event object or an invalid Event object was supplied.', 'event_espresso');
255
-            $dev_msg = $user_msg
256
-                       . __('In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
257
-                    'event_espresso');
258
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
259
-            return false;
260
-        }
261
-        return true;
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * creates buttons for selecting number of attendees for an event
268
-     *
269
-     * @access public
270
-     * @param EE_Event $event
271
-     * @param bool     $view_details
272
-     * @return string
273
-     * @throws \EE_Error
274
-     */
275
-    public static function display_ticket_selector($event = null, $view_details = false)
276
-    {
277
-        // reset filter for displaying submit button
278
-        remove_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
279
-        // poke and prod incoming event till it tells us what it is
280
-        if ( ! EED_Ticket_Selector::set_event($event)) {
281
-            return false;
282
-        }
283
-        $event_post = self::$_event instanceof EE_Event ? self::$_event->ID() : $event;
284
-        // grab event status
285
-        $_event_active_status = self::$_event->get_active_status();
286
-        if (
287
-            ! is_admin()
288
-            && (
289
-                ! self::$_event->display_ticket_selector()
290
-                || $view_details
291
-                || post_password_required($event_post)
292
-                || (
293
-                    $_event_active_status !== EE_Datetime::active
294
-                    && $_event_active_status !== EE_Datetime::upcoming
295
-                    && $_event_active_status !== EE_Datetime::sold_out
296
-                    && ! (
297
-                        $_event_active_status === EE_Datetime::inactive
298
-                        && is_user_logged_in()
299
-                    )
300
-                )
301
-            )
302
-        ) {
303
-            return ! is_single() ? EED_Ticket_Selector::display_view_details_btn() : '';
304
-        }
305
-        $template_args = array();
306
-        $template_args['event_status'] = $_event_active_status;
307
-        $template_args['date_format'] = apply_filters('FHEE__EED_Ticket_Selector__display_ticket_selector__date_format',
308
-            get_option('date_format'));
309
-        $template_args['time_format'] = apply_filters('FHEE__EED_Ticket_Selector__display_ticket_selector__time_format',
310
-            get_option('time_format'));
311
-        $template_args['EVT_ID'] = self::$_event->ID();
312
-        $template_args['event'] = self::$_event;
313
-        // is the event expired ?
314
-        $template_args['event_is_expired'] = self::$_event->is_expired();
315
-        if ($template_args['event_is_expired']) {
316
-            return '<div class="ee-event-expired-notice"><span class="important-notice">'
317
-                   . __('We\'re sorry, but all tickets sales have ended because the event is expired.',
318
-                'event_espresso')
319
-                   . '</span></div>';
320
-        }
321
-        $ticket_query_args = array(
322
-            array('Datetime.EVT_ID' => self::$_event->ID()),
323
-            'order_by' => array(
324
-                'TKT_order'              => 'ASC',
325
-                'TKT_required'           => 'DESC',
326
-                'TKT_start_date'         => 'ASC',
327
-                'TKT_end_date'           => 'ASC',
328
-                'Datetime.DTT_EVT_start' => 'DESC',
329
-            ),
330
-        );
331
-        if ( ! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector->show_expired_tickets) {
332
-            //use the correct applicable time query depending on what version of core is being run.
333
-            $current_time = method_exists('EEM_Datetime', 'current_time_for_query') ? time()
334
-                : current_time('timestamp');
335
-            $ticket_query_args[0]['TKT_end_date'] = array('>', $current_time);
336
-        }
337
-        // get all tickets for this event ordered by the datetime
338
-        $template_args['tickets'] = EEM_Ticket::instance()->get_all($ticket_query_args);
339
-        if (count($template_args['tickets']) < 1) {
340
-            return '<div class="ee-event-expired-notice"><span class="important-notice">'
341
-                   . __('We\'re sorry, but all ticket sales have ended.', 'event_espresso')
342
-                   . '</span></div>';
343
-        }
344
-        // filter the maximum qty that can appear in the Ticket Selector qty dropdowns
345
-        \EED_Ticket_Selector::$_max_atndz = apply_filters(
346
-            'FHEE__EE_Ticket_Selector__display_ticket_selector__max_tickets',
347
-            self::$_event->additional_limit()
348
-        );
349
-        $template_args['max_atndz'] = \EED_Ticket_Selector::$_max_atndz;
350
-        if ($template_args['max_atndz'] < 1) {
351
-            $sales_closed_msg = __('We\'re sorry, but ticket sales have been closed at this time. Please check back again later.',
352
-                'event_espresso');
353
-            if (current_user_can('edit_post', self::$_event->ID())) {
354
-                $sales_closed_msg .= sprintf(
355
-                    __('%sNote to Event Admin:%sThe "Maximum number of tickets allowed per order for this event" in the Event Registration Options has been set to "0". This effectively turns off ticket sales. %s(click to edit this event)%s',
356
-                        'event_espresso'),
357
-                    '<div class="ee-attention" style="text-align: left;"><b>',
358
-                    '</b><br />',
359
-                    $link = '<span class="edit-link"><a class="post-edit-link" href="'
360
-                            . get_edit_post_link(self::$_event->ID())
361
-                            . '">',
362
-                    '</a></span></div>'
363
-                );
364
-            }
365
-            return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
366
-        }
367
-        $templates['ticket_selector'] = TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart.template.php';
368
-        $templates['ticket_selector'] = apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
369
-            $templates['ticket_selector'], self::$_event);
370
-        // redirecting to another site for registration ??
371
-        $external_url = self::$_event->external_url() !== null || self::$_event->external_url() !== ''
372
-            ? self::$_event->external_url() : false;
373
-        // if not redirecting to another site for registration
374
-        if ( ! $external_url) {
375
-            // then display the ticket selector
376
-            $ticket_selector = EEH_Template::locate_template($templates['ticket_selector'], $template_args);
377
-        } else {
378
-            // if not we still need to trigger the display of the submit button
379
-            add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
380
-            //display notice to admin that registration is external
381
-            $ticket_selector = ! is_admin() ? ''
382
-                : __('Registration is at an external URL for this event.', 'event_espresso');
383
-        }
384
-        // now set up the form (but not for the admin)
385
-        $ticket_selector = ! is_admin()
386
-            ? EED_Ticket_Selector::ticket_selector_form_open(
387
-                self::$_event->ID(),
388
-                $external_url
389
-            ) . $ticket_selector
390
-            : $ticket_selector;
391
-        // submit button and form close tag
392
-        $ticket_selector .= ! is_admin() ? EED_Ticket_Selector::display_ticket_selector_submit($external_url) : '';
393
-        // set no cache headers and constants
394
-        EE_System::do_not_cache();
395
-        return $ticket_selector;
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     *    ticket_selector_form_open
402
-     *
403
-     * @access        public
404
-     * @param        int    $ID
405
-     * @param        string $external_url
406
-     * @return        string
407
-     */
408
-    public static function ticket_selector_form_open($ID = 0, $external_url = '')
409
-    {
410
-        // if redirecting, we don't need any anything else
411
-        if ($external_url) {
412
-            $html = '<form method="GET" action="' . EEH_URL::refactor_url($external_url) . '"';
413
-            // open link in new window ?
414
-            $html .= apply_filters(
415
-                'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
416
-                false
417
-            )
418
-                ? ' target="_blank"'
419
-                : '';
420
-            $html .= '>';
421
-            $query_args = (array)EEH_URL::get_query_string($external_url);
422
-            foreach ($query_args as $query_arg => $value) {
423
-                $html .= '
225
+		}
226
+		return $permalink_string;
227
+	}
228
+
229
+
230
+
231
+	/**
232
+	 *    finds and sets the EE_Event object for use throughout class
233
+	 *
234
+	 * @access    public
235
+	 * @param    mixed $event
236
+	 * @return    bool
237
+	 */
238
+	protected static function set_event($event = null)
239
+	{
240
+		if ($event === null) {
241
+			global $post;
242
+			$event = $post;
243
+		}
244
+		if ($event instanceof EE_Event) {
245
+			self::$_event = $event;
246
+		} else if ($event instanceof WP_Post ) {
247
+			if ( isset($event->EE_Event) && $event->EE_Event instanceof EE_Event) {
248
+				self::$_event = $event->EE_Event;
249
+			} else if ( $event->post_type === 'espresso_events') {
250
+				$event->EE_Event = EEM_Event::instance()->instantiate_class_from_post_object($event);
251
+				self::$_event = $event->EE_Event;
252
+			}
253
+		} else {
254
+			$user_msg = __('No Event object or an invalid Event object was supplied.', 'event_espresso');
255
+			$dev_msg = $user_msg
256
+					   . __('In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
257
+					'event_espresso');
258
+			EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
259
+			return false;
260
+		}
261
+		return true;
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * creates buttons for selecting number of attendees for an event
268
+	 *
269
+	 * @access public
270
+	 * @param EE_Event $event
271
+	 * @param bool     $view_details
272
+	 * @return string
273
+	 * @throws \EE_Error
274
+	 */
275
+	public static function display_ticket_selector($event = null, $view_details = false)
276
+	{
277
+		// reset filter for displaying submit button
278
+		remove_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
279
+		// poke and prod incoming event till it tells us what it is
280
+		if ( ! EED_Ticket_Selector::set_event($event)) {
281
+			return false;
282
+		}
283
+		$event_post = self::$_event instanceof EE_Event ? self::$_event->ID() : $event;
284
+		// grab event status
285
+		$_event_active_status = self::$_event->get_active_status();
286
+		if (
287
+			! is_admin()
288
+			&& (
289
+				! self::$_event->display_ticket_selector()
290
+				|| $view_details
291
+				|| post_password_required($event_post)
292
+				|| (
293
+					$_event_active_status !== EE_Datetime::active
294
+					&& $_event_active_status !== EE_Datetime::upcoming
295
+					&& $_event_active_status !== EE_Datetime::sold_out
296
+					&& ! (
297
+						$_event_active_status === EE_Datetime::inactive
298
+						&& is_user_logged_in()
299
+					)
300
+				)
301
+			)
302
+		) {
303
+			return ! is_single() ? EED_Ticket_Selector::display_view_details_btn() : '';
304
+		}
305
+		$template_args = array();
306
+		$template_args['event_status'] = $_event_active_status;
307
+		$template_args['date_format'] = apply_filters('FHEE__EED_Ticket_Selector__display_ticket_selector__date_format',
308
+			get_option('date_format'));
309
+		$template_args['time_format'] = apply_filters('FHEE__EED_Ticket_Selector__display_ticket_selector__time_format',
310
+			get_option('time_format'));
311
+		$template_args['EVT_ID'] = self::$_event->ID();
312
+		$template_args['event'] = self::$_event;
313
+		// is the event expired ?
314
+		$template_args['event_is_expired'] = self::$_event->is_expired();
315
+		if ($template_args['event_is_expired']) {
316
+			return '<div class="ee-event-expired-notice"><span class="important-notice">'
317
+				   . __('We\'re sorry, but all tickets sales have ended because the event is expired.',
318
+				'event_espresso')
319
+				   . '</span></div>';
320
+		}
321
+		$ticket_query_args = array(
322
+			array('Datetime.EVT_ID' => self::$_event->ID()),
323
+			'order_by' => array(
324
+				'TKT_order'              => 'ASC',
325
+				'TKT_required'           => 'DESC',
326
+				'TKT_start_date'         => 'ASC',
327
+				'TKT_end_date'           => 'ASC',
328
+				'Datetime.DTT_EVT_start' => 'DESC',
329
+			),
330
+		);
331
+		if ( ! EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector->show_expired_tickets) {
332
+			//use the correct applicable time query depending on what version of core is being run.
333
+			$current_time = method_exists('EEM_Datetime', 'current_time_for_query') ? time()
334
+				: current_time('timestamp');
335
+			$ticket_query_args[0]['TKT_end_date'] = array('>', $current_time);
336
+		}
337
+		// get all tickets for this event ordered by the datetime
338
+		$template_args['tickets'] = EEM_Ticket::instance()->get_all($ticket_query_args);
339
+		if (count($template_args['tickets']) < 1) {
340
+			return '<div class="ee-event-expired-notice"><span class="important-notice">'
341
+				   . __('We\'re sorry, but all ticket sales have ended.', 'event_espresso')
342
+				   . '</span></div>';
343
+		}
344
+		// filter the maximum qty that can appear in the Ticket Selector qty dropdowns
345
+		\EED_Ticket_Selector::$_max_atndz = apply_filters(
346
+			'FHEE__EE_Ticket_Selector__display_ticket_selector__max_tickets',
347
+			self::$_event->additional_limit()
348
+		);
349
+		$template_args['max_atndz'] = \EED_Ticket_Selector::$_max_atndz;
350
+		if ($template_args['max_atndz'] < 1) {
351
+			$sales_closed_msg = __('We\'re sorry, but ticket sales have been closed at this time. Please check back again later.',
352
+				'event_espresso');
353
+			if (current_user_can('edit_post', self::$_event->ID())) {
354
+				$sales_closed_msg .= sprintf(
355
+					__('%sNote to Event Admin:%sThe "Maximum number of tickets allowed per order for this event" in the Event Registration Options has been set to "0". This effectively turns off ticket sales. %s(click to edit this event)%s',
356
+						'event_espresso'),
357
+					'<div class="ee-attention" style="text-align: left;"><b>',
358
+					'</b><br />',
359
+					$link = '<span class="edit-link"><a class="post-edit-link" href="'
360
+							. get_edit_post_link(self::$_event->ID())
361
+							. '">',
362
+					'</a></span></div>'
363
+				);
364
+			}
365
+			return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
366
+		}
367
+		$templates['ticket_selector'] = TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart.template.php';
368
+		$templates['ticket_selector'] = apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
369
+			$templates['ticket_selector'], self::$_event);
370
+		// redirecting to another site for registration ??
371
+		$external_url = self::$_event->external_url() !== null || self::$_event->external_url() !== ''
372
+			? self::$_event->external_url() : false;
373
+		// if not redirecting to another site for registration
374
+		if ( ! $external_url) {
375
+			// then display the ticket selector
376
+			$ticket_selector = EEH_Template::locate_template($templates['ticket_selector'], $template_args);
377
+		} else {
378
+			// if not we still need to trigger the display of the submit button
379
+			add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
380
+			//display notice to admin that registration is external
381
+			$ticket_selector = ! is_admin() ? ''
382
+				: __('Registration is at an external URL for this event.', 'event_espresso');
383
+		}
384
+		// now set up the form (but not for the admin)
385
+		$ticket_selector = ! is_admin()
386
+			? EED_Ticket_Selector::ticket_selector_form_open(
387
+				self::$_event->ID(),
388
+				$external_url
389
+			) . $ticket_selector
390
+			: $ticket_selector;
391
+		// submit button and form close tag
392
+		$ticket_selector .= ! is_admin() ? EED_Ticket_Selector::display_ticket_selector_submit($external_url) : '';
393
+		// set no cache headers and constants
394
+		EE_System::do_not_cache();
395
+		return $ticket_selector;
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 *    ticket_selector_form_open
402
+	 *
403
+	 * @access        public
404
+	 * @param        int    $ID
405
+	 * @param        string $external_url
406
+	 * @return        string
407
+	 */
408
+	public static function ticket_selector_form_open($ID = 0, $external_url = '')
409
+	{
410
+		// if redirecting, we don't need any anything else
411
+		if ($external_url) {
412
+			$html = '<form method="GET" action="' . EEH_URL::refactor_url($external_url) . '"';
413
+			// open link in new window ?
414
+			$html .= apply_filters(
415
+				'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
416
+				false
417
+			)
418
+				? ' target="_blank"'
419
+				: '';
420
+			$html .= '>';
421
+			$query_args = (array)EEH_URL::get_query_string($external_url);
422
+			foreach ($query_args as $query_arg => $value) {
423
+				$html .= '
424 424
 				<input type="hidden" name="' . $query_arg . '" value="' . $value . '">';
425
-            }
426
-            return $html;
427
-        }
428
-        // if there is no submit button, then don't start building a form
429
-        // because the "View Details" button will build its own form
430
-        if ( ! apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
431
-            return '';
432
-        }
433
-        $checkout_url = EEH_Event_View::event_link_url($ID);
434
-        if ( ! $checkout_url) {
435
-            EE_Error::add_error(__('The URL for the Event Details page could not be retrieved.', 'event_espresso'),
436
-                __FILE__, __FUNCTION__, __LINE__);
437
-        }
438
-        $extra_params = self::$_in_iframe ? ' target="_blank"' : '';
439
-        $html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
440
-        $html .= wp_nonce_field('process_ticket_selections', 'process_ticket_selections_nonce_' . $ID, true, false);
441
-        $html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
442
-        $html = apply_filters('FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, self::$_event);
443
-        return $html;
444
-    }
445
-
446
-
447
-
448
-    /**
449
-     * display_ticket_selector_submit
450
-     *
451
-     * @param        string $external_url
452
-     * @return        string
453
-     * @throws \EE_Error
454
-     */
455
-    public static function display_ticket_selector_submit($external_url = '')
456
-    {
457
-        $html = '';
458
-        if ( ! is_admin()) {
459
-            // standard TS displayed with submit button, ie: "Register Now"
460
-            if (apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
461
-                $html .= \EED_Ticket_Selector::display_register_now_button();
462
-                $html .= empty($external_url) ?
463
-                    \EED_Ticket_Selector::no_tkt_slctr_end_dv()
464
-                    : \EED_Ticket_Selector::clear_tkt_slctr();
465
-                $html .= '<br/>' . \EED_Ticket_Selector::ticket_selector_form_close();
466
-            } else if ( EED_Ticket_Selector::$_max_atndz === 1 ) {
467
-                // its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
468
-                if ( EED_Ticket_Selector::$_event->is_sold_out() ) {
469
-                    // then instead of a View Details or Submit button, just display a "Sold Out" message
470
-                    $html .= apply_filters(
471
-                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
472
-                        sprintf(
473
-                            __(
474
-                                '%1$s"%2$s" is currently sold out.%4$sPlease check back again later, as spots may become available.%3$s',
475
-                                'event_espresso'
476
-                            ),
477
-                            '<p class="no-ticket-selector-msg clear-float">',
478
-                            EED_Ticket_Selector::$_event->name(),
479
-                            '</p>',
480
-                            '<br />'
481
-                        ),
482
-                        EED_Ticket_Selector::$_event
483
-                    );
484
-                    if (
485
-                        apply_filters(
486
-                            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
487
-                            false,
488
-                            EED_Ticket_Selector::$_event
489
-                        )
490
-                    ) {
491
-                        $html .= \EED_Ticket_Selector::display_register_now_button();
492
-                    }
493
-                    // sold out DWMTS event, no TS, no submit or view details button, but has additional content
494
-                    $html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
495
-                } else if (
496
-                    apply_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector', false)
497
-                    && ! is_single()
498
-                ) {
499
-                    // this is a "Dude Where's my Ticket Selector?" (DWMTS) type event,
500
-                    // but no tickets are available, so display event's "View Details" button.
501
-                    // it is being viewed via somewhere other than a single post
502
-                    $html .= EED_Ticket_Selector::display_view_details_btn(true);
503
-                }
504
-            } else if (is_archive()) {
505
-                // event list, no tickets available so display event's "View Details" button
506
-                $html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
507
-                $html .= EED_Ticket_Selector::display_view_details_btn();
508
-            } else {
509
-                if (
510
-                    apply_filters(
511
-                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
512
-                        false,
513
-                        EED_Ticket_Selector::$_event
514
-                    )
515
-                ) {
516
-                    $html .= \EED_Ticket_Selector::display_register_now_button();
517
-                }
518
-                // no submit or view details button, and no additional content
519
-                $html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
520
-            }
521
-            if ( ! is_archive()) {
522
-                $html .= \EEH_Template::powered_by_event_espresso('', '', array('utm_content' => 'ticket_selector'));
523
-            }
524
-        }
525
-        return $html;
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     * @return string
532
-     */
533
-    public static function clear_tkt_slctr()
534
-    {
535
-        // standard TS displayed, appears after a "Register Now" or "view Details" button
536
-        return '<div class="clear"></div>';
537
-    }
538
-
539
-
540
-
541
-    /**
542
-     * @deprecated 4.9.13
543
-     * @return string
544
-     */
545
-    public static function tkt_slctr_end_dv()
546
-    {
547
-        return \EED_Ticket_Selector::clear_tkt_slctr();
548
-    }
549
-
550
-
551
-
552
-    /**
553
-     * @return string
554
-     */
555
-    public static function no_tkt_slctr_end_dv()
556
-    {
557
-        // DWMTS event, no TS, appears after a "Register Now" or "view Details" button
558
-        return '<div class="clear"></div></div>';
559
-    }
560
-
561
-
562
-
563
-    /**
564
-     *    ticket_selector_form_close
565
-     *
566
-     * @access        public
567
-     * @access        public
568
-     * @return        string
569
-     */
570
-    public static function ticket_selector_form_close()
571
-    {
572
-        return '</form>';
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * @return string
579
-     * @throws \EE_Error
580
-     */
581
-    public static function display_register_now_button()
582
-    {
583
-        $btn_text = apply_filters(
584
-            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__btn_text',
585
-            __('Register Now', 'event_espresso'),
586
-            EED_Ticket_Selector::$_event
587
-        );
588
-        $external_url = EED_Ticket_Selector::$_event->external_url();
589
-        $html = '<input id="ticket-selector-submit-' . EED_Ticket_Selector::$_event->ID() . '-btn"';
590
-        $html .= ' class="ticket-selector-submit-btn ';
591
-        $html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
592
-        $html .= ' type="submit" value="' . $btn_text . '" />';
593
-        $html .= apply_filters(
594
-            'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
595
-            '',
596
-            EED_Ticket_Selector::$_event
597
-        );
598
-        return $html;
599
-    }
600
-
601
-
602
-    /**
603
-     * display_view_details_btn
604
-     *
605
-     * @access public
606
-     * @param bool $DWMTS indicates a "Dude Where's my Ticket Selector?" (DWMTS) type event
607
-     *                    (ie: $_max_atndz === 1) where there are no available tickets,
608
-     *                    either because they are sold out, expired, or not yet on sale.
609
-     *                    In this case, we need to close the form BEFORE adding any closing divs
610
-     * @return string
611
-     * @throws \EE_Error
612
-     */
613
-    public static function display_view_details_btn($DWMTS = false)
614
-    {
615
-        if ( ! self::$_event->get_permalink()) {
616
-            EE_Error::add_error(
617
-                __('The URL for the Event Details page could not be retrieved.', 'event_espresso'),
618
-                __FILE__, __FUNCTION__, __LINE__
619
-            );
620
-        }
621
-        $view_details_btn = '<form method="POST" action="';
622
-        $view_details_btn .= apply_filters(
623
-            'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_url',
624
-            self::$_event->get_permalink(),
625
-            self::$_event
626
-        );
627
-        $view_details_btn .= '">';
628
-        $btn_text = apply_filters(
629
-            'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_text',
630
-            __('View Details', 'event_espresso'),
631
-            self::$_event
632
-        );
633
-        $view_details_btn .= '<input id="ticket-selector-submit-'
634
-                             . self::$_event->ID()
635
-                             . '-btn" class="ticket-selector-submit-btn view-details-btn" type="submit" value="'
636
-                             . $btn_text
637
-                             . '" />';
638
-        $view_details_btn .= apply_filters('FHEE__EE_Ticket_Selector__after_view_details_btn', '', self::$_event);
639
-        if ($DWMTS) {
640
-            $view_details_btn .= \EED_Ticket_Selector::ticket_selector_form_close();
641
-            $view_details_btn .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
642
-            $view_details_btn .= '<br/>';
643
-        } else {
644
-            $view_details_btn .= \EED_Ticket_Selector::clear_tkt_slctr();
645
-            $view_details_btn .= '<br/>';
646
-            $view_details_btn .= \EED_Ticket_Selector::ticket_selector_form_close();
647
-        }
648
-        return $view_details_btn;
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     *    cancel_ticket_selections
655
-     *
656
-     * @access        public
657
-     * @access        public
658
-     * @return        string
659
-     */
660
-    public static function cancel_ticket_selections()
661
-    {
662
-        // check nonce
663
-        if ( ! EED_Ticket_Selector::process_ticket_selector_nonce('cancel_ticket_selections')) {
664
-            return false;
665
-        }
666
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
667
-        if (EE_Registry::instance()->REQ->is_set('event_id')) {
668
-            wp_safe_redirect(
669
-                EEH_Event_View::event_link_url(
670
-                    EE_Registry::instance()->REQ->get('event_id')
671
-                )
672
-            );
673
-        } else {
674
-            wp_safe_redirect(
675
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
676
-            );
677
-        }
678
-        die();
679
-    }
680
-
681
-
682
-
683
-    /**
684
-     *    process_ticket_selector_nonce
685
-     *
686
-     * @access public
687
-     * @param  string $nonce_name
688
-     * @param string  $id
689
-     * @return bool
690
-     */
691
-    public static function process_ticket_selector_nonce($nonce_name, $id = '')
692
-    {
693
-        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
694
-        if (
695
-            ! is_admin()
696
-            && (
697
-                ! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
698
-                || ! wp_verify_nonce(
699
-                    EE_Registry::instance()->REQ->get($nonce_name_with_id),
700
-                    $nonce_name
701
-                )
702
-            )
703
-        ) {
704
-            EE_Error::add_error(
705
-                sprintf(
706
-                    __(
707
-                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
708
-                        'event_espresso'
709
-                    ),
710
-                    '<br/>'
711
-                ),
712
-                __FILE__,
713
-                __FUNCTION__,
714
-                __LINE__
715
-            );
716
-            return false;
717
-        }
718
-        return true;
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     *    process_ticket_selections
725
-     *
726
-     * @access public
727
-     * @return array|boolean
728
-     * @throws \EE_Error
729
-     */
730
-    public function process_ticket_selections()
731
-    {
732
-        do_action('EED_Ticket_Selector__process_ticket_selections__before');
733
-        // do we have an event id?
734
-        if ( ! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
735
-            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
736
-            EE_Error::add_error(
737
-                sprintf(
738
-                    __(
739
-                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
740
-                        'event_espresso'
741
-                    ),
742
-                    '<br/>'
743
-                ),
744
-                __FILE__,
745
-                __FUNCTION__,
746
-                __LINE__
747
-            );
748
-        }
749
-        //if event id is valid
750
-        $id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
751
-        // check nonce
752
-        if ( ! EED_Ticket_Selector::process_ticket_selector_nonce('process_ticket_selections', $id)) {
753
-            return false;
754
-        }
755
-        //		d( EE_Registry::instance()->REQ );
756
-        self::$_available_spaces = array(
757
-            'tickets'   => array(),
758
-            'datetimes' => array(),
759
-        );
760
-        //we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
761
-        // When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
762
-        EE_Registry::instance()->load_core('Session');
763
-        // unless otherwise requested, clear the session
764
-        if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
765
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
766
-        }
767
-        //d( EE_Registry::instance()->SSN );
768
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
769
-        // validate/sanitize data
770
-        $valid = self::_validate_post_data($id);
771
-        //EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
772
-        //EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
773
-        //EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
774
-        //EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
775
-        //check total tickets ordered vs max number of attendees that can register
776
-        if ($valid['total_tickets'] > $valid['max_atndz']) {
777
-            // ordering too many tickets !!!
778
-            $total_tickets_string = _n('You have attempted to purchase %s ticket.',
779
-                'You have attempted to purchase %s tickets.', $valid['total_tickets'], 'event_espresso');
780
-            $limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
781
-            // dev only message
782
-            $max_atndz_string = _n('The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
783
-                'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
784
-                $valid['max_atndz'], 'event_espresso');
785
-            $limit_error_2 = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
786
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
787
-        } else {
788
-            // all data appears to be valid
789
-            $tckts_slctd = false;
790
-            $tickets_added = 0;
791
-            $valid = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data', $valid);
792
-            if ($valid['total_tickets'] > 0) {
793
-                // load cart
794
-                EE_Registry::instance()->load_core('Cart');
795
-                // cycle thru the number of data rows sent from the event listing
796
-                for ($x = 0; $x < $valid['rows']; $x++) {
797
-                    // does this row actually contain a ticket quantity?
798
-                    if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
799
-                        // YES we have a ticket quantity
800
-                        $tckts_slctd = true;
801
-                        //						d( $valid['ticket_obj'][$x] );
802
-                        if ($valid['ticket_obj'][$x] instanceof EE_Ticket) {
803
-                            // then add ticket to cart
804
-                            $tickets_added += self::_add_ticket_to_cart($valid['ticket_obj'][$x], $valid['qty'][$x]);
805
-                            if (EE_Error::has_error()) {
806
-                                break;
807
-                            }
808
-                        } else {
809
-                            // nothing added to cart retrieved
810
-                            EE_Error::add_error(
811
-                                sprintf(__('A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
812
-                                    'event_espresso'), '<br/>'),
813
-                                __FILE__, __FUNCTION__, __LINE__
814
-                            );
815
-                        }
816
-                    }
817
-                }
818
-            }
819
-            do_action(
820
-                'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
821
-                EE_Registry::instance()->CART,
822
-                $this
823
-            );
824
-            //d( EE_Registry::instance()->CART );
825
-            //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
826
-            if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
827
-                if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
828
-                    do_action(
829
-                        'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
830
-                        EE_Registry::instance()->CART,
831
-                        $this
832
-                    );
833
-                    EE_Registry::instance()->CART->recalculate_all_cart_totals();
834
-                    EE_Registry::instance()->CART->save_cart(false);
835
-                    // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< OR HERE TO KILL REDIRECT AFTER CART UPDATE
836
-                    // just return TRUE for registrations being made from admin
837
-                    if (is_admin()) {
838
-                        return true;
839
-                    }
840
-                    EE_Error::get_notices(false, true);
841
-                    wp_safe_redirect(
842
-                        apply_filters(
843
-                            'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
844
-                            EE_Registry::instance()->CFG->core->reg_page_url()
845
-                        )
846
-                    );
847
-                    exit();
848
-                } else {
849
-                    if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
850
-                        // nothing added to cart
851
-                        EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'), __FILE__,
852
-                            __FUNCTION__, __LINE__);
853
-                    }
854
-                }
855
-            } else {
856
-                // no ticket quantities were selected
857
-                EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
858
-                    'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
859
-            }
860
-        }
861
-        //die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
862
-        // at this point, just return if registration is being made from admin
863
-        if (is_admin()) {
864
-            return false;
865
-        }
866
-        if ($valid['return_url']) {
867
-            EE_Error::get_notices(false, true);
868
-            wp_safe_redirect($valid['return_url']);
869
-            exit();
870
-        } elseif (isset($event_to_add['id'])) {
871
-            EE_Error::get_notices(false, true);
872
-            wp_safe_redirect(get_permalink($event_to_add['id']));
873
-            exit();
874
-        } else {
875
-            echo EE_Error::get_notices();
876
-        }
877
-        return false;
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     *    validate_post_data
884
-     *
885
-     * @access        private
886
-     * @param int $id
887
-     * @return array|FALSE
888
-     */
889
-    private static function _validate_post_data($id = 0)
890
-    {
891
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
892
-        if ( ! $id) {
893
-            EE_Error::add_error(
894
-                __('The event id provided was not valid.', 'event_espresso'),
895
-                __FILE__,
896
-                __FUNCTION__,
897
-                __LINE__
898
-            );
899
-            return false;
900
-        }
901
-        // start with an empty array()
902
-        $valid_data = array();
903
-        // grab valid id
904
-        $valid_data['id'] = $id;
905
-        // grab and sanitize return-url
906
-        $valid_data['return_url'] = esc_url_raw(EE_Registry::instance()->REQ->get('tkt-slctr-return-url-' . $id));
907
-        // array of other form names
908
-        $inputs_to_clean = array(
909
-            'event_id'   => 'tkt-slctr-event-id',
910
-            'max_atndz'  => 'tkt-slctr-max-atndz-',
911
-            'rows'       => 'tkt-slctr-rows-',
912
-            'qty'        => 'tkt-slctr-qty-',
913
-            'ticket_id'  => 'tkt-slctr-ticket-id-',
914
-            'return_url' => 'tkt-slctr-return-url-',
915
-        );
916
-        // let's track the total number of tickets ordered.'
917
-        $valid_data['total_tickets'] = 0;
918
-        // cycle through $inputs_to_clean array
919
-        foreach ($inputs_to_clean as $what => $input_to_clean) {
920
-            // check for POST data
921
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
922
-                // grab value
923
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
924
-                switch ($what) {
925
-                    // integers
926
-                    case 'event_id':
927
-                        $valid_data[$what] = absint($input_value);
928
-                        // get event via the event id we put in the form
929
-                        $valid_data['event'] = EE_Registry::instance()
930
-                                                          ->load_model('Event')
931
-                                                          ->get_one_by_ID($valid_data['event_id']);
932
-                        break;
933
-                    case 'rows':
934
-                    case 'max_atndz':
935
-                        $valid_data[$what] = absint($input_value);
936
-                        break;
937
-                    // arrays of integers
938
-                    case 'qty':
939
-                        /** @var array $row_qty */
940
-                        $row_qty = $input_value;
941
-                        // if qty is coming from a radio button input, then we need to assemble an array of rows
942
-                        if ( ! is_array($row_qty)) {
943
-                            // get number of rows
944
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
945
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
946
-                                : 1;
947
-                            // explode ints by the dash
948
-                            $row_qty = explode('-', $row_qty);
949
-                            $row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
950
-                            $qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
951
-                            $row_qty = array($row => $qty);
952
-                            //								 d( $row_qty );
953
-                            for ($x = 1; $x <= $rows; $x++) {
954
-                                if ( ! isset($row_qty[$x])) {
955
-                                    $row_qty[$x] = 0;
956
-                                }
957
-                            }
958
-                        }
959
-                        ksort($row_qty);
960
-                        //							 d( $row_qty );
961
-                        // cycle thru values
962
-                        foreach ($row_qty as $qty) {
963
-                            $qty = absint($qty);
964
-                            // sanitize as integers
965
-                            $valid_data[$what][] = $qty;
966
-                            $valid_data['total_tickets'] += $qty;
967
-                        }
968
-                        break;
969
-                    // array of integers
970
-                    case 'ticket_id':
971
-                        $value_array = array();
972
-                        // cycle thru values
973
-                        foreach ((array)$input_value as $key => $value) {
974
-                            // allow only numbers, letters,  spaces, commas and dashes
975
-                            $value_array[$key] = wp_strip_all_tags($value);
976
-                            // get ticket via the ticket id we put in the form
977
-                            $ticket_obj = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($value);
978
-                            $valid_data['ticket_obj'][$key] = $ticket_obj;
979
-                        }
980
-                        $valid_data[$what] = $value_array;
981
-                        break;
982
-                    case 'return_url' :
983
-                        // grab and sanitize return-url
984
-                        $valid_data[$what] = esc_url_raw($input_value);
985
-                        break;
986
-                }    // end switch $what
987
-            }
988
-        }    // end foreach $inputs_to_clean
989
-        //		d( $valid_data );
990
-        //		die();
991
-        return $valid_data;
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     *    adds a ticket to the cart
998
-     *
999
-     * @access   private
1000
-     * @param EE_Ticket $ticket
1001
-     * @param int       $qty
1002
-     * @return TRUE on success, FALSE on fail
1003
-     * @throws \EE_Error
1004
-     */
1005
-    private static function _add_ticket_to_cart(EE_Ticket $ticket = null, $qty = 1)
1006
-    {
1007
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1008
-        // get the number of spaces left for this datetime ticket
1009
-        $available_spaces = self::_ticket_datetime_availability($ticket);
1010
-        // compare available spaces against the number of tickets being purchased
1011
-        if ($available_spaces >= $qty) {
1012
-            // allow addons to prevent a ticket from being added to cart
1013
-            if ( ! apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart', true, $ticket,
1014
-                $qty, $available_spaces)
1015
-            ) {
1016
-                return false;
1017
-            }
1018
-            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
1019
-            // add event to cart
1020
-            if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
1021
-                self::_recalculate_ticket_datetime_availability($ticket, $qty);
1022
-                return true;
1023
-            } else {
1024
-                return false;
1025
-            }
1026
-        } else {
1027
-            // tickets can not be purchased but let's find the exact number left for the last ticket selected PRIOR to subtracting tickets
1028
-            $available_spaces = self::_ticket_datetime_availability($ticket, true);
1029
-            // greedy greedy greedy eh?
1030
-            if ($available_spaces > 0) {
1031
-                if (
1032
-                apply_filters(
1033
-                    'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
1034
-                    true,
1035
-                    $ticket,
1036
-                    $qty,
1037
-                    $available_spaces
1038
-                )
1039
-                ) {
1040
-                    EED_Ticket_Selector::_display_availability_error($available_spaces);
1041
-                }
1042
-            } else {
1043
-                EE_Error::add_error(
1044
-                    __('We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
1045
-                        'event_espresso'),
1046
-                    __FILE__, __FUNCTION__, __LINE__
1047
-                );
1048
-            }
1049
-            return false;
1050
-        }
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     *  _display_availability_error
1057
-     *
1058
-     * @access    private
1059
-     * @param int $available_spaces
1060
-     * @throws \EE_Error
1061
-     */
1062
-    private static function _display_availability_error($available_spaces = 1)
1063
-    {
1064
-        // add error messaging - we're using the _n function that will generate
1065
-        // the appropriate singular or plural message based on the number of $available_spaces
1066
-        if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
1067
-            $msg = sprintf(
1068
-                _n(
1069
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
1070
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
1071
-                    $available_spaces,
1072
-                    'event_espresso'
1073
-                ),
1074
-                $available_spaces,
1075
-                '<br />'
1076
-            );
1077
-        } else {
1078
-            $msg = sprintf(
1079
-                _n(
1080
-                    'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
1081
-                    'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
1082
-                    $available_spaces,
1083
-                    'event_espresso'
1084
-                ),
1085
-                $available_spaces,
1086
-                '<br />'
1087
-            );
1088
-        }
1089
-        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1090
-    }
1091
-
1092
-
1093
-
1094
-    /**
1095
-     * _ticket_datetime_availability
1096
-     * creates an array of tickets plus all of the datetimes available to each ticket
1097
-     * and tracks the spaces remaining for each of those datetimes
1098
-     *
1099
-     * @access private
1100
-     * @param EE_Ticket $ticket - selected ticket
1101
-     * @param bool      $get_original_ticket_spaces
1102
-     * @return int
1103
-     * @throws \EE_Error
1104
-     */
1105
-    private static function _ticket_datetime_availability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
1106
-    {
1107
-        // if the $_available_spaces array has not been set up yet...
1108
-        if ( ! isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1109
-            self::_set_initial_ticket_datetime_availability($ticket);
1110
-        }
1111
-        $available_spaces = $ticket->qty() - $ticket->sold();
1112
-        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1113
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
1114
-            foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1115
-                // if we want the original datetime availability BEFORE we started subtracting tickets ?
1116
-                if ($get_original_ticket_spaces) {
1117
-                    // then grab the available spaces from the "tickets" array and compare with the above to get the lowest number
1118
-                    $available_spaces = min($available_spaces,
1119
-                        self::$_available_spaces['tickets'][$ticket->ID()][$DTD_ID]);
1120
-                } else {
1121
-                    // we want the updated ticket availability as stored in the "datetimes" array
1122
-                    $available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][$DTD_ID]);
1123
-                }
1124
-            }
1125
-        }
1126
-        return $available_spaces;
1127
-    }
1128
-
1129
-
1130
-
1131
-    /**
1132
-     * _set_initial_ticket_datetime_availability
1133
-     *
1134
-     * @access private
1135
-     * @param EE_Ticket $ticket
1136
-     * @return void
1137
-     * @throws \EE_Error
1138
-     */
1139
-    private static function _set_initial_ticket_datetime_availability(EE_Ticket $ticket)
1140
-    {
1141
-        // first, get all of the datetimes that are available to this ticket
1142
-        $datetimes = $ticket->get_many_related(
1143
-            'Datetime',
1144
-            array(
1145
-                array(
1146
-                    'DTT_EVT_end' => array(
1147
-                        '>=',
1148
-                        EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
1149
-                    ),
1150
-                ),
1151
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1152
-            )
1153
-        );
1154
-        if ( ! empty($datetimes)) {
1155
-            // now loop thru all of the datetimes
1156
-            foreach ($datetimes as $datetime) {
1157
-                if ($datetime instanceof EE_Datetime) {
1158
-                    // the number of spaces available for the datetime without considering individual ticket quantities
1159
-                    $spaces_remaining = $datetime->spaces_remaining();
1160
-                    // save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold or the datetime spaces remaining) to this ticket using the datetime ID as the key
1161
-                    self::$_available_spaces['tickets'][$ticket->ID()][$datetime->ID()] = min(
1162
-                        $ticket->qty() - $ticket->sold(),
1163
-                        $spaces_remaining
1164
-                    );
1165
-                    // if the remaining spaces for this datetime is already set, then compare that against the datetime spaces remaining, and take the lowest number,
1166
-                    // else just take the datetime spaces remaining, and assign to the datetimes array
1167
-                    self::$_available_spaces['datetimes'][$datetime->ID()] = isset(self::$_available_spaces['datetimes'][$datetime->ID()])
1168
-                        ? min(self::$_available_spaces['datetimes'][$datetime->ID()], $spaces_remaining)
1169
-                        : $spaces_remaining;
1170
-                }
1171
-            }
1172
-        }
1173
-    }
1174
-
1175
-
1176
-
1177
-    /**
1178
-     *    _recalculate_ticket_datetime_availability
1179
-     *
1180
-     * @access    private
1181
-     * @param    EE_Ticket $ticket
1182
-     * @param    int       $qty
1183
-     * @return    void
1184
-     */
1185
-    private static function _recalculate_ticket_datetime_availability(EE_Ticket $ticket, $qty = 0)
1186
-    {
1187
-        if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1188
-            // loop thru tickets, which will ALSO include individual ticket records AND a total
1189
-            foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1190
-                // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
1191
-                self::$_available_spaces['datetimes'][$DTD_ID] -= $qty;
1192
-            }
1193
-        }
1194
-    }
1195
-
1196
-
1197
-
1198
-    /**
1199
-     *    load js
1200
-     *
1201
-     * @access        public
1202
-     * @return        void
1203
-     */
1204
-    public static function load_tckt_slctr_assets()
1205
-    {
1206
-        // add some style
1207
-        if (apply_filters('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', false)) {
1208
-            wp_register_style('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css');
1209
-            wp_enqueue_style('ticket_selector');
1210
-            // make it dance
1211
-            // wp_register_script('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js', array('espresso_core'), '', TRUE);
1212
-            // wp_enqueue_script('ticket_selector');
1213
-        }
1214
-    }
1215
-
1216
-
1217
-
1218
-    public static function load_tckt_slctr_assets_admin()
1219
-    {
1220
-        //iframe button js on admin event editor page
1221
-        if (EE_Registry::instance()->REQ->get('page') === 'espresso_events'
1222
-            && EE_Registry::instance()->REQ->get('action') === 'edit'
1223
-        ) {
1224
-            wp_register_script('ticket_selector_embed', TICKET_SELECTOR_ASSETS_URL . 'ticket-selector-embed.js',
1225
-                array('ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1226
-            wp_enqueue_script('ticket_selector_embed');
1227
-        }
1228
-    }
425
+			}
426
+			return $html;
427
+		}
428
+		// if there is no submit button, then don't start building a form
429
+		// because the "View Details" button will build its own form
430
+		if ( ! apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
431
+			return '';
432
+		}
433
+		$checkout_url = EEH_Event_View::event_link_url($ID);
434
+		if ( ! $checkout_url) {
435
+			EE_Error::add_error(__('The URL for the Event Details page could not be retrieved.', 'event_espresso'),
436
+				__FILE__, __FUNCTION__, __LINE__);
437
+		}
438
+		$extra_params = self::$_in_iframe ? ' target="_blank"' : '';
439
+		$html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
440
+		$html .= wp_nonce_field('process_ticket_selections', 'process_ticket_selections_nonce_' . $ID, true, false);
441
+		$html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
442
+		$html = apply_filters('FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, self::$_event);
443
+		return $html;
444
+	}
445
+
446
+
447
+
448
+	/**
449
+	 * display_ticket_selector_submit
450
+	 *
451
+	 * @param        string $external_url
452
+	 * @return        string
453
+	 * @throws \EE_Error
454
+	 */
455
+	public static function display_ticket_selector_submit($external_url = '')
456
+	{
457
+		$html = '';
458
+		if ( ! is_admin()) {
459
+			// standard TS displayed with submit button, ie: "Register Now"
460
+			if (apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
461
+				$html .= \EED_Ticket_Selector::display_register_now_button();
462
+				$html .= empty($external_url) ?
463
+					\EED_Ticket_Selector::no_tkt_slctr_end_dv()
464
+					: \EED_Ticket_Selector::clear_tkt_slctr();
465
+				$html .= '<br/>' . \EED_Ticket_Selector::ticket_selector_form_close();
466
+			} else if ( EED_Ticket_Selector::$_max_atndz === 1 ) {
467
+				// its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
468
+				if ( EED_Ticket_Selector::$_event->is_sold_out() ) {
469
+					// then instead of a View Details or Submit button, just display a "Sold Out" message
470
+					$html .= apply_filters(
471
+						'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
472
+						sprintf(
473
+							__(
474
+								'%1$s"%2$s" is currently sold out.%4$sPlease check back again later, as spots may become available.%3$s',
475
+								'event_espresso'
476
+							),
477
+							'<p class="no-ticket-selector-msg clear-float">',
478
+							EED_Ticket_Selector::$_event->name(),
479
+							'</p>',
480
+							'<br />'
481
+						),
482
+						EED_Ticket_Selector::$_event
483
+					);
484
+					if (
485
+						apply_filters(
486
+							'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
487
+							false,
488
+							EED_Ticket_Selector::$_event
489
+						)
490
+					) {
491
+						$html .= \EED_Ticket_Selector::display_register_now_button();
492
+					}
493
+					// sold out DWMTS event, no TS, no submit or view details button, but has additional content
494
+					$html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
495
+				} else if (
496
+					apply_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector', false)
497
+					&& ! is_single()
498
+				) {
499
+					// this is a "Dude Where's my Ticket Selector?" (DWMTS) type event,
500
+					// but no tickets are available, so display event's "View Details" button.
501
+					// it is being viewed via somewhere other than a single post
502
+					$html .= EED_Ticket_Selector::display_view_details_btn(true);
503
+				}
504
+			} else if (is_archive()) {
505
+				// event list, no tickets available so display event's "View Details" button
506
+				$html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
507
+				$html .= EED_Ticket_Selector::display_view_details_btn();
508
+			} else {
509
+				if (
510
+					apply_filters(
511
+						'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
512
+						false,
513
+						EED_Ticket_Selector::$_event
514
+					)
515
+				) {
516
+					$html .= \EED_Ticket_Selector::display_register_now_button();
517
+				}
518
+				// no submit or view details button, and no additional content
519
+				$html .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
520
+			}
521
+			if ( ! is_archive()) {
522
+				$html .= \EEH_Template::powered_by_event_espresso('', '', array('utm_content' => 'ticket_selector'));
523
+			}
524
+		}
525
+		return $html;
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 * @return string
532
+	 */
533
+	public static function clear_tkt_slctr()
534
+	{
535
+		// standard TS displayed, appears after a "Register Now" or "view Details" button
536
+		return '<div class="clear"></div>';
537
+	}
538
+
539
+
540
+
541
+	/**
542
+	 * @deprecated 4.9.13
543
+	 * @return string
544
+	 */
545
+	public static function tkt_slctr_end_dv()
546
+	{
547
+		return \EED_Ticket_Selector::clear_tkt_slctr();
548
+	}
549
+
550
+
551
+
552
+	/**
553
+	 * @return string
554
+	 */
555
+	public static function no_tkt_slctr_end_dv()
556
+	{
557
+		// DWMTS event, no TS, appears after a "Register Now" or "view Details" button
558
+		return '<div class="clear"></div></div>';
559
+	}
560
+
561
+
562
+
563
+	/**
564
+	 *    ticket_selector_form_close
565
+	 *
566
+	 * @access        public
567
+	 * @access        public
568
+	 * @return        string
569
+	 */
570
+	public static function ticket_selector_form_close()
571
+	{
572
+		return '</form>';
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * @return string
579
+	 * @throws \EE_Error
580
+	 */
581
+	public static function display_register_now_button()
582
+	{
583
+		$btn_text = apply_filters(
584
+			'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__btn_text',
585
+			__('Register Now', 'event_espresso'),
586
+			EED_Ticket_Selector::$_event
587
+		);
588
+		$external_url = EED_Ticket_Selector::$_event->external_url();
589
+		$html = '<input id="ticket-selector-submit-' . EED_Ticket_Selector::$_event->ID() . '-btn"';
590
+		$html .= ' class="ticket-selector-submit-btn ';
591
+		$html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
592
+		$html .= ' type="submit" value="' . $btn_text . '" />';
593
+		$html .= apply_filters(
594
+			'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
595
+			'',
596
+			EED_Ticket_Selector::$_event
597
+		);
598
+		return $html;
599
+	}
600
+
601
+
602
+	/**
603
+	 * display_view_details_btn
604
+	 *
605
+	 * @access public
606
+	 * @param bool $DWMTS indicates a "Dude Where's my Ticket Selector?" (DWMTS) type event
607
+	 *                    (ie: $_max_atndz === 1) where there are no available tickets,
608
+	 *                    either because they are sold out, expired, or not yet on sale.
609
+	 *                    In this case, we need to close the form BEFORE adding any closing divs
610
+	 * @return string
611
+	 * @throws \EE_Error
612
+	 */
613
+	public static function display_view_details_btn($DWMTS = false)
614
+	{
615
+		if ( ! self::$_event->get_permalink()) {
616
+			EE_Error::add_error(
617
+				__('The URL for the Event Details page could not be retrieved.', 'event_espresso'),
618
+				__FILE__, __FUNCTION__, __LINE__
619
+			);
620
+		}
621
+		$view_details_btn = '<form method="POST" action="';
622
+		$view_details_btn .= apply_filters(
623
+			'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_url',
624
+			self::$_event->get_permalink(),
625
+			self::$_event
626
+		);
627
+		$view_details_btn .= '">';
628
+		$btn_text = apply_filters(
629
+			'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_text',
630
+			__('View Details', 'event_espresso'),
631
+			self::$_event
632
+		);
633
+		$view_details_btn .= '<input id="ticket-selector-submit-'
634
+							 . self::$_event->ID()
635
+							 . '-btn" class="ticket-selector-submit-btn view-details-btn" type="submit" value="'
636
+							 . $btn_text
637
+							 . '" />';
638
+		$view_details_btn .= apply_filters('FHEE__EE_Ticket_Selector__after_view_details_btn', '', self::$_event);
639
+		if ($DWMTS) {
640
+			$view_details_btn .= \EED_Ticket_Selector::ticket_selector_form_close();
641
+			$view_details_btn .= \EED_Ticket_Selector::no_tkt_slctr_end_dv();
642
+			$view_details_btn .= '<br/>';
643
+		} else {
644
+			$view_details_btn .= \EED_Ticket_Selector::clear_tkt_slctr();
645
+			$view_details_btn .= '<br/>';
646
+			$view_details_btn .= \EED_Ticket_Selector::ticket_selector_form_close();
647
+		}
648
+		return $view_details_btn;
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 *    cancel_ticket_selections
655
+	 *
656
+	 * @access        public
657
+	 * @access        public
658
+	 * @return        string
659
+	 */
660
+	public static function cancel_ticket_selections()
661
+	{
662
+		// check nonce
663
+		if ( ! EED_Ticket_Selector::process_ticket_selector_nonce('cancel_ticket_selections')) {
664
+			return false;
665
+		}
666
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
667
+		if (EE_Registry::instance()->REQ->is_set('event_id')) {
668
+			wp_safe_redirect(
669
+				EEH_Event_View::event_link_url(
670
+					EE_Registry::instance()->REQ->get('event_id')
671
+				)
672
+			);
673
+		} else {
674
+			wp_safe_redirect(
675
+				site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
676
+			);
677
+		}
678
+		die();
679
+	}
680
+
681
+
682
+
683
+	/**
684
+	 *    process_ticket_selector_nonce
685
+	 *
686
+	 * @access public
687
+	 * @param  string $nonce_name
688
+	 * @param string  $id
689
+	 * @return bool
690
+	 */
691
+	public static function process_ticket_selector_nonce($nonce_name, $id = '')
692
+	{
693
+		$nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
694
+		if (
695
+			! is_admin()
696
+			&& (
697
+				! EE_Registry::instance()->REQ->is_set($nonce_name_with_id)
698
+				|| ! wp_verify_nonce(
699
+					EE_Registry::instance()->REQ->get($nonce_name_with_id),
700
+					$nonce_name
701
+				)
702
+			)
703
+		) {
704
+			EE_Error::add_error(
705
+				sprintf(
706
+					__(
707
+						'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
708
+						'event_espresso'
709
+					),
710
+					'<br/>'
711
+				),
712
+				__FILE__,
713
+				__FUNCTION__,
714
+				__LINE__
715
+			);
716
+			return false;
717
+		}
718
+		return true;
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 *    process_ticket_selections
725
+	 *
726
+	 * @access public
727
+	 * @return array|boolean
728
+	 * @throws \EE_Error
729
+	 */
730
+	public function process_ticket_selections()
731
+	{
732
+		do_action('EED_Ticket_Selector__process_ticket_selections__before');
733
+		// do we have an event id?
734
+		if ( ! EE_Registry::instance()->REQ->is_set('tkt-slctr-event-id')) {
735
+			// $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
736
+			EE_Error::add_error(
737
+				sprintf(
738
+					__(
739
+						'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
740
+						'event_espresso'
741
+					),
742
+					'<br/>'
743
+				),
744
+				__FILE__,
745
+				__FUNCTION__,
746
+				__LINE__
747
+			);
748
+		}
749
+		//if event id is valid
750
+		$id = absint(EE_Registry::instance()->REQ->get('tkt-slctr-event-id'));
751
+		// check nonce
752
+		if ( ! EED_Ticket_Selector::process_ticket_selector_nonce('process_ticket_selections', $id)) {
753
+			return false;
754
+		}
755
+		//		d( EE_Registry::instance()->REQ );
756
+		self::$_available_spaces = array(
757
+			'tickets'   => array(),
758
+			'datetimes' => array(),
759
+		);
760
+		//we should really only have 1 registration in the works now (ie, no MER) so clear any previous items in the cart.
761
+		// When MER happens this will probably need to be tweaked, possibly wrapped in a conditional checking for some constant defined in MER etc.
762
+		EE_Registry::instance()->load_core('Session');
763
+		// unless otherwise requested, clear the session
764
+		if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
765
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
766
+		}
767
+		//d( EE_Registry::instance()->SSN );
768
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
769
+		// validate/sanitize data
770
+		$valid = self::_validate_post_data($id);
771
+		//EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
772
+		//EEH_Debug_Tools::printr( $valid, '$valid', __FILE__, __LINE__ );
773
+		//EEH_Debug_Tools::printr( $valid[ 'total_tickets' ], 'total_tickets', __FILE__, __LINE__ );
774
+		//EEH_Debug_Tools::printr( $valid[ 'max_atndz' ], 'max_atndz', __FILE__, __LINE__ );
775
+		//check total tickets ordered vs max number of attendees that can register
776
+		if ($valid['total_tickets'] > $valid['max_atndz']) {
777
+			// ordering too many tickets !!!
778
+			$total_tickets_string = _n('You have attempted to purchase %s ticket.',
779
+				'You have attempted to purchase %s tickets.', $valid['total_tickets'], 'event_espresso');
780
+			$limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
781
+			// dev only message
782
+			$max_atndz_string = _n('The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
783
+				'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
784
+				$valid['max_atndz'], 'event_espresso');
785
+			$limit_error_2 = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
786
+			EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
787
+		} else {
788
+			// all data appears to be valid
789
+			$tckts_slctd = false;
790
+			$tickets_added = 0;
791
+			$valid = apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data', $valid);
792
+			if ($valid['total_tickets'] > 0) {
793
+				// load cart
794
+				EE_Registry::instance()->load_core('Cart');
795
+				// cycle thru the number of data rows sent from the event listing
796
+				for ($x = 0; $x < $valid['rows']; $x++) {
797
+					// does this row actually contain a ticket quantity?
798
+					if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
799
+						// YES we have a ticket quantity
800
+						$tckts_slctd = true;
801
+						//						d( $valid['ticket_obj'][$x] );
802
+						if ($valid['ticket_obj'][$x] instanceof EE_Ticket) {
803
+							// then add ticket to cart
804
+							$tickets_added += self::_add_ticket_to_cart($valid['ticket_obj'][$x], $valid['qty'][$x]);
805
+							if (EE_Error::has_error()) {
806
+								break;
807
+							}
808
+						} else {
809
+							// nothing added to cart retrieved
810
+							EE_Error::add_error(
811
+								sprintf(__('A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
812
+									'event_espresso'), '<br/>'),
813
+								__FILE__, __FUNCTION__, __LINE__
814
+							);
815
+						}
816
+					}
817
+				}
818
+			}
819
+			do_action(
820
+				'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
821
+				EE_Registry::instance()->CART,
822
+				$this
823
+			);
824
+			//d( EE_Registry::instance()->CART );
825
+			//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
826
+			if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tckts_slctd)) {
827
+				if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
828
+					do_action(
829
+						'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
830
+						EE_Registry::instance()->CART,
831
+						$this
832
+					);
833
+					EE_Registry::instance()->CART->recalculate_all_cart_totals();
834
+					EE_Registry::instance()->CART->save_cart(false);
835
+					// exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< OR HERE TO KILL REDIRECT AFTER CART UPDATE
836
+					// just return TRUE for registrations being made from admin
837
+					if (is_admin()) {
838
+						return true;
839
+					}
840
+					EE_Error::get_notices(false, true);
841
+					wp_safe_redirect(
842
+						apply_filters(
843
+							'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
844
+							EE_Registry::instance()->CFG->core->reg_page_url()
845
+						)
846
+					);
847
+					exit();
848
+				} else {
849
+					if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
850
+						// nothing added to cart
851
+						EE_Error::add_attention(__('No tickets were added for the event', 'event_espresso'), __FILE__,
852
+							__FUNCTION__, __LINE__);
853
+					}
854
+				}
855
+			} else {
856
+				// no ticket quantities were selected
857
+				EE_Error::add_error(__('You need to select a ticket quantity before you can proceed.',
858
+					'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
859
+			}
860
+		}
861
+		//die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
862
+		// at this point, just return if registration is being made from admin
863
+		if (is_admin()) {
864
+			return false;
865
+		}
866
+		if ($valid['return_url']) {
867
+			EE_Error::get_notices(false, true);
868
+			wp_safe_redirect($valid['return_url']);
869
+			exit();
870
+		} elseif (isset($event_to_add['id'])) {
871
+			EE_Error::get_notices(false, true);
872
+			wp_safe_redirect(get_permalink($event_to_add['id']));
873
+			exit();
874
+		} else {
875
+			echo EE_Error::get_notices();
876
+		}
877
+		return false;
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 *    validate_post_data
884
+	 *
885
+	 * @access        private
886
+	 * @param int $id
887
+	 * @return array|FALSE
888
+	 */
889
+	private static function _validate_post_data($id = 0)
890
+	{
891
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
892
+		if ( ! $id) {
893
+			EE_Error::add_error(
894
+				__('The event id provided was not valid.', 'event_espresso'),
895
+				__FILE__,
896
+				__FUNCTION__,
897
+				__LINE__
898
+			);
899
+			return false;
900
+		}
901
+		// start with an empty array()
902
+		$valid_data = array();
903
+		// grab valid id
904
+		$valid_data['id'] = $id;
905
+		// grab and sanitize return-url
906
+		$valid_data['return_url'] = esc_url_raw(EE_Registry::instance()->REQ->get('tkt-slctr-return-url-' . $id));
907
+		// array of other form names
908
+		$inputs_to_clean = array(
909
+			'event_id'   => 'tkt-slctr-event-id',
910
+			'max_atndz'  => 'tkt-slctr-max-atndz-',
911
+			'rows'       => 'tkt-slctr-rows-',
912
+			'qty'        => 'tkt-slctr-qty-',
913
+			'ticket_id'  => 'tkt-slctr-ticket-id-',
914
+			'return_url' => 'tkt-slctr-return-url-',
915
+		);
916
+		// let's track the total number of tickets ordered.'
917
+		$valid_data['total_tickets'] = 0;
918
+		// cycle through $inputs_to_clean array
919
+		foreach ($inputs_to_clean as $what => $input_to_clean) {
920
+			// check for POST data
921
+			if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
922
+				// grab value
923
+				$input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
924
+				switch ($what) {
925
+					// integers
926
+					case 'event_id':
927
+						$valid_data[$what] = absint($input_value);
928
+						// get event via the event id we put in the form
929
+						$valid_data['event'] = EE_Registry::instance()
930
+														  ->load_model('Event')
931
+														  ->get_one_by_ID($valid_data['event_id']);
932
+						break;
933
+					case 'rows':
934
+					case 'max_atndz':
935
+						$valid_data[$what] = absint($input_value);
936
+						break;
937
+					// arrays of integers
938
+					case 'qty':
939
+						/** @var array $row_qty */
940
+						$row_qty = $input_value;
941
+						// if qty is coming from a radio button input, then we need to assemble an array of rows
942
+						if ( ! is_array($row_qty)) {
943
+							// get number of rows
944
+							$rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
945
+								? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
946
+								: 1;
947
+							// explode ints by the dash
948
+							$row_qty = explode('-', $row_qty);
949
+							$row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
950
+							$qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
951
+							$row_qty = array($row => $qty);
952
+							//								 d( $row_qty );
953
+							for ($x = 1; $x <= $rows; $x++) {
954
+								if ( ! isset($row_qty[$x])) {
955
+									$row_qty[$x] = 0;
956
+								}
957
+							}
958
+						}
959
+						ksort($row_qty);
960
+						//							 d( $row_qty );
961
+						// cycle thru values
962
+						foreach ($row_qty as $qty) {
963
+							$qty = absint($qty);
964
+							// sanitize as integers
965
+							$valid_data[$what][] = $qty;
966
+							$valid_data['total_tickets'] += $qty;
967
+						}
968
+						break;
969
+					// array of integers
970
+					case 'ticket_id':
971
+						$value_array = array();
972
+						// cycle thru values
973
+						foreach ((array)$input_value as $key => $value) {
974
+							// allow only numbers, letters,  spaces, commas and dashes
975
+							$value_array[$key] = wp_strip_all_tags($value);
976
+							// get ticket via the ticket id we put in the form
977
+							$ticket_obj = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($value);
978
+							$valid_data['ticket_obj'][$key] = $ticket_obj;
979
+						}
980
+						$valid_data[$what] = $value_array;
981
+						break;
982
+					case 'return_url' :
983
+						// grab and sanitize return-url
984
+						$valid_data[$what] = esc_url_raw($input_value);
985
+						break;
986
+				}    // end switch $what
987
+			}
988
+		}    // end foreach $inputs_to_clean
989
+		//		d( $valid_data );
990
+		//		die();
991
+		return $valid_data;
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 *    adds a ticket to the cart
998
+	 *
999
+	 * @access   private
1000
+	 * @param EE_Ticket $ticket
1001
+	 * @param int       $qty
1002
+	 * @return TRUE on success, FALSE on fail
1003
+	 * @throws \EE_Error
1004
+	 */
1005
+	private static function _add_ticket_to_cart(EE_Ticket $ticket = null, $qty = 1)
1006
+	{
1007
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1008
+		// get the number of spaces left for this datetime ticket
1009
+		$available_spaces = self::_ticket_datetime_availability($ticket);
1010
+		// compare available spaces against the number of tickets being purchased
1011
+		if ($available_spaces >= $qty) {
1012
+			// allow addons to prevent a ticket from being added to cart
1013
+			if ( ! apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart', true, $ticket,
1014
+				$qty, $available_spaces)
1015
+			) {
1016
+				return false;
1017
+			}
1018
+			$qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
1019
+			// add event to cart
1020
+			if (EE_Registry::instance()->CART->add_ticket_to_cart($ticket, $qty)) {
1021
+				self::_recalculate_ticket_datetime_availability($ticket, $qty);
1022
+				return true;
1023
+			} else {
1024
+				return false;
1025
+			}
1026
+		} else {
1027
+			// tickets can not be purchased but let's find the exact number left for the last ticket selected PRIOR to subtracting tickets
1028
+			$available_spaces = self::_ticket_datetime_availability($ticket, true);
1029
+			// greedy greedy greedy eh?
1030
+			if ($available_spaces > 0) {
1031
+				if (
1032
+				apply_filters(
1033
+					'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_display_availability_error',
1034
+					true,
1035
+					$ticket,
1036
+					$qty,
1037
+					$available_spaces
1038
+				)
1039
+				) {
1040
+					EED_Ticket_Selector::_display_availability_error($available_spaces);
1041
+				}
1042
+			} else {
1043
+				EE_Error::add_error(
1044
+					__('We\'re sorry, but there are no available spaces left for this event at this particular date and time.',
1045
+						'event_espresso'),
1046
+					__FILE__, __FUNCTION__, __LINE__
1047
+				);
1048
+			}
1049
+			return false;
1050
+		}
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 *  _display_availability_error
1057
+	 *
1058
+	 * @access    private
1059
+	 * @param int $available_spaces
1060
+	 * @throws \EE_Error
1061
+	 */
1062
+	private static function _display_availability_error($available_spaces = 1)
1063
+	{
1064
+		// add error messaging - we're using the _n function that will generate
1065
+		// the appropriate singular or plural message based on the number of $available_spaces
1066
+		if (EE_Registry::instance()->CART->all_ticket_quantity_count()) {
1067
+			$msg = sprintf(
1068
+				_n(
1069
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
1070
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets by cancelling the current selection and choosing again, or proceed to registration.',
1071
+					$available_spaces,
1072
+					'event_espresso'
1073
+				),
1074
+				$available_spaces,
1075
+				'<br />'
1076
+			);
1077
+		} else {
1078
+			$msg = sprintf(
1079
+				_n(
1080
+					'We\'re sorry, but there is only %1$s available space left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
1081
+					'We\'re sorry, but there are only %1$s available spaces left for this event at this particular date and time. Please select a different number (or different combination) of tickets.',
1082
+					$available_spaces,
1083
+					'event_espresso'
1084
+				),
1085
+				$available_spaces,
1086
+				'<br />'
1087
+			);
1088
+		}
1089
+		EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1090
+	}
1091
+
1092
+
1093
+
1094
+	/**
1095
+	 * _ticket_datetime_availability
1096
+	 * creates an array of tickets plus all of the datetimes available to each ticket
1097
+	 * and tracks the spaces remaining for each of those datetimes
1098
+	 *
1099
+	 * @access private
1100
+	 * @param EE_Ticket $ticket - selected ticket
1101
+	 * @param bool      $get_original_ticket_spaces
1102
+	 * @return int
1103
+	 * @throws \EE_Error
1104
+	 */
1105
+	private static function _ticket_datetime_availability(EE_Ticket $ticket, $get_original_ticket_spaces = false)
1106
+	{
1107
+		// if the $_available_spaces array has not been set up yet...
1108
+		if ( ! isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1109
+			self::_set_initial_ticket_datetime_availability($ticket);
1110
+		}
1111
+		$available_spaces = $ticket->qty() - $ticket->sold();
1112
+		if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1113
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
1114
+			foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1115
+				// if we want the original datetime availability BEFORE we started subtracting tickets ?
1116
+				if ($get_original_ticket_spaces) {
1117
+					// then grab the available spaces from the "tickets" array and compare with the above to get the lowest number
1118
+					$available_spaces = min($available_spaces,
1119
+						self::$_available_spaces['tickets'][$ticket->ID()][$DTD_ID]);
1120
+				} else {
1121
+					// we want the updated ticket availability as stored in the "datetimes" array
1122
+					$available_spaces = min($available_spaces, self::$_available_spaces['datetimes'][$DTD_ID]);
1123
+				}
1124
+			}
1125
+		}
1126
+		return $available_spaces;
1127
+	}
1128
+
1129
+
1130
+
1131
+	/**
1132
+	 * _set_initial_ticket_datetime_availability
1133
+	 *
1134
+	 * @access private
1135
+	 * @param EE_Ticket $ticket
1136
+	 * @return void
1137
+	 * @throws \EE_Error
1138
+	 */
1139
+	private static function _set_initial_ticket_datetime_availability(EE_Ticket $ticket)
1140
+	{
1141
+		// first, get all of the datetimes that are available to this ticket
1142
+		$datetimes = $ticket->get_many_related(
1143
+			'Datetime',
1144
+			array(
1145
+				array(
1146
+					'DTT_EVT_end' => array(
1147
+						'>=',
1148
+						EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
1149
+					),
1150
+				),
1151
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1152
+			)
1153
+		);
1154
+		if ( ! empty($datetimes)) {
1155
+			// now loop thru all of the datetimes
1156
+			foreach ($datetimes as $datetime) {
1157
+				if ($datetime instanceof EE_Datetime) {
1158
+					// the number of spaces available for the datetime without considering individual ticket quantities
1159
+					$spaces_remaining = $datetime->spaces_remaining();
1160
+					// save the total available spaces ( the lesser of the ticket qty minus the number of tickets sold or the datetime spaces remaining) to this ticket using the datetime ID as the key
1161
+					self::$_available_spaces['tickets'][$ticket->ID()][$datetime->ID()] = min(
1162
+						$ticket->qty() - $ticket->sold(),
1163
+						$spaces_remaining
1164
+					);
1165
+					// if the remaining spaces for this datetime is already set, then compare that against the datetime spaces remaining, and take the lowest number,
1166
+					// else just take the datetime spaces remaining, and assign to the datetimes array
1167
+					self::$_available_spaces['datetimes'][$datetime->ID()] = isset(self::$_available_spaces['datetimes'][$datetime->ID()])
1168
+						? min(self::$_available_spaces['datetimes'][$datetime->ID()], $spaces_remaining)
1169
+						: $spaces_remaining;
1170
+				}
1171
+			}
1172
+		}
1173
+	}
1174
+
1175
+
1176
+
1177
+	/**
1178
+	 *    _recalculate_ticket_datetime_availability
1179
+	 *
1180
+	 * @access    private
1181
+	 * @param    EE_Ticket $ticket
1182
+	 * @param    int       $qty
1183
+	 * @return    void
1184
+	 */
1185
+	private static function _recalculate_ticket_datetime_availability(EE_Ticket $ticket, $qty = 0)
1186
+	{
1187
+		if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1188
+			// loop thru tickets, which will ALSO include individual ticket records AND a total
1189
+			foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1190
+				// subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
1191
+				self::$_available_spaces['datetimes'][$DTD_ID] -= $qty;
1192
+			}
1193
+		}
1194
+	}
1195
+
1196
+
1197
+
1198
+	/**
1199
+	 *    load js
1200
+	 *
1201
+	 * @access        public
1202
+	 * @return        void
1203
+	 */
1204
+	public static function load_tckt_slctr_assets()
1205
+	{
1206
+		// add some style
1207
+		if (apply_filters('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', false)) {
1208
+			wp_register_style('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css');
1209
+			wp_enqueue_style('ticket_selector');
1210
+			// make it dance
1211
+			// wp_register_script('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js', array('espresso_core'), '', TRUE);
1212
+			// wp_enqueue_script('ticket_selector');
1213
+		}
1214
+	}
1215
+
1216
+
1217
+
1218
+	public static function load_tckt_slctr_assets_admin()
1219
+	{
1220
+		//iframe button js on admin event editor page
1221
+		if (EE_Registry::instance()->REQ->get('page') === 'espresso_events'
1222
+			&& EE_Registry::instance()->REQ->get('action') === 'edit'
1223
+		) {
1224
+			wp_register_script('ticket_selector_embed', TICKET_SELECTOR_ASSETS_URL . 'ticket-selector-embed.js',
1225
+				array('ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1226
+			wp_enqueue_script('ticket_selector_embed');
1227
+		}
1228
+	}
1229 1229
 
1230 1230
 
1231 1231
 
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 class EED_Ticket_Selector extends EED_Module
15 15
 {
16 16
 
17
-    const debug = false;    //	true false
17
+    const debug = false; //	true false
18 18
 
19 19
     /**
20 20
      * event that ticket selector is being generated for
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public static function set_definitions()
115 115
     {
116
-        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
117
-        define('TICKET_SELECTOR_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)) . 'templates' . DS);
116
+        define('TICKET_SELECTOR_ASSETS_URL', plugin_dir_url(__FILE__).'assets'.DS);
117
+        define('TICKET_SELECTOR_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)).'templates'.DS);
118 118
         //if config is not set, initialize
119 119
         //If config is not set, set it.
120 120
         if (EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector === null) {
@@ -158,10 +158,10 @@  discard block
 block discarded – undo
158 158
         $template_args['css'] = apply_filters(
159 159
             'FHEE__EED_Ticket_Selector__ticket_selector_iframe__css',
160 160
             array(
161
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_embed.css?ver=' . EVENT_ESPRESSO_VERSION,
162
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css?ver=' . EVENT_ESPRESSO_VERSION,
163
-                includes_url('css/dashicons.min.css?ver=' . $GLOBALS['wp_version']),
164
-                EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
161
+                TICKET_SELECTOR_ASSETS_URL.'ticket_selector_embed.css?ver='.EVENT_ESPRESSO_VERSION,
162
+                TICKET_SELECTOR_ASSETS_URL.'ticket_selector.css?ver='.EVENT_ESPRESSO_VERSION,
163
+                includes_url('css/dashicons.min.css?ver='.$GLOBALS['wp_version']),
164
+                EE_GLOBAL_ASSETS_URL.'css/espresso_default.css?ver='.EVENT_ESPRESSO_VERSION,
165 165
             )
166 166
         );
167 167
         EE_Registry::$i18n_js_strings['ticket_selector_iframe'] = true;
@@ -174,18 +174,18 @@  discard block
 block discarded – undo
174 174
         $template_args['js'] = apply_filters(
175 175
             'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js',
176 176
             array(
177
-                includes_url('js/jquery/jquery.js?ver=' . $GLOBALS['wp_version']),
178
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . EVENT_ESPRESSO_VERSION,
179
-                TICKET_SELECTOR_ASSETS_URL . 'ticket_selector_iframe_embed.js?ver=' . EVENT_ESPRESSO_VERSION,
177
+                includes_url('js/jquery/jquery.js?ver='.$GLOBALS['wp_version']),
178
+                EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js?ver='.EVENT_ESPRESSO_VERSION,
179
+                TICKET_SELECTOR_ASSETS_URL.'ticket_selector_iframe_embed.js?ver='.EVENT_ESPRESSO_VERSION,
180 180
             )
181 181
         );
182 182
         $template_args['notices'] = EEH_Template::display_template(
183
-            EE_TEMPLATES . 'espresso-ajax-notices.template.php',
183
+            EE_TEMPLATES.'espresso-ajax-notices.template.php',
184 184
             array(),
185 185
             true
186 186
         );
187 187
         EEH_Template::display_template(
188
-            TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart_iframe.template.php',
188
+            TICKET_SELECTOR_TEMPLATES_PATH.'ticket_selector_chart_iframe.template.php',
189 189
             $template_args
190 190
         );
191 191
         exit;
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
      * @param int    $id               The post id for the event.
201 201
      * @return string The new html string for the permalink area.
202 202
      */
203
-    public static function iframe_code_button($permalink_string, $id )
203
+    public static function iframe_code_button($permalink_string, $id)
204 204
     {
205 205
         //make sure this is ONLY when editing and the event id has been set.
206 206
         if ( ! empty($id)) {
@@ -214,12 +214,12 @@  discard block
 block discarded – undo
214 214
                                  . '</a> ';
215 215
             $ticket_selector_url = add_query_arg(array('ticket_selector' => 'iframe', 'event' => $id), site_url());
216 216
             $iframe_string = esc_html(
217
-                '<iframe src="' . $ticket_selector_url . '" width="100%" height="100%"></iframe>'
217
+                '<iframe src="'.$ticket_selector_url.'" width="100%" height="100%"></iframe>'
218 218
             );
219 219
             $permalink_string .= '
220 220
 <div id="js-ts-iframe" style="display:none">
221 221
 	<div style="width:100%; height: 500px;">
222
-		' . $iframe_string . '
222
+		' . $iframe_string.'
223 223
 	</div>
224 224
 </div>';
225 225
         }
@@ -243,10 +243,10 @@  discard block
 block discarded – undo
243 243
         }
244 244
         if ($event instanceof EE_Event) {
245 245
             self::$_event = $event;
246
-        } else if ($event instanceof WP_Post ) {
247
-            if ( isset($event->EE_Event) && $event->EE_Event instanceof EE_Event) {
246
+        } else if ($event instanceof WP_Post) {
247
+            if (isset($event->EE_Event) && $event->EE_Event instanceof EE_Event) {
248 248
                 self::$_event = $event->EE_Event;
249
-            } else if ( $event->post_type === 'espresso_events') {
249
+            } else if ($event->post_type === 'espresso_events') {
250 250
                 $event->EE_Event = EEM_Event::instance()->instantiate_class_from_post_object($event);
251 251
                 self::$_event = $event->EE_Event;
252 252
             }
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
             $dev_msg = $user_msg
256 256
                        . __('In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
257 257
                     'event_espresso');
258
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
258
+            EE_Error::add_error($user_msg.'||'.$dev_msg, __FILE__, __FUNCTION__, __LINE__);
259 259
             return false;
260 260
         }
261 261
         return true;
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
                     '</a></span></div>'
363 363
                 );
364 364
             }
365
-            return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
365
+            return '<p><span class="important-notice">'.$sales_closed_msg.'</span></p>';
366 366
         }
367
-        $templates['ticket_selector'] = TICKET_SELECTOR_TEMPLATES_PATH . 'ticket_selector_chart.template.php';
367
+        $templates['ticket_selector'] = TICKET_SELECTOR_TEMPLATES_PATH.'ticket_selector_chart.template.php';
368 368
         $templates['ticket_selector'] = apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
369 369
             $templates['ticket_selector'], self::$_event);
370 370
         // redirecting to another site for registration ??
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
             ? EED_Ticket_Selector::ticket_selector_form_open(
387 387
                 self::$_event->ID(),
388 388
                 $external_url
389
-            ) . $ticket_selector
389
+            ).$ticket_selector
390 390
             : $ticket_selector;
391 391
         // submit button and form close tag
392 392
         $ticket_selector .= ! is_admin() ? EED_Ticket_Selector::display_ticket_selector_submit($external_url) : '';
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
     {
410 410
         // if redirecting, we don't need any anything else
411 411
         if ($external_url) {
412
-            $html = '<form method="GET" action="' . EEH_URL::refactor_url($external_url) . '"';
412
+            $html = '<form method="GET" action="'.EEH_URL::refactor_url($external_url).'"';
413 413
             // open link in new window ?
414 414
             $html .= apply_filters(
415 415
                 'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
@@ -418,10 +418,10 @@  discard block
 block discarded – undo
418 418
                 ? ' target="_blank"'
419 419
                 : '';
420 420
             $html .= '>';
421
-            $query_args = (array)EEH_URL::get_query_string($external_url);
421
+            $query_args = (array) EEH_URL::get_query_string($external_url);
422 422
             foreach ($query_args as $query_arg => $value) {
423 423
                 $html .= '
424
-				<input type="hidden" name="' . $query_arg . '" value="' . $value . '">';
424
+				<input type="hidden" name="' . $query_arg.'" value="'.$value.'">';
425 425
             }
426 426
             return $html;
427 427
         }
@@ -436,8 +436,8 @@  discard block
 block discarded – undo
436 436
                 __FILE__, __FUNCTION__, __LINE__);
437 437
         }
438 438
         $extra_params = self::$_in_iframe ? ' target="_blank"' : '';
439
-        $html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
440
-        $html .= wp_nonce_field('process_ticket_selections', 'process_ticket_selections_nonce_' . $ID, true, false);
439
+        $html = '<form method="POST" action="'.$checkout_url.'"'.$extra_params.'>';
440
+        $html .= wp_nonce_field('process_ticket_selections', 'process_ticket_selections_nonce_'.$ID, true, false);
441 441
         $html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
442 442
         $html = apply_filters('FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, self::$_event);
443 443
         return $html;
@@ -462,10 +462,10 @@  discard block
 block discarded – undo
462 462
                 $html .= empty($external_url) ?
463 463
                     \EED_Ticket_Selector::no_tkt_slctr_end_dv()
464 464
                     : \EED_Ticket_Selector::clear_tkt_slctr();
465
-                $html .= '<br/>' . \EED_Ticket_Selector::ticket_selector_form_close();
466
-            } else if ( EED_Ticket_Selector::$_max_atndz === 1 ) {
465
+                $html .= '<br/>'.\EED_Ticket_Selector::ticket_selector_form_close();
466
+            } else if (EED_Ticket_Selector::$_max_atndz === 1) {
467 467
                 // its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
468
-                if ( EED_Ticket_Selector::$_event->is_sold_out() ) {
468
+                if (EED_Ticket_Selector::$_event->is_sold_out()) {
469 469
                     // then instead of a View Details or Submit button, just display a "Sold Out" message
470 470
                     $html .= apply_filters(
471 471
                         'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
@@ -586,10 +586,10 @@  discard block
 block discarded – undo
586 586
             EED_Ticket_Selector::$_event
587 587
         );
588 588
         $external_url = EED_Ticket_Selector::$_event->external_url();
589
-        $html = '<input id="ticket-selector-submit-' . EED_Ticket_Selector::$_event->ID() . '-btn"';
589
+        $html = '<input id="ticket-selector-submit-'.EED_Ticket_Selector::$_event->ID().'-btn"';
590 590
         $html .= ' class="ticket-selector-submit-btn ';
591 591
         $html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
592
-        $html .= ' type="submit" value="' . $btn_text . '" />';
592
+        $html .= ' type="submit" value="'.$btn_text.'" />';
593 593
         $html .= apply_filters(
594 594
             'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
595 595
             '',
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
             );
673 673
         } else {
674 674
             wp_safe_redirect(
675
-                site_url('/' . EE_Registry::instance()->CFG->core->event_cpt_slug . '/')
675
+                site_url('/'.EE_Registry::instance()->CFG->core->event_cpt_slug.'/')
676 676
             );
677 677
         }
678 678
         die();
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
                 'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
784 784
                 $valid['max_atndz'], 'event_espresso');
785 785
             $limit_error_2 = sprintf($max_atndz_string, $valid['max_atndz'], $valid['max_atndz']);
786
-            EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
786
+            EE_Error::add_error($limit_error_1.'<br/>'.$limit_error_2, __FILE__, __FUNCTION__, __LINE__);
787 787
         } else {
788 788
             // all data appears to be valid
789 789
             $tckts_slctd = false;
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
         // grab valid id
904 904
         $valid_data['id'] = $id;
905 905
         // grab and sanitize return-url
906
-        $valid_data['return_url'] = esc_url_raw(EE_Registry::instance()->REQ->get('tkt-slctr-return-url-' . $id));
906
+        $valid_data['return_url'] = esc_url_raw(EE_Registry::instance()->REQ->get('tkt-slctr-return-url-'.$id));
907 907
         // array of other form names
908 908
         $inputs_to_clean = array(
909 909
             'event_id'   => 'tkt-slctr-event-id',
@@ -918,9 +918,9 @@  discard block
 block discarded – undo
918 918
         // cycle through $inputs_to_clean array
919 919
         foreach ($inputs_to_clean as $what => $input_to_clean) {
920 920
             // check for POST data
921
-            if (EE_Registry::instance()->REQ->is_set($input_to_clean . $id)) {
921
+            if (EE_Registry::instance()->REQ->is_set($input_to_clean.$id)) {
922 922
                 // grab value
923
-                $input_value = EE_Registry::instance()->REQ->get($input_to_clean . $id);
923
+                $input_value = EE_Registry::instance()->REQ->get($input_to_clean.$id);
924 924
                 switch ($what) {
925 925
                     // integers
926 926
                     case 'event_id':
@@ -941,8 +941,8 @@  discard block
 block discarded – undo
941 941
                         // if qty is coming from a radio button input, then we need to assemble an array of rows
942 942
                         if ( ! is_array($row_qty)) {
943 943
                             // get number of rows
944
-                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-' . $id)
945
-                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-' . $id))
944
+                            $rows = EE_Registry::instance()->REQ->is_set('tkt-slctr-rows-'.$id)
945
+                                ? absint(EE_Registry::instance()->REQ->get('tkt-slctr-rows-'.$id))
946 946
                                 : 1;
947 947
                             // explode ints by the dash
948 948
                             $row_qty = explode('-', $row_qty);
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
                     case 'ticket_id':
971 971
                         $value_array = array();
972 972
                         // cycle thru values
973
-                        foreach ((array)$input_value as $key => $value) {
973
+                        foreach ((array) $input_value as $key => $value) {
974 974
                             // allow only numbers, letters,  spaces, commas and dashes
975 975
                             $value_array[$key] = wp_strip_all_tags($value);
976 976
                             // get ticket via the ticket id we put in the form
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
         $available_spaces = $ticket->qty() - $ticket->sold();
1112 1112
         if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1113 1113
             // loop thru tickets, which will ALSO include individual ticket records AND a total
1114
-            foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1114
+            foreach ((array) self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1115 1115
                 // if we want the original datetime availability BEFORE we started subtracting tickets ?
1116 1116
                 if ($get_original_ticket_spaces) {
1117 1117
                     // then grab the available spaces from the "tickets" array and compare with the above to get the lowest number
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
     {
1187 1187
         if (isset(self::$_available_spaces['tickets'][$ticket->ID()])) {
1188 1188
             // loop thru tickets, which will ALSO include individual ticket records AND a total
1189
-            foreach ((array)self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1189
+            foreach ((array) self::$_available_spaces['tickets'][$ticket->ID()] as $DTD_ID => $spaces) {
1190 1190
                 // subtract the qty of selected tickets from each datetime's available spaces this ticket has access to,
1191 1191
                 self::$_available_spaces['datetimes'][$DTD_ID] -= $qty;
1192 1192
             }
@@ -1205,7 +1205,7 @@  discard block
 block discarded – undo
1205 1205
     {
1206 1206
         // add some style
1207 1207
         if (apply_filters('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', false)) {
1208
-            wp_register_style('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.css');
1208
+            wp_register_style('ticket_selector', TICKET_SELECTOR_ASSETS_URL.'ticket_selector.css');
1209 1209
             wp_enqueue_style('ticket_selector');
1210 1210
             // make it dance
1211 1211
             // wp_register_script('ticket_selector', TICKET_SELECTOR_ASSETS_URL . 'ticket_selector.js', array('espresso_core'), '', TRUE);
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
         if (EE_Registry::instance()->REQ->get('page') === 'espresso_events'
1222 1222
             && EE_Registry::instance()->REQ->get('action') === 'edit'
1223 1223
         ) {
1224
-            wp_register_script('ticket_selector_embed', TICKET_SELECTOR_ASSETS_URL . 'ticket-selector-embed.js',
1224
+            wp_register_script('ticket_selector_embed', TICKET_SELECTOR_ASSETS_URL.'ticket-selector-embed.js',
1225 1225
                 array('ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1226 1226
             wp_enqueue_script('ticket_selector_embed');
1227 1227
         }
Please login to merge, or discard this patch.
core/entities/models/JsonModelSchema.php 3 patches
Doc Comments   -2 removed lines patch added patch discarded remove patch
@@ -39,7 +39,6 @@  discard block
 block discarded – undo
39 39
 
40 40
     /**
41 41
      * Return the schema for a given model from a given model.
42
-     * @param \EEM_Base $model
43 42
      * @return array
44 43
      */
45 44
     public function getModelSchema()
@@ -103,7 +102,6 @@  discard block
 block discarded – undo
103 102
 
104 103
     /**
105 104
      * Outputs the schema header for a model.
106
-     * @param \EEM_Base $model
107 105
      * @return array
108 106
      */
109 107
     public function getInitialSchemaStructure()
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
      *
34 34
      * @param \EEM_Base $model
35 35
      */
36
-    public function __construct(EEM_Base $model){
36
+    public function __construct(EEM_Base $model) {
37 37
         $this->model = $model;
38 38
     }
39 39
 
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
     public function getModelSchemaForFields(array $model_fields, array $schema)
61 61
     {
62 62
         foreach ($model_fields as $field => $model_field) {
63
-            if (! $model_field instanceof EE_Model_Field_Base) {
63
+            if ( ! $model_field instanceof EE_Model_Field_Base) {
64 64
                 continue;
65 65
             }
66 66
             $schema['properties'][$field] = $model_field->getSchema();
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
     public function getModelSchemaForRelations(array $relations_on_model, array $schema)
92 92
     {
93 93
         foreach ($relations_on_model as $model_name => $relation) {
94
-            if (! $relation instanceof EE_Model_Relation_Base) {
94
+            if ( ! $relation instanceof EE_Model_Relation_Base) {
95 95
                 continue;
96 96
             }
97 97
             $model_name_for_schema = EEH_Inflector::pluralize_and_lower($model_name);
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -24,115 +24,115 @@
 block discarded – undo
24 24
 class JsonModelSchema
25 25
 {
26 26
 
27
-    /**
28
-     * @var \EEM_Base
29
-     */
30
-    protected $model;
31
-
32
-    /**
33
-     * JsonModelSchema constructor.
34
-     *
35
-     * @param \EEM_Base $model
36
-     */
37
-    public function __construct(EEM_Base $model){
38
-        $this->model = $model;
39
-    }
40
-
41
-    /**
42
-     * Return the schema for a given model from a given model.
43
-     * @param \EEM_Base $model
44
-     * @return array
45
-     */
46
-    public function getModelSchema()
47
-    {
48
-        return $this->getModelSchemaForRelations(
49
-            $this->model->relation_settings(),
50
-            $this->getModelSchemaForFields(
51
-                $this->model->field_settings(),
52
-                $this->getInitialSchemaStructure()
53
-            )
54
-        );
55
-    }
56
-
57
-
58
-    /**
59
-     * Get the schema for a given set of model fields.
60
-     * @param \EE_Model_Field_Base[]     $model_fields
61
-     * @return array
62
-     */
63
-    public function getModelSchemaForFields(array $model_fields, array $schema)
64
-    {
65
-        foreach ($model_fields as $field => $model_field) {
66
-            if (! $model_field instanceof EE_Model_Field_Base) {
67
-                continue;
68
-            }
69
-            $schema['properties'][$field] = $model_field->getSchema();
70
-
71
-            //if this is a primary key field add the primary key item
72
-            if ($model_field instanceof EE_Primary_Key_Field_Base) {
73
-                $schema['properties'][$field]['primary_key'] = true;
74
-            }
75
-
76
-            //if this is a foreign key field add the foreign key item
77
-            if ($model_field instanceof EE_Foreign_Key_Field_Base) {
78
-                $schema['properties'][$field]['foreign_key'] = array(
79
-                    'description' => esc_html__('This is a foreign key the points to the given models.', 'event_espresso'),
80
-                    'type' => 'array',
81
-                    'enum' => $model_field->get_model_class_names_pointed_to()
82
-                );
83
-            }
84
-        }
85
-        return $schema;
86
-    }
87
-
88
-
89
-    /**
90
-     * Get the schema for a given set of model relations
91
-     * @param EE_Model_Relation_Base[] $relations_on_model
92
-     * @return array
93
-     */
94
-    public function getModelSchemaForRelations(array $relations_on_model, array $schema)
95
-    {
96
-        foreach ($relations_on_model as $model_name => $relation) {
97
-            if (! $relation instanceof EE_Model_Relation_Base) {
98
-                continue;
99
-            }
100
-            $model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
101
-                ? strtolower($model_name)
102
-                : EEH_Inflector::pluralize_and_lower($model_name);
103
-            $schema['properties'][$model_name_for_schema] = $relation->getSchema();
104
-        }
105
-        return $schema;
106
-    }
107
-
108
-
109
-    /**
110
-     * Outputs the schema header for a model.
111
-     * @param \EEM_Base $model
112
-     * @return array
113
-     */
114
-    public function getInitialSchemaStructure()
115
-    {
116
-        return array(
117
-            '$schema' => 'http://json-schema.org/draft-04/schema#',
118
-            'title' => $this->model->get_this_model_name(),
119
-            'type' => 'object',
120
-            'properties' => array()
121
-        );
122
-    }
123
-
124
-
125
-    /**
126
-     * Allows one to just use the object as a string to get the json.
127
-     * eg.
128
-     *
129
-     * $json_schema = new JsonModelSchema(EEM_Event::instance());
130
-     * echo $json_schema; //outputs the schema as a json formatted string.
131
-     *
132
-     * @return bool|false|mixed|string
133
-     */
134
-    public function __toString()
135
-    {
136
-        return wp_json_encode($this->getModelSchema());
137
-    }
27
+	/**
28
+	 * @var \EEM_Base
29
+	 */
30
+	protected $model;
31
+
32
+	/**
33
+	 * JsonModelSchema constructor.
34
+	 *
35
+	 * @param \EEM_Base $model
36
+	 */
37
+	public function __construct(EEM_Base $model){
38
+		$this->model = $model;
39
+	}
40
+
41
+	/**
42
+	 * Return the schema for a given model from a given model.
43
+	 * @param \EEM_Base $model
44
+	 * @return array
45
+	 */
46
+	public function getModelSchema()
47
+	{
48
+		return $this->getModelSchemaForRelations(
49
+			$this->model->relation_settings(),
50
+			$this->getModelSchemaForFields(
51
+				$this->model->field_settings(),
52
+				$this->getInitialSchemaStructure()
53
+			)
54
+		);
55
+	}
56
+
57
+
58
+	/**
59
+	 * Get the schema for a given set of model fields.
60
+	 * @param \EE_Model_Field_Base[]     $model_fields
61
+	 * @return array
62
+	 */
63
+	public function getModelSchemaForFields(array $model_fields, array $schema)
64
+	{
65
+		foreach ($model_fields as $field => $model_field) {
66
+			if (! $model_field instanceof EE_Model_Field_Base) {
67
+				continue;
68
+			}
69
+			$schema['properties'][$field] = $model_field->getSchema();
70
+
71
+			//if this is a primary key field add the primary key item
72
+			if ($model_field instanceof EE_Primary_Key_Field_Base) {
73
+				$schema['properties'][$field]['primary_key'] = true;
74
+			}
75
+
76
+			//if this is a foreign key field add the foreign key item
77
+			if ($model_field instanceof EE_Foreign_Key_Field_Base) {
78
+				$schema['properties'][$field]['foreign_key'] = array(
79
+					'description' => esc_html__('This is a foreign key the points to the given models.', 'event_espresso'),
80
+					'type' => 'array',
81
+					'enum' => $model_field->get_model_class_names_pointed_to()
82
+				);
83
+			}
84
+		}
85
+		return $schema;
86
+	}
87
+
88
+
89
+	/**
90
+	 * Get the schema for a given set of model relations
91
+	 * @param EE_Model_Relation_Base[] $relations_on_model
92
+	 * @return array
93
+	 */
94
+	public function getModelSchemaForRelations(array $relations_on_model, array $schema)
95
+	{
96
+		foreach ($relations_on_model as $model_name => $relation) {
97
+			if (! $relation instanceof EE_Model_Relation_Base) {
98
+				continue;
99
+			}
100
+			$model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
101
+				? strtolower($model_name)
102
+				: EEH_Inflector::pluralize_and_lower($model_name);
103
+			$schema['properties'][$model_name_for_schema] = $relation->getSchema();
104
+		}
105
+		return $schema;
106
+	}
107
+
108
+
109
+	/**
110
+	 * Outputs the schema header for a model.
111
+	 * @param \EEM_Base $model
112
+	 * @return array
113
+	 */
114
+	public function getInitialSchemaStructure()
115
+	{
116
+		return array(
117
+			'$schema' => 'http://json-schema.org/draft-04/schema#',
118
+			'title' => $this->model->get_this_model_name(),
119
+			'type' => 'object',
120
+			'properties' => array()
121
+		);
122
+	}
123
+
124
+
125
+	/**
126
+	 * Allows one to just use the object as a string to get the json.
127
+	 * eg.
128
+	 *
129
+	 * $json_schema = new JsonModelSchema(EEM_Event::instance());
130
+	 * echo $json_schema; //outputs the schema as a json formatted string.
131
+	 *
132
+	 * @return bool|false|mixed|string
133
+	 */
134
+	public function __toString()
135
+	{
136
+		return wp_json_encode($this->getModelSchema());
137
+	}
138 138
 }
Please login to merge, or discard this patch.