Completed
Branch FET/extra-logging-when-trashin... (7fb54e)
by
unknown
02:46 queued 20s
created
core/db_models/EEM_Price_Type.model.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -11,142 +11,142 @@
 block discarded – undo
11 11
  */
12 12
 class EEM_Price_Type extends EEM_Soft_Delete_Base
13 13
 {
14
-    // private instance of the Price Type object
15
-    protected static $_instance = null;
16
-    // An array of the price type objects
17
-    public $type = null;
14
+	// private instance of the Price Type object
15
+	protected static $_instance = null;
16
+	// An array of the price type objects
17
+	public $type = null;
18 18
 
19
-    /**
20
-    *   Price Base types
21
-    *
22
-    *   @access private
23
-    *   @var int
24
-    */
25
-    public $base_types = null;
19
+	/**
20
+	 *   Price Base types
21
+	 *
22
+	 *   @access private
23
+	 *   @var int
24
+	 */
25
+	public $base_types = null;
26 26
 
27
-    /**
28
-     * return an array of Base types. Keys are INTs which are used in the database,
29
-     * values are text-representations of the base type.
30
-     * @return array
31
-     */
32
-    public function get_base_types()
33
-    {
34
-        return $this->base_types;
35
-    }
27
+	/**
28
+	 * return an array of Base types. Keys are INTs which are used in the database,
29
+	 * values are text-representations of the base type.
30
+	 * @return array
31
+	 */
32
+	public function get_base_types()
33
+	{
34
+		return $this->base_types;
35
+	}
36 36
 
37
-    /**
38
-     * Gets the name of the base
39
-     * @param type $base_type_int
40
-     * @return type
41
-     */
42
-    public function get_base_type_name($base_type_int)
43
-    {
44
-        return $this->base_types[ $base_type_int ];
45
-    }
37
+	/**
38
+	 * Gets the name of the base
39
+	 * @param type $base_type_int
40
+	 * @return type
41
+	 */
42
+	public function get_base_type_name($base_type_int)
43
+	{
44
+		return $this->base_types[ $base_type_int ];
45
+	}
46 46
 
47
-    /**
48
-     * constants for price base types. In the DB, we decided to store the price base type
49
-     * as an integer. So, to avoid just having magic numbers everwhere (eg, querying for
50
-     * all price types with PBT_ID = 2), we define these constants, to make code more understandable.
51
-     * So, as an example, to query for all price types that are a tax, we'd do
52
-     * EEM_PRice_Type::instance()->get_all(array(array('PBT_ID'=>EEM_Price_Type::base_type_tax)))
53
-     * instead of
54
-     * EEM_Price_Type::instance()->get_all(array(array('PBT_ID'=>2)))
55
-     * Although the 2nd is shorter, it's much less obvious what it's doing. Also, should these magic IDs ever
56
-     * change, we can continue to use the constant, by simply change its value.
57
-     */
58
-    const base_type_base_price = 1;
59
-    const base_type_discount = 2;
60
-    const base_type_surcharge = 3;
61
-    const base_type_tax = 4;
62
-    /**
63
-     *      private constructor to prevent direct creation
64
-     *      @Constructor
65
-     *      @access protected
66
-     *      @return void
67
-     */
68
-    protected function __construct($timezone = null)
69
-    {
70
-        $this->base_types = array(
71
-            EEM_Price_Type::base_type_base_price => esc_html__('Price', 'event_espresso'),
72
-            EEM_Price_Type::base_type_discount => esc_html__('Discount', 'event_espresso'),
73
-            EEM_Price_Type::base_type_surcharge => esc_html__('Surcharge', 'event_espresso'),
74
-            EEM_Price_Type::base_type_tax => esc_html__('Tax', 'event_espresso') );
75
-        $this->singular_item = esc_html__('Price Type', 'event_espresso');
76
-        $this->plural_item = esc_html__('Price Types', 'event_espresso');
47
+	/**
48
+	 * constants for price base types. In the DB, we decided to store the price base type
49
+	 * as an integer. So, to avoid just having magic numbers everwhere (eg, querying for
50
+	 * all price types with PBT_ID = 2), we define these constants, to make code more understandable.
51
+	 * So, as an example, to query for all price types that are a tax, we'd do
52
+	 * EEM_PRice_Type::instance()->get_all(array(array('PBT_ID'=>EEM_Price_Type::base_type_tax)))
53
+	 * instead of
54
+	 * EEM_Price_Type::instance()->get_all(array(array('PBT_ID'=>2)))
55
+	 * Although the 2nd is shorter, it's much less obvious what it's doing. Also, should these magic IDs ever
56
+	 * change, we can continue to use the constant, by simply change its value.
57
+	 */
58
+	const base_type_base_price = 1;
59
+	const base_type_discount = 2;
60
+	const base_type_surcharge = 3;
61
+	const base_type_tax = 4;
62
+	/**
63
+	 *      private constructor to prevent direct creation
64
+	 *      @Constructor
65
+	 *      @access protected
66
+	 *      @return void
67
+	 */
68
+	protected function __construct($timezone = null)
69
+	{
70
+		$this->base_types = array(
71
+			EEM_Price_Type::base_type_base_price => esc_html__('Price', 'event_espresso'),
72
+			EEM_Price_Type::base_type_discount => esc_html__('Discount', 'event_espresso'),
73
+			EEM_Price_Type::base_type_surcharge => esc_html__('Surcharge', 'event_espresso'),
74
+			EEM_Price_Type::base_type_tax => esc_html__('Tax', 'event_espresso') );
75
+		$this->singular_item = esc_html__('Price Type', 'event_espresso');
76
+		$this->plural_item = esc_html__('Price Types', 'event_espresso');
77 77
 
78
-        $this->_tables = array(
79
-            'Price_Type' => new EE_Primary_Table('esp_price_type', 'PRT_ID')
80
-        );
81
-        $this->_fields = array(
82
-            'Price_Type' => array(
83
-                'PRT_ID' => new EE_Primary_Key_Int_Field('PRT_ID', esc_html__('Price Type ID', 'event_espresso')),
84
-                'PRT_name' => new EE_Plain_Text_Field('PRT_name', esc_html__('Price Type Name', 'event_espresso'), false, ''),
85
-                'PBT_ID' => new EE_Enum_Integer_Field('PBT_ID', esc_html__('Price Base type ID, 1 = Price , 2 = Discount , 3 = Surcharge , 4 = Tax', 'event_espresso'), false, EEM_Price_Type::base_type_base_price, $this->base_types),
86
-                'PRT_is_percent' => new EE_Boolean_Field('PRT_is_percent', esc_html__('Flag indicating price is a percentage', 'event_espresso'), false, false),
87
-                'PRT_order' => new EE_Integer_Field('PRT_order', esc_html__('Order in which price should be applied. ', 'event_espresso'), false, 0),
88
-                'PRT_deleted' => new EE_Trashed_Flag_Field('PRT_deleted', esc_html__('Flag indicating price type has been trashed', 'event_espresso'), false, false),
89
-                'PRT_wp_user' => new EE_WP_User_Field('PRT_wp_user', esc_html__('Price Type Creator ID', 'event_espresso'), false),
90
-            )
91
-        );
92
-        $this->_model_relations = array(
93
-            'Price' => new EE_Has_Many_Relation(),
94
-            'WP_User' => new EE_Belongs_To_Relation(),
95
-        );
96
-        // this model is generally available for reading
97
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
98
-        // all price types are "default" in terms of capability names
99
-        $this->_caps_slug = 'default_price_types';
100
-        parent::__construct($timezone);
101
-    }
78
+		$this->_tables = array(
79
+			'Price_Type' => new EE_Primary_Table('esp_price_type', 'PRT_ID')
80
+		);
81
+		$this->_fields = array(
82
+			'Price_Type' => array(
83
+				'PRT_ID' => new EE_Primary_Key_Int_Field('PRT_ID', esc_html__('Price Type ID', 'event_espresso')),
84
+				'PRT_name' => new EE_Plain_Text_Field('PRT_name', esc_html__('Price Type Name', 'event_espresso'), false, ''),
85
+				'PBT_ID' => new EE_Enum_Integer_Field('PBT_ID', esc_html__('Price Base type ID, 1 = Price , 2 = Discount , 3 = Surcharge , 4 = Tax', 'event_espresso'), false, EEM_Price_Type::base_type_base_price, $this->base_types),
86
+				'PRT_is_percent' => new EE_Boolean_Field('PRT_is_percent', esc_html__('Flag indicating price is a percentage', 'event_espresso'), false, false),
87
+				'PRT_order' => new EE_Integer_Field('PRT_order', esc_html__('Order in which price should be applied. ', 'event_espresso'), false, 0),
88
+				'PRT_deleted' => new EE_Trashed_Flag_Field('PRT_deleted', esc_html__('Flag indicating price type has been trashed', 'event_espresso'), false, false),
89
+				'PRT_wp_user' => new EE_WP_User_Field('PRT_wp_user', esc_html__('Price Type Creator ID', 'event_espresso'), false),
90
+			)
91
+		);
92
+		$this->_model_relations = array(
93
+			'Price' => new EE_Has_Many_Relation(),
94
+			'WP_User' => new EE_Belongs_To_Relation(),
95
+		);
96
+		// this model is generally available for reading
97
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
98
+		// all price types are "default" in terms of capability names
99
+		$this->_caps_slug = 'default_price_types';
100
+		parent::__construct($timezone);
101
+	}
102 102
 
103 103
 
104 104
 
105 105
 
106
-    /**
107
-     *      instantiate a new price type object with blank/empty properties
108
-     *
109
-     *      @access     public
110
-     *      @return     mixed       array on success, FALSE on fail
111
-     */
112
-    public function get_new_price_type()
113
-    {
114
-        return EE_Price_Type::new_instance();
115
-    }
106
+	/**
107
+	 *      instantiate a new price type object with blank/empty properties
108
+	 *
109
+	 *      @access     public
110
+	 *      @return     mixed       array on success, FALSE on fail
111
+	 */
112
+	public function get_new_price_type()
113
+	{
114
+		return EE_Price_Type::new_instance();
115
+	}
116 116
 
117 117
 
118
-    /**
119
-     *
120
-     * @param array   $query_params
121
-     * @param bool    $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
122
-     *                                that blocks it (ie, there' sno other data that depends on this data);
123
-     *                                if false, deletes regardless of other objects which may depend on it.
124
-     *                                Its generally advisable to always leave this as TRUE,
125
-     *                                otherwise you could easily corrupt your DB
126
-     * @return bool
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function delete_permanently($query_params = array(), $allow_blocking = true)
131
-    {
132
-        $would_be_deleted_price_types = $this->get_all_deleted_and_undeleted($query_params);
133
-        $would_be_deleted_price_type_ids = array_keys($would_be_deleted_price_types);
118
+	/**
119
+	 *
120
+	 * @param array   $query_params
121
+	 * @param bool    $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
122
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
123
+	 *                                if false, deletes regardless of other objects which may depend on it.
124
+	 *                                Its generally advisable to always leave this as TRUE,
125
+	 *                                otherwise you could easily corrupt your DB
126
+	 * @return bool
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function delete_permanently($query_params = array(), $allow_blocking = true)
131
+	{
132
+		$would_be_deleted_price_types = $this->get_all_deleted_and_undeleted($query_params);
133
+		$would_be_deleted_price_type_ids = array_keys($would_be_deleted_price_types);
134 134
 
135
-        $ID = $query_params[0][ $this->get_primary_key_field()->get_name() ];
135
+		$ID = $query_params[0][ $this->get_primary_key_field()->get_name() ];
136 136
 
137
-        // check if any prices use this price type
138
-        $prc_query_params = array(array('PRT_ID' => array('IN',$would_be_deleted_price_type_ids)));
139
-        if ($prices = $this->get_all_related($ID, 'Price', $prc_query_params)) {
140
-            $prices_names_and_ids = array();
141
-            foreach ($prices as $price) {
142
-                /* @var $price EE_Price */
143
-                $prices_names_and_ids[] = $price->name() . "(" . $price->ID() . ")";
144
-            }
145
-            $msg = sprintf(esc_html__('The Price Type(s) could not be deleted because there are existing Prices that currently use this Price Type.  If you still wish to delete this Price Type, then either delete those Prices or change them to use other Price Types.The prices are: %s', 'event_espresso'), implode(",", $prices_names_and_ids));
146
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
147
-            return false;
148
-        }
137
+		// check if any prices use this price type
138
+		$prc_query_params = array(array('PRT_ID' => array('IN',$would_be_deleted_price_type_ids)));
139
+		if ($prices = $this->get_all_related($ID, 'Price', $prc_query_params)) {
140
+			$prices_names_and_ids = array();
141
+			foreach ($prices as $price) {
142
+				/* @var $price EE_Price */
143
+				$prices_names_and_ids[] = $price->name() . "(" . $price->ID() . ")";
144
+			}
145
+			$msg = sprintf(esc_html__('The Price Type(s) could not be deleted because there are existing Prices that currently use this Price Type.  If you still wish to delete this Price Type, then either delete those Prices or change them to use other Price Types.The prices are: %s', 'event_espresso'), implode(",", $prices_names_and_ids));
146
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
147
+			return false;
148
+		}
149 149
 
150
-        return parent::delete_permanently($query_params);
151
-    }
150
+		return parent::delete_permanently($query_params);
151
+	}
152 152
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Term_Taxonomy.model.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -10,133 +10,133 @@
 block discarded – undo
10 10
  */
11 11
 class EEM_Term_Taxonomy extends EEM_Base
12 12
 {
13
-    /**
14
-     * @var EEM_Term_Taxonomy
15
-     */
16
-    protected static $_instance = null;
13
+	/**
14
+	 * @var EEM_Term_Taxonomy
15
+	 */
16
+	protected static $_instance = null;
17 17
 
18 18
 
19
-    /**
20
-     * @param $timezone
21
-     * @throws EE_Error
22
-     */
23
-    protected function __construct($timezone = null)
24
-    {
25
-        $this->singular_item = esc_html__('Term Taxonomy', 'event_espresso');
26
-        $this->plural_item = esc_html__('Term Taxonomy', 'event_espresso');
27
-        $this->_tables = array(
28
-            'Term_Taxonomy' => new EE_Primary_Table('term_taxonomy', 'term_taxonomy_id'),
29
-        );
30
-        $this->_fields = array(
31
-            'Term_Taxonomy' => array(
32
-                'term_taxonomy_id' => new EE_Primary_Key_Int_Field(
33
-                    'term_taxonomy_id',
34
-                    esc_html__('Term-Taxonomy ID', 'event_espresso')
35
-                ),
36
-                'term_id'          => new EE_Foreign_Key_Int_Field(
37
-                    'term_id',
38
-                    esc_html__("Term Id", "event_espresso"),
39
-                    false,
40
-                    0,
41
-                    'Term'
42
-                ),
43
-                'taxonomy'         => new EE_Plain_Text_Field(
44
-                    'taxonomy',
45
-                    esc_html__('Taxonomy Name', 'event_espresso'),
46
-                    false,
47
-                    'category'
48
-                ),
49
-                'description'      => new EE_Post_Content_Field(
50
-                    'description',
51
-                    esc_html__("Description of Term", "event_espresso"),
52
-                    false,
53
-                    ''
54
-                ),
55
-                'parent'           => new EE_Integer_Field('parent', esc_html__("Parent Term ID", "event_espresso"), false, 0),
56
-                'term_count'       => new EE_Integer_Field(
57
-                    'count',
58
-                    esc_html__("Count of Objects attached", 'event_espresso'),
59
-                    false,
60
-                    0
61
-                ),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Term_Relationship' => new EE_Has_Many_Relation(),
66
-            'Term'              => new EE_Belongs_To_Relation(),
67
-        );
68
-        $cpt_models = array_keys(EE_Registry::instance()->cpt_models());
69
-        foreach ($cpt_models as $model_name) {
70
-            $this->_model_relations[ $model_name ] = new EE_HABTM_Relation('Term_Relationship');
71
-        }
72
-        $this->_wp_core_model = true;
73
-        $this->_indexes = array(
74
-            'term_id_taxonomy' => new EE_Unique_Index(array('term_id', 'taxonomy')),
75
-        );
76
-        $path_to_tax_model = '';
77
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
78
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Taxonomy_Protected(
79
-            $path_to_tax_model
80
-        );
81
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = false;
82
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = false;
83
-        // add cap restrictions for editing relating to the "ee_edit_*"
84
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
85
-            array(
86
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
87
-            )
88
-        );
89
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
90
-            array(
91
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
92
-            )
93
-        );
94
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
95
-            array(
96
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
97
-            )
98
-        );
99
-        // add cap restrictions for deleting relating to the "ee_deleting_*"
100
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
101
-            array(
102
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
103
-            )
104
-        );
105
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
106
-            array(
107
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
108
-            )
109
-        );
110
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
111
-            array(
112
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
113
-            )
114
-        );
115
-        parent::__construct($timezone);
116
-        add_filter('FHEE__Read__create_model_query_params', array('EEM_Term_Taxonomy', 'rest_api_query_params'), 10, 3);
117
-    }
19
+	/**
20
+	 * @param $timezone
21
+	 * @throws EE_Error
22
+	 */
23
+	protected function __construct($timezone = null)
24
+	{
25
+		$this->singular_item = esc_html__('Term Taxonomy', 'event_espresso');
26
+		$this->plural_item = esc_html__('Term Taxonomy', 'event_espresso');
27
+		$this->_tables = array(
28
+			'Term_Taxonomy' => new EE_Primary_Table('term_taxonomy', 'term_taxonomy_id'),
29
+		);
30
+		$this->_fields = array(
31
+			'Term_Taxonomy' => array(
32
+				'term_taxonomy_id' => new EE_Primary_Key_Int_Field(
33
+					'term_taxonomy_id',
34
+					esc_html__('Term-Taxonomy ID', 'event_espresso')
35
+				),
36
+				'term_id'          => new EE_Foreign_Key_Int_Field(
37
+					'term_id',
38
+					esc_html__("Term Id", "event_espresso"),
39
+					false,
40
+					0,
41
+					'Term'
42
+				),
43
+				'taxonomy'         => new EE_Plain_Text_Field(
44
+					'taxonomy',
45
+					esc_html__('Taxonomy Name', 'event_espresso'),
46
+					false,
47
+					'category'
48
+				),
49
+				'description'      => new EE_Post_Content_Field(
50
+					'description',
51
+					esc_html__("Description of Term", "event_espresso"),
52
+					false,
53
+					''
54
+				),
55
+				'parent'           => new EE_Integer_Field('parent', esc_html__("Parent Term ID", "event_espresso"), false, 0),
56
+				'term_count'       => new EE_Integer_Field(
57
+					'count',
58
+					esc_html__("Count of Objects attached", 'event_espresso'),
59
+					false,
60
+					0
61
+				),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Term_Relationship' => new EE_Has_Many_Relation(),
66
+			'Term'              => new EE_Belongs_To_Relation(),
67
+		);
68
+		$cpt_models = array_keys(EE_Registry::instance()->cpt_models());
69
+		foreach ($cpt_models as $model_name) {
70
+			$this->_model_relations[ $model_name ] = new EE_HABTM_Relation('Term_Relationship');
71
+		}
72
+		$this->_wp_core_model = true;
73
+		$this->_indexes = array(
74
+			'term_id_taxonomy' => new EE_Unique_Index(array('term_id', 'taxonomy')),
75
+		);
76
+		$path_to_tax_model = '';
77
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
78
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Taxonomy_Protected(
79
+			$path_to_tax_model
80
+		);
81
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = false;
82
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = false;
83
+		// add cap restrictions for editing relating to the "ee_edit_*"
84
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
85
+			array(
86
+				$path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
87
+			)
88
+		);
89
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
90
+			array(
91
+				$path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
92
+			)
93
+		);
94
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
95
+			array(
96
+				$path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
97
+			)
98
+		);
99
+		// add cap restrictions for deleting relating to the "ee_deleting_*"
100
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
101
+			array(
102
+				$path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
103
+			)
104
+		);
105
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
106
+			array(
107
+				$path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
108
+			)
109
+		);
110
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
111
+			array(
112
+				$path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
113
+			)
114
+		);
115
+		parent::__construct($timezone);
116
+		add_filter('FHEE__Read__create_model_query_params', array('EEM_Term_Taxonomy', 'rest_api_query_params'), 10, 3);
117
+	}
118 118
 
119 119
 
120
-    /**
121
-     * Makes sure that during REST API queries, we only return term-taxonomies
122
-     * for term taxonomies which should be shown in the rest api
123
-     *
124
-     * @param array    $model_query_params
125
-     * @param array    $querystring_query_params
126
-     * @param EEM_Base $model
127
-     * @return array
128
-     * @throws EE_Error
129
-     */
130
-    public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
131
-    {
132
-        if ($model === EEM_Term_Taxonomy::instance()) {
133
-            $taxonomies = get_taxonomies(array('show_in_rest' => true));
134
-            if (! empty($taxonomies)) {
135
-                $model_query_params[0]['taxonomy'] = array('IN', $taxonomies);
136
-            }
137
-        }
138
-        return $model_query_params;
139
-    }
120
+	/**
121
+	 * Makes sure that during REST API queries, we only return term-taxonomies
122
+	 * for term taxonomies which should be shown in the rest api
123
+	 *
124
+	 * @param array    $model_query_params
125
+	 * @param array    $querystring_query_params
126
+	 * @param EEM_Base $model
127
+	 * @return array
128
+	 * @throws EE_Error
129
+	 */
130
+	public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
131
+	{
132
+		if ($model === EEM_Term_Taxonomy::instance()) {
133
+			$taxonomies = get_taxonomies(array('show_in_rest' => true));
134
+			if (! empty($taxonomies)) {
135
+				$model_query_params[0]['taxonomy'] = array('IN', $taxonomies);
136
+			}
137
+		}
138
+		return $model_query_params;
139
+	}
140 140
 }
141 141
 // End of file EEM_Term_Taxonomy.model.php
142 142
 // Location: /includes/models/EEM_Term_Taxonomy.model.php
Please login to merge, or discard this patch.
core/db_models/EEM_CPT_Base.model.php 1 patch
Indentation   +563 added lines, -563 removed lines patch added patch discarded remove patch
@@ -14,567 +14,567 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
16 16
 {
17
-    const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
-
19
-    /**
20
-     * @var string post_status_publish - the wp post status for published cpts
21
-     */
22
-    const post_status_publish = 'publish';
23
-
24
-    /**
25
-     * @var string post_status_future - the wp post status for scheduled cpts
26
-     */
27
-    const post_status_future = 'future';
28
-
29
-    /**
30
-     * @var string post_status_draft - the wp post status for draft cpts
31
-     */
32
-    const post_status_draft = 'draft';
33
-
34
-    /**
35
-     * @var string post_status_pending - the wp post status for pending cpts
36
-     */
37
-    const post_status_pending = 'pending';
38
-
39
-    /**
40
-     * @var string post_status_private - the wp post status for private cpts
41
-     */
42
-    const post_status_private = 'private';
43
-
44
-    /**
45
-     * @var string post_status_trashed - the wp post status for trashed cpts
46
-     */
47
-    const post_status_trashed = 'trash';
48
-
49
-    /**
50
-     * This is an array of custom statuses for the given CPT model (modified by children)
51
-     * format:
52
-     * array(
53
-     *        'status_name' => array(
54
-     *            'label' => esc_html__('Status Name', 'event_espresso'),
55
-     *            'public' => TRUE //whether a public status or not.
56
-     *        )
57
-     * )
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_custom_stati = array();
62
-
63
-
64
-    /**
65
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
66
-     *
67
-     * @param string $timezone
68
-     * @throws \EE_Error
69
-     */
70
-    protected function __construct($timezone = null)
71
-    {
72
-        // adds a relationship to Term_Taxonomy for all these models. For this to work
73
-        // Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
74
-        // eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
75
-        // with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
76
-        // must also be new EE_HABTM_Relation('Term_Relationship');
77
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
78
-        $primary_table_name = null;
79
-        // add  the common _status field to all CPT primary tables.
80
-        foreach ($this->_tables as $alias => $table_obj) {
81
-            if ($table_obj instanceof EE_Primary_Table) {
82
-                $primary_table_name = $alias;
83
-            }
84
-        }
85
-        // set default wp post statuses if child has not already set.
86
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
87
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
88
-                'post_status',
89
-                esc_html__("Event Status", "event_espresso"),
90
-                false,
91
-                'draft'
92
-            );
93
-        }
94
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
95
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
96
-                'to_ping',
97
-                esc_html__('To Ping', 'event_espresso'),
98
-                false,
99
-                ''
100
-            );
101
-        }
102
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
103
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
104
-                'pinged',
105
-                esc_html__('Pinged', 'event_espresso'),
106
-                false,
107
-                ''
108
-            );
109
-        }
110
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
111
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
112
-                'comment_status',
113
-                esc_html__('Comment Status', 'event_espresso'),
114
-                false,
115
-                'open'
116
-            );
117
-        }
118
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
119
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
120
-                'ping_status',
121
-                esc_html__('Ping Status', 'event_espresso'),
122
-                false,
123
-                'open'
124
-            );
125
-        }
126
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
127
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
128
-                'post_content_filtered',
129
-                esc_html__('Post Content Filtered', 'event_espresso'),
130
-                false,
131
-                ''
132
-            );
133
-        }
134
-        if (! isset($this->_model_relations['Post_Meta'])) {
135
-            // don't block deletes though because we want to maintain the current behaviour
136
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
137
-        }
138
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
139
-            // nothing was set during child constructor, so set default
140
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
141
-        }
142
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
143
-            // nothing was set during child constructor, so set default
144
-            // it's ok for child classes to specify this, but generally this is more DRY
145
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
146
-        }
147
-        parent::__construct($timezone);
148
-    }
149
-
150
-
151
-    /**
152
-     * @return array
153
-     */
154
-    public function public_event_stati()
155
-    {
156
-        // @see wp-includes/post.php
157
-        return get_post_stati(array('public' => true));
158
-    }
159
-
160
-
161
-    /**
162
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
163
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
164
-     *
165
-     * @return string
166
-     * @throws EE_Error
167
-     */
168
-    public function deleted_field_name()
169
-    {
170
-        throw new EE_Error(
171
-            sprintf(
172
-                esc_html__(
173
-                    "EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
174
-                    "event_espresso"
175
-                )
176
-            )
177
-        );
178
-    }
179
-
180
-
181
-    /**
182
-     * Gets the field's name that sets the post status
183
-     *
184
-     * @return string
185
-     * @throws EE_Error
186
-     */
187
-    public function post_status_field_name()
188
-    {
189
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
190
-        if ($field) {
191
-            return $field->get_name();
192
-        } else {
193
-            throw new EE_Error(
194
-                sprintf(
195
-                    esc_html__(
196
-                        'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
197
-                        'event_espresso'
198
-                    ),
199
-                    get_class($this),
200
-                    get_class($this)
201
-                )
202
-            );
203
-        }
204
-    }
205
-
206
-
207
-    /**
208
-     * Alters the query params so that only trashed/soft-deleted items are considered
209
-     *
210
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
212
-     */
213
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
214
-    {
215
-        $post_status_field_name = $this->post_status_field_name();
216
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
217
-        return $query_params;
218
-    }
219
-
220
-
221
-    /**
222
-     * Alters the query params so each item's deleted status is ignored.
223
-     *
224
-     * @param array $query_params
225
-     * @return array
226
-     */
227
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
228
-    {
229
-        $query_params['default_where_conditions'] = 'minimum';
230
-        return $query_params;
231
-    }
232
-
233
-
234
-    /**
235
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
236
-     *
237
-     * @param boolean $delete       true to indicate deletion, false to indicate restoration
238
-     * @param array $query_params
239
-     * @return boolean success
240
-     * @throws EE_Error
241
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
242
-     */
243
-    public function delete_or_restore($delete = true, $query_params = array())
244
-    {
245
-        $post_status_field_name = $this->post_status_field_name();
246
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
247
-        $new_status = $delete ? self::post_status_trashed : 'draft';
248
-        $fields_n_values = [$post_status_field_name => $new_status];
249
-        if ($this->update($fields_n_values, $query_params)) {
250
-            return parent::delete_or_restore($delete, $query_params);
251
-        }
252
-        return false;
253
-    }
254
-
255
-
256
-    /**
257
-     * meta_table
258
-     * returns first EE_Secondary_Table table name
259
-     *
260
-     * @access public
261
-     * @return string
262
-     */
263
-    public function meta_table()
264
-    {
265
-        $meta_table = $this->_get_other_tables();
266
-        $meta_table = reset($meta_table);
267
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
268
-    }
269
-
270
-
271
-    /**
272
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
273
-     *
274
-     * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
275
-     *                   db only fields)
276
-     * @return array
277
-     */
278
-    public function get_meta_table_fields($all = false)
279
-    {
280
-        $all_fields = $fields_to_return = array();
281
-        foreach ($this->_tables as $alias => $table_obj) {
282
-            if ($table_obj instanceof EE_Secondary_Table) {
283
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
284
-            }
285
-        }
286
-        if (! $all) {
287
-            foreach ($all_fields as $name => $obj) {
288
-                if ($obj instanceof EE_DB_Only_Field_Base) {
289
-                    continue;
290
-                }
291
-                $fields_to_return[] = $name;
292
-            }
293
-        } else {
294
-            $fields_to_return = array_keys($all_fields);
295
-        }
296
-        return $fields_to_return;
297
-    }
298
-
299
-
300
-    /**
301
-     * Adds an event category with the specified name and description to the specified
302
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
303
-     * and adds an entry in the term_relationship if necessary.
304
-     *
305
-     * @param EE_CPT_Base $cpt_model_object
306
-     * @param string      $category_name (used to derive the term slug too)
307
-     * @param string      $category_description
308
-     * @param int         $parent_term_taxonomy_id
309
-     * @return EE_Term_Taxonomy
310
-     */
311
-    public function add_event_category(
312
-        EE_CPT_Base $cpt_model_object,
313
-        $category_name,
314
-        $category_description = '',
315
-        $parent_term_taxonomy_id = null
316
-    ) {
317
-        // create term
318
-        require_once(EE_MODELS . 'EEM_Term.model.php');
319
-        // first, check for a term by the same name or slug
320
-        $category_slug = sanitize_title($category_name);
321
-        $term = EEM_Term::instance()->get_one(
322
-            array(
323
-                array(
324
-                    'OR' => array(
325
-                        'name' => $category_name,
326
-                        'slug' => $category_slug,
327
-                    ),
328
-                    'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY
329
-                ),
330
-            )
331
-        );
332
-        if (! $term) {
333
-            $term = EE_Term::new_instance(
334
-                array(
335
-                    'name' => $category_name,
336
-                    'slug' => $category_slug,
337
-                )
338
-            );
339
-            $term->save();
340
-        }
341
-        // make sure there's a term-taxonomy entry too
342
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
343
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
344
-            array(
345
-                array(
346
-                    'term_id'  => $term->ID(),
347
-                    'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
348
-                ),
349
-            )
350
-        );
351
-        /** @var $term_taxonomy EE_Term_Taxonomy */
352
-        if (! $term_taxonomy) {
353
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(
354
-                array(
355
-                    'term_id'     => $term->ID(),
356
-                    'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
357
-                    'description' => $category_description,
358
-                    'term_count'       => 1,
359
-                    'parent'      => $parent_term_taxonomy_id,
360
-                )
361
-            );
362
-            $term_taxonomy->save();
363
-        } else {
364
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
365
-            $term_taxonomy->save();
366
-        }
367
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
368
-    }
369
-
370
-
371
-    /**
372
-     * Removed the category specified by name as having a relation to this event.
373
-     * Does not remove the term or term_taxonomy.
374
-     *
375
-     * @param EE_CPT_Base $cpt_model_object_event
376
-     * @param string      $category_name name of the event category (term)
377
-     * @return bool
378
-     */
379
-    public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
380
-    {
381
-        // find the term_taxonomy by that name
382
-        $term_taxonomy = $this->get_first_related(
383
-            $cpt_model_object_event,
384
-            'Term_Taxonomy',
385
-            array(array('Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY))
386
-        );
387
-        /** @var $term_taxonomy EE_Term_Taxonomy */
388
-        if ($term_taxonomy) {
389
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
390
-            $term_taxonomy->save();
391
-        }
392
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
393
-    }
394
-
395
-
396
-    /**
397
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
398
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
399
-     *
400
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
401
-     * @access public
402
-     * @param int          $id   the ID for the cpt we want the feature image for
403
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
404
-     *                           representing width and height in pixels (i.e. array(32,32) ).
405
-     * @param string|array $attr Optional. Query string or array of attributes.
406
-     * @return string HTML image element
407
-     */
408
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
409
-    {
410
-        return get_the_post_thumbnail($id, $size, $attr);
411
-    }
412
-
413
-
414
-    /**
415
-     * Just a handy way to get the list of post statuses currently registered with WP.
416
-     *
417
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
418
-     * @return array
419
-     */
420
-    public function get_post_statuses()
421
-    {
422
-        global $wp_post_statuses;
423
-        $statuses = array();
424
-        foreach ($wp_post_statuses as $post_status => $args_object) {
425
-            $statuses[ $post_status ] = $args_object->label;
426
-        }
427
-        return $statuses;
428
-    }
429
-
430
-
431
-    /**
432
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
433
-     *
434
-     * @return array array of statuses.
435
-     */
436
-    public function get_status_array()
437
-    {
438
-        $statuses = $this->get_post_statuses();
439
-        // first the global filter
440
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
441
-        // now the class specific filter
442
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
443
-        return $statuses;
444
-    }
445
-
446
-
447
-    /**
448
-     * this returns the post statuses that are NOT the default wordpress status
449
-     *
450
-     * @return array
451
-     */
452
-    public function get_custom_post_statuses()
453
-    {
454
-        $new_stati = array();
455
-        foreach ($this->_custom_stati as $status => $props) {
456
-            $new_stati[ $status ] = $props['label'];
457
-        }
458
-        return $new_stati;
459
-    }
460
-
461
-
462
-    /**
463
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
464
-     * are a row from the posts table. If we're missing any fields required for the model,
465
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
466
-     * make sure you are attaching all the model's fields onto the post)
467
-     *
468
-     * @param WP_Post|array $post
469
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
470
-     */
471
-    public function instantiate_class_from_post_object_orig($post)
472
-    {
473
-        $post = (array) $post;
474
-        $has_all_necessary_fields_for_table = true;
475
-        // check if the post has fields on the meta table already
476
-        foreach ($this->_get_other_tables() as $table_obj) {
477
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
478
-            foreach ($fields_for_that_table as $field_obj) {
479
-                if (
480
-                    ! isset($post[ $field_obj->get_table_column() ])
481
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
482
-                ) {
483
-                    $has_all_necessary_fields_for_table = false;
484
-                }
485
-            }
486
-        }
487
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
488
-        if (! $has_all_necessary_fields_for_table) {
489
-            return $this->get_one_by_ID($post['ID']);
490
-        } else {
491
-            return $this->instantiate_class_from_array_or_object($post);
492
-        }
493
-    }
494
-
495
-
496
-    /**
497
-     * @param null $post
498
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
499
-     */
500
-    public function instantiate_class_from_post_object($post = null)
501
-    {
502
-        if (empty($post)) {
503
-            global $post;
504
-        }
505
-        $post = (array) $post;
506
-        $tables_needing_to_be_queried = array();
507
-        // check if the post has fields on the meta table already
508
-        foreach ($this->get_tables() as $table_obj) {
509
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
510
-            foreach ($fields_for_that_table as $field_obj) {
511
-                if (
512
-                    ! isset($post[ $field_obj->get_table_column() ])
513
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
514
-                ) {
515
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
516
-                }
517
-            }
518
-        }
519
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
520
-        if ($tables_needing_to_be_queried) {
521
-            if (
522
-                count($tables_needing_to_be_queried) == 1
523
-                && reset($tables_needing_to_be_queried)
524
-                   instanceof
525
-                   EE_Secondary_Table
526
-            ) {
527
-                // so we're only missing data from a secondary table. Well that's not too hard to query for
528
-                $table_to_query = reset($tables_needing_to_be_queried);
529
-                $missing_data = $this->_do_wpdb_query(
530
-                    'get_row',
531
-                    array(
532
-                        'SELECT * FROM '
533
-                        . $table_to_query->get_table_name()
534
-                        . ' WHERE '
535
-                        . $table_to_query->get_fk_on_table()
536
-                        . ' = '
537
-                        . $post['ID'],
538
-                        ARRAY_A,
539
-                    )
540
-                );
541
-                if (! empty($missing_data)) {
542
-                    $post = array_merge($post, $missing_data);
543
-                }
544
-            } else {
545
-                return $this->get_one_by_ID($post['ID']);
546
-            }
547
-        }
548
-        return $this->instantiate_class_from_array_or_object($post);
549
-    }
550
-
551
-
552
-    /**
553
-     * Gets the post type associated with this
554
-     *
555
-     * @throws EE_Error
556
-     * @return string
557
-     */
558
-    public function post_type()
559
-    {
560
-        $post_type_field = null;
561
-        foreach ($this->field_settings(true) as $field_obj) {
562
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
563
-                $post_type_field = $field_obj;
564
-                break;
565
-            }
566
-        }
567
-        if ($post_type_field == null) {
568
-            throw new EE_Error(
569
-                sprintf(
570
-                    esc_html__(
571
-                        "CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
572
-                        "event_espresso"
573
-                    ),
574
-                    get_class($this)
575
-                )
576
-            );
577
-        }
578
-        return $post_type_field->get_default_value();
579
-    }
17
+	const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
+
19
+	/**
20
+	 * @var string post_status_publish - the wp post status for published cpts
21
+	 */
22
+	const post_status_publish = 'publish';
23
+
24
+	/**
25
+	 * @var string post_status_future - the wp post status for scheduled cpts
26
+	 */
27
+	const post_status_future = 'future';
28
+
29
+	/**
30
+	 * @var string post_status_draft - the wp post status for draft cpts
31
+	 */
32
+	const post_status_draft = 'draft';
33
+
34
+	/**
35
+	 * @var string post_status_pending - the wp post status for pending cpts
36
+	 */
37
+	const post_status_pending = 'pending';
38
+
39
+	/**
40
+	 * @var string post_status_private - the wp post status for private cpts
41
+	 */
42
+	const post_status_private = 'private';
43
+
44
+	/**
45
+	 * @var string post_status_trashed - the wp post status for trashed cpts
46
+	 */
47
+	const post_status_trashed = 'trash';
48
+
49
+	/**
50
+	 * This is an array of custom statuses for the given CPT model (modified by children)
51
+	 * format:
52
+	 * array(
53
+	 *        'status_name' => array(
54
+	 *            'label' => esc_html__('Status Name', 'event_espresso'),
55
+	 *            'public' => TRUE //whether a public status or not.
56
+	 *        )
57
+	 * )
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_custom_stati = array();
62
+
63
+
64
+	/**
65
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
66
+	 *
67
+	 * @param string $timezone
68
+	 * @throws \EE_Error
69
+	 */
70
+	protected function __construct($timezone = null)
71
+	{
72
+		// adds a relationship to Term_Taxonomy for all these models. For this to work
73
+		// Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
74
+		// eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
75
+		// with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
76
+		// must also be new EE_HABTM_Relation('Term_Relationship');
77
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
78
+		$primary_table_name = null;
79
+		// add  the common _status field to all CPT primary tables.
80
+		foreach ($this->_tables as $alias => $table_obj) {
81
+			if ($table_obj instanceof EE_Primary_Table) {
82
+				$primary_table_name = $alias;
83
+			}
84
+		}
85
+		// set default wp post statuses if child has not already set.
86
+		if (! isset($this->_fields[ $primary_table_name ]['status'])) {
87
+			$this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
88
+				'post_status',
89
+				esc_html__("Event Status", "event_espresso"),
90
+				false,
91
+				'draft'
92
+			);
93
+		}
94
+		if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
95
+			$this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
96
+				'to_ping',
97
+				esc_html__('To Ping', 'event_espresso'),
98
+				false,
99
+				''
100
+			);
101
+		}
102
+		if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
103
+			$this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
104
+				'pinged',
105
+				esc_html__('Pinged', 'event_espresso'),
106
+				false,
107
+				''
108
+			);
109
+		}
110
+		if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
111
+			$this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
112
+				'comment_status',
113
+				esc_html__('Comment Status', 'event_espresso'),
114
+				false,
115
+				'open'
116
+			);
117
+		}
118
+		if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
119
+			$this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
120
+				'ping_status',
121
+				esc_html__('Ping Status', 'event_espresso'),
122
+				false,
123
+				'open'
124
+			);
125
+		}
126
+		if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
127
+			$this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
128
+				'post_content_filtered',
129
+				esc_html__('Post Content Filtered', 'event_espresso'),
130
+				false,
131
+				''
132
+			);
133
+		}
134
+		if (! isset($this->_model_relations['Post_Meta'])) {
135
+			// don't block deletes though because we want to maintain the current behaviour
136
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
137
+		}
138
+		if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
139
+			// nothing was set during child constructor, so set default
140
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
141
+		}
142
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
143
+			// nothing was set during child constructor, so set default
144
+			// it's ok for child classes to specify this, but generally this is more DRY
145
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
146
+		}
147
+		parent::__construct($timezone);
148
+	}
149
+
150
+
151
+	/**
152
+	 * @return array
153
+	 */
154
+	public function public_event_stati()
155
+	{
156
+		// @see wp-includes/post.php
157
+		return get_post_stati(array('public' => true));
158
+	}
159
+
160
+
161
+	/**
162
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
163
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
164
+	 *
165
+	 * @return string
166
+	 * @throws EE_Error
167
+	 */
168
+	public function deleted_field_name()
169
+	{
170
+		throw new EE_Error(
171
+			sprintf(
172
+				esc_html__(
173
+					"EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
174
+					"event_espresso"
175
+				)
176
+			)
177
+		);
178
+	}
179
+
180
+
181
+	/**
182
+	 * Gets the field's name that sets the post status
183
+	 *
184
+	 * @return string
185
+	 * @throws EE_Error
186
+	 */
187
+	public function post_status_field_name()
188
+	{
189
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
190
+		if ($field) {
191
+			return $field->get_name();
192
+		} else {
193
+			throw new EE_Error(
194
+				sprintf(
195
+					esc_html__(
196
+						'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
197
+						'event_espresso'
198
+					),
199
+					get_class($this),
200
+					get_class($this)
201
+				)
202
+			);
203
+		}
204
+	}
205
+
206
+
207
+	/**
208
+	 * Alters the query params so that only trashed/soft-deleted items are considered
209
+	 *
210
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
212
+	 */
213
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
214
+	{
215
+		$post_status_field_name = $this->post_status_field_name();
216
+		$query_params[0][ $post_status_field_name ] = self::post_status_trashed;
217
+		return $query_params;
218
+	}
219
+
220
+
221
+	/**
222
+	 * Alters the query params so each item's deleted status is ignored.
223
+	 *
224
+	 * @param array $query_params
225
+	 * @return array
226
+	 */
227
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
228
+	{
229
+		$query_params['default_where_conditions'] = 'minimum';
230
+		return $query_params;
231
+	}
232
+
233
+
234
+	/**
235
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
236
+	 *
237
+	 * @param boolean $delete       true to indicate deletion, false to indicate restoration
238
+	 * @param array $query_params
239
+	 * @return boolean success
240
+	 * @throws EE_Error
241
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
242
+	 */
243
+	public function delete_or_restore($delete = true, $query_params = array())
244
+	{
245
+		$post_status_field_name = $this->post_status_field_name();
246
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
247
+		$new_status = $delete ? self::post_status_trashed : 'draft';
248
+		$fields_n_values = [$post_status_field_name => $new_status];
249
+		if ($this->update($fields_n_values, $query_params)) {
250
+			return parent::delete_or_restore($delete, $query_params);
251
+		}
252
+		return false;
253
+	}
254
+
255
+
256
+	/**
257
+	 * meta_table
258
+	 * returns first EE_Secondary_Table table name
259
+	 *
260
+	 * @access public
261
+	 * @return string
262
+	 */
263
+	public function meta_table()
264
+	{
265
+		$meta_table = $this->_get_other_tables();
266
+		$meta_table = reset($meta_table);
267
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
268
+	}
269
+
270
+
271
+	/**
272
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
273
+	 *
274
+	 * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
275
+	 *                   db only fields)
276
+	 * @return array
277
+	 */
278
+	public function get_meta_table_fields($all = false)
279
+	{
280
+		$all_fields = $fields_to_return = array();
281
+		foreach ($this->_tables as $alias => $table_obj) {
282
+			if ($table_obj instanceof EE_Secondary_Table) {
283
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
284
+			}
285
+		}
286
+		if (! $all) {
287
+			foreach ($all_fields as $name => $obj) {
288
+				if ($obj instanceof EE_DB_Only_Field_Base) {
289
+					continue;
290
+				}
291
+				$fields_to_return[] = $name;
292
+			}
293
+		} else {
294
+			$fields_to_return = array_keys($all_fields);
295
+		}
296
+		return $fields_to_return;
297
+	}
298
+
299
+
300
+	/**
301
+	 * Adds an event category with the specified name and description to the specified
302
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
303
+	 * and adds an entry in the term_relationship if necessary.
304
+	 *
305
+	 * @param EE_CPT_Base $cpt_model_object
306
+	 * @param string      $category_name (used to derive the term slug too)
307
+	 * @param string      $category_description
308
+	 * @param int         $parent_term_taxonomy_id
309
+	 * @return EE_Term_Taxonomy
310
+	 */
311
+	public function add_event_category(
312
+		EE_CPT_Base $cpt_model_object,
313
+		$category_name,
314
+		$category_description = '',
315
+		$parent_term_taxonomy_id = null
316
+	) {
317
+		// create term
318
+		require_once(EE_MODELS . 'EEM_Term.model.php');
319
+		// first, check for a term by the same name or slug
320
+		$category_slug = sanitize_title($category_name);
321
+		$term = EEM_Term::instance()->get_one(
322
+			array(
323
+				array(
324
+					'OR' => array(
325
+						'name' => $category_name,
326
+						'slug' => $category_slug,
327
+					),
328
+					'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY
329
+				),
330
+			)
331
+		);
332
+		if (! $term) {
333
+			$term = EE_Term::new_instance(
334
+				array(
335
+					'name' => $category_name,
336
+					'slug' => $category_slug,
337
+				)
338
+			);
339
+			$term->save();
340
+		}
341
+		// make sure there's a term-taxonomy entry too
342
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
343
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
344
+			array(
345
+				array(
346
+					'term_id'  => $term->ID(),
347
+					'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
348
+				),
349
+			)
350
+		);
351
+		/** @var $term_taxonomy EE_Term_Taxonomy */
352
+		if (! $term_taxonomy) {
353
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(
354
+				array(
355
+					'term_id'     => $term->ID(),
356
+					'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
357
+					'description' => $category_description,
358
+					'term_count'       => 1,
359
+					'parent'      => $parent_term_taxonomy_id,
360
+				)
361
+			);
362
+			$term_taxonomy->save();
363
+		} else {
364
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
365
+			$term_taxonomy->save();
366
+		}
367
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
368
+	}
369
+
370
+
371
+	/**
372
+	 * Removed the category specified by name as having a relation to this event.
373
+	 * Does not remove the term or term_taxonomy.
374
+	 *
375
+	 * @param EE_CPT_Base $cpt_model_object_event
376
+	 * @param string      $category_name name of the event category (term)
377
+	 * @return bool
378
+	 */
379
+	public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
380
+	{
381
+		// find the term_taxonomy by that name
382
+		$term_taxonomy = $this->get_first_related(
383
+			$cpt_model_object_event,
384
+			'Term_Taxonomy',
385
+			array(array('Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY))
386
+		);
387
+		/** @var $term_taxonomy EE_Term_Taxonomy */
388
+		if ($term_taxonomy) {
389
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
390
+			$term_taxonomy->save();
391
+		}
392
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
393
+	}
394
+
395
+
396
+	/**
397
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
398
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
399
+	 *
400
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
401
+	 * @access public
402
+	 * @param int          $id   the ID for the cpt we want the feature image for
403
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
404
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
405
+	 * @param string|array $attr Optional. Query string or array of attributes.
406
+	 * @return string HTML image element
407
+	 */
408
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
409
+	{
410
+		return get_the_post_thumbnail($id, $size, $attr);
411
+	}
412
+
413
+
414
+	/**
415
+	 * Just a handy way to get the list of post statuses currently registered with WP.
416
+	 *
417
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
418
+	 * @return array
419
+	 */
420
+	public function get_post_statuses()
421
+	{
422
+		global $wp_post_statuses;
423
+		$statuses = array();
424
+		foreach ($wp_post_statuses as $post_status => $args_object) {
425
+			$statuses[ $post_status ] = $args_object->label;
426
+		}
427
+		return $statuses;
428
+	}
429
+
430
+
431
+	/**
432
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
433
+	 *
434
+	 * @return array array of statuses.
435
+	 */
436
+	public function get_status_array()
437
+	{
438
+		$statuses = $this->get_post_statuses();
439
+		// first the global filter
440
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
441
+		// now the class specific filter
442
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
443
+		return $statuses;
444
+	}
445
+
446
+
447
+	/**
448
+	 * this returns the post statuses that are NOT the default wordpress status
449
+	 *
450
+	 * @return array
451
+	 */
452
+	public function get_custom_post_statuses()
453
+	{
454
+		$new_stati = array();
455
+		foreach ($this->_custom_stati as $status => $props) {
456
+			$new_stati[ $status ] = $props['label'];
457
+		}
458
+		return $new_stati;
459
+	}
460
+
461
+
462
+	/**
463
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
464
+	 * are a row from the posts table. If we're missing any fields required for the model,
465
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
466
+	 * make sure you are attaching all the model's fields onto the post)
467
+	 *
468
+	 * @param WP_Post|array $post
469
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
470
+	 */
471
+	public function instantiate_class_from_post_object_orig($post)
472
+	{
473
+		$post = (array) $post;
474
+		$has_all_necessary_fields_for_table = true;
475
+		// check if the post has fields on the meta table already
476
+		foreach ($this->_get_other_tables() as $table_obj) {
477
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
478
+			foreach ($fields_for_that_table as $field_obj) {
479
+				if (
480
+					! isset($post[ $field_obj->get_table_column() ])
481
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
482
+				) {
483
+					$has_all_necessary_fields_for_table = false;
484
+				}
485
+			}
486
+		}
487
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
488
+		if (! $has_all_necessary_fields_for_table) {
489
+			return $this->get_one_by_ID($post['ID']);
490
+		} else {
491
+			return $this->instantiate_class_from_array_or_object($post);
492
+		}
493
+	}
494
+
495
+
496
+	/**
497
+	 * @param null $post
498
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
499
+	 */
500
+	public function instantiate_class_from_post_object($post = null)
501
+	{
502
+		if (empty($post)) {
503
+			global $post;
504
+		}
505
+		$post = (array) $post;
506
+		$tables_needing_to_be_queried = array();
507
+		// check if the post has fields on the meta table already
508
+		foreach ($this->get_tables() as $table_obj) {
509
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
510
+			foreach ($fields_for_that_table as $field_obj) {
511
+				if (
512
+					! isset($post[ $field_obj->get_table_column() ])
513
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
514
+				) {
515
+					$tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
516
+				}
517
+			}
518
+		}
519
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
520
+		if ($tables_needing_to_be_queried) {
521
+			if (
522
+				count($tables_needing_to_be_queried) == 1
523
+				&& reset($tables_needing_to_be_queried)
524
+				   instanceof
525
+				   EE_Secondary_Table
526
+			) {
527
+				// so we're only missing data from a secondary table. Well that's not too hard to query for
528
+				$table_to_query = reset($tables_needing_to_be_queried);
529
+				$missing_data = $this->_do_wpdb_query(
530
+					'get_row',
531
+					array(
532
+						'SELECT * FROM '
533
+						. $table_to_query->get_table_name()
534
+						. ' WHERE '
535
+						. $table_to_query->get_fk_on_table()
536
+						. ' = '
537
+						. $post['ID'],
538
+						ARRAY_A,
539
+					)
540
+				);
541
+				if (! empty($missing_data)) {
542
+					$post = array_merge($post, $missing_data);
543
+				}
544
+			} else {
545
+				return $this->get_one_by_ID($post['ID']);
546
+			}
547
+		}
548
+		return $this->instantiate_class_from_array_or_object($post);
549
+	}
550
+
551
+
552
+	/**
553
+	 * Gets the post type associated with this
554
+	 *
555
+	 * @throws EE_Error
556
+	 * @return string
557
+	 */
558
+	public function post_type()
559
+	{
560
+		$post_type_field = null;
561
+		foreach ($this->field_settings(true) as $field_obj) {
562
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
563
+				$post_type_field = $field_obj;
564
+				break;
565
+			}
566
+		}
567
+		if ($post_type_field == null) {
568
+			throw new EE_Error(
569
+				sprintf(
570
+					esc_html__(
571
+						"CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
572
+						"event_espresso"
573
+					),
574
+					get_class($this)
575
+				)
576
+			);
577
+		}
578
+		return $post_type_field->get_default_value();
579
+	}
580 580
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Ticket.model.php 2 patches
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -12,318 +12,318 @@
 block discarded – undo
12 12
  */
13 13
 class EEM_Ticket extends EEM_Soft_Delete_Base
14 14
 {
15
-    /**
16
-     * private instance of the EEM_Ticket object
17
-     *
18
-     * @var EEM_Ticket $_instance
19
-     */
20
-    protected static $_instance;
15
+	/**
16
+	 * private instance of the EEM_Ticket object
17
+	 *
18
+	 * @var EEM_Ticket $_instance
19
+	 */
20
+	protected static $_instance;
21 21
 
22 22
 
23
-    /**
24
-     * private constructor to prevent direct creation
25
-     *
26
-     * @Constructor
27
-     * @access private
28
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
29
-     *                         (and any incoming timezone data that gets saved).
30
-     *                         Note this just sends the timezone info to the date time model field objects.
31
-     *                         Default is NULL
32
-     *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct($timezone)
36
-    {
37
-        $this->singular_item    = esc_html__('Ticket', 'event_espresso');
38
-        $this->plural_item      = esc_html__('Tickets', 'event_espresso');
39
-        $this->_tables          = [
40
-            'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
41
-        ];
42
-        $this->_fields          = [
43
-            'Ticket' => [
44
-                'TKT_ID'          => new EE_Primary_Key_Int_Field(
45
-                    'TKT_ID',
46
-                    esc_html__('Ticket ID', 'event_espresso')
47
-                ),
48
-                'TTM_ID'          => new EE_Foreign_Key_Int_Field(
49
-                    'TTM_ID',
50
-                    esc_html__('Ticket Template ID', 'event_espresso'),
51
-                    false,
52
-                    0,
53
-                    'Ticket_Template'
54
-                ),
55
-                'TKT_name'        => new EE_Plain_Text_Field(
56
-                    'TKT_name',
57
-                    esc_html__('Ticket Name', 'event_espresso'),
58
-                    false,
59
-                    ''
60
-                ),
61
-                'TKT_description' => new EE_Post_Content_Field(
62
-                    'TKT_description',
63
-                    esc_html__('Description of Ticket', 'event_espresso'),
64
-                    false,
65
-                    ''
66
-                ),
67
-                'TKT_start_date'  => new EE_Datetime_Field(
68
-                    'TKT_start_date',
69
-                    esc_html__('Start time/date of Ticket', 'event_espresso'),
70
-                    false,
71
-                    EE_Datetime_Field::now,
72
-                    $timezone
73
-                ),
74
-                'TKT_end_date'    => new EE_Datetime_Field(
75
-                    'TKT_end_date',
76
-                    esc_html__('End time/date of Ticket', 'event_espresso'),
77
-                    false,
78
-                    EE_Datetime_Field::now,
79
-                    $timezone
80
-                ),
81
-                'TKT_min'         => new EE_Integer_Field(
82
-                    'TKT_min',
83
-                    esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
84
-                    false,
85
-                    0
86
-                ),
87
-                'TKT_max'         => new EE_Infinite_Integer_Field(
88
-                    'TKT_max',
89
-                    esc_html__(
90
-                        'Maximum quantity of this ticket that can be purchased in one transaction',
91
-                        'event_espresso'
92
-                    ),
93
-                    false,
94
-                    EE_INF
95
-                ),
96
-                'TKT_price'       => new EE_Money_Field(
97
-                    'TKT_price',
98
-                    esc_html__('Final calculated price for ticket', 'event_espresso'),
99
-                    false,
100
-                    0
101
-                ),
102
-                'TKT_sold'        => new EE_Integer_Field(
103
-                    'TKT_sold',
104
-                    esc_html__('Number of this ticket sold', 'event_espresso'),
105
-                    false,
106
-                    0
107
-                ),
108
-                'TKT_qty'         => new EE_Infinite_Integer_Field(
109
-                    'TKT_qty',
110
-                    esc_html__('Quantity of this ticket that is available', 'event_espresso'),
111
-                    false,
112
-                    EE_INF
113
-                ),
114
-                'TKT_reserved'    => new EE_Integer_Field(
115
-                    'TKT_reserved',
116
-                    esc_html__(
117
-                        'Quantity of this ticket that is reserved, but not yet fully purchased',
118
-                        'event_espresso'
119
-                    ),
120
-                    false,
121
-                    0
122
-                ),
123
-                'TKT_uses'        => new EE_Infinite_Integer_Field(
124
-                    'TKT_uses',
125
-                    esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
126
-                    false,
127
-                    EE_INF
128
-                ),
129
-                'TKT_required'    => new EE_Boolean_Field(
130
-                    'TKT_required',
131
-                    esc_html__(
132
-                        'Flag indicating whether this ticket must be purchased with a transaction',
133
-                        'event_espresso'
134
-                    ),
135
-                    false,
136
-                    false
137
-                ),
138
-                'TKT_taxable'     => new EE_Boolean_Field(
139
-                    'TKT_taxable',
140
-                    esc_html__(
141
-                        'Flag indicating whether there is tax applied on this ticket',
142
-                        'event_espresso'
143
-                    ),
144
-                    false,
145
-                    false
146
-                ),
147
-                'TKT_is_default'  => new EE_Boolean_Field(
148
-                    'TKT_is_default',
149
-                    esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
150
-                    false,
151
-                    false
152
-                ),
153
-                'TKT_order'       => new EE_Integer_Field(
154
-                    'TKT_order',
155
-                    esc_html__(
156
-                        'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
157
-                        'event_espresso'
158
-                    ),
159
-                    false,
160
-                    0
161
-                ),
162
-                'TKT_row'         => new EE_Integer_Field(
163
-                    'TKT_row',
164
-                    esc_html__('How tickets are displayed in the ui', 'event_espresso'),
165
-                    false,
166
-                    0
167
-                ),
168
-                'TKT_deleted'     => new EE_Trashed_Flag_Field(
169
-                    'TKT_deleted',
170
-                    esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
171
-                    false,
172
-                    false
173
-                ),
174
-                'TKT_wp_user'     => new EE_WP_User_Field(
175
-                    'TKT_wp_user',
176
-                    esc_html__('Ticket Creator ID', 'event_espresso'),
177
-                    false
178
-                ),
179
-                'TKT_parent'      => new EE_Integer_Field(
180
-                    'TKT_parent',
181
-                    esc_html__(
182
-                        'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
183
-                        'event_espresso'
184
-                    ),
185
-                    true,
186
-                    0
187
-                ),
188
-            ],
189
-        ];
190
-        $this->_model_relations = [
191
-            'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
192
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
193
-            'Price'           => new EE_HABTM_Relation('Ticket_Price'),
194
-            'Ticket_Template' => new EE_Belongs_To_Relation(),
195
-            'Registration'    => new EE_Has_Many_Relation(),
196
-            'WP_User'         => new EE_Belongs_To_Relation(),
197
-        ];
198
-        // this model is generally available for reading
199
-        $path_to_event                                            = 'Datetime.Event';
200
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
201
-            'TKT_is_default',
202
-            $path_to_event
203
-        );
23
+	/**
24
+	 * private constructor to prevent direct creation
25
+	 *
26
+	 * @Constructor
27
+	 * @access private
28
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
29
+	 *                         (and any incoming timezone data that gets saved).
30
+	 *                         Note this just sends the timezone info to the date time model field objects.
31
+	 *                         Default is NULL
32
+	 *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct($timezone)
36
+	{
37
+		$this->singular_item    = esc_html__('Ticket', 'event_espresso');
38
+		$this->plural_item      = esc_html__('Tickets', 'event_espresso');
39
+		$this->_tables          = [
40
+			'Ticket' => new EE_Primary_Table('esp_ticket', 'TKT_ID'),
41
+		];
42
+		$this->_fields          = [
43
+			'Ticket' => [
44
+				'TKT_ID'          => new EE_Primary_Key_Int_Field(
45
+					'TKT_ID',
46
+					esc_html__('Ticket ID', 'event_espresso')
47
+				),
48
+				'TTM_ID'          => new EE_Foreign_Key_Int_Field(
49
+					'TTM_ID',
50
+					esc_html__('Ticket Template ID', 'event_espresso'),
51
+					false,
52
+					0,
53
+					'Ticket_Template'
54
+				),
55
+				'TKT_name'        => new EE_Plain_Text_Field(
56
+					'TKT_name',
57
+					esc_html__('Ticket Name', 'event_espresso'),
58
+					false,
59
+					''
60
+				),
61
+				'TKT_description' => new EE_Post_Content_Field(
62
+					'TKT_description',
63
+					esc_html__('Description of Ticket', 'event_espresso'),
64
+					false,
65
+					''
66
+				),
67
+				'TKT_start_date'  => new EE_Datetime_Field(
68
+					'TKT_start_date',
69
+					esc_html__('Start time/date of Ticket', 'event_espresso'),
70
+					false,
71
+					EE_Datetime_Field::now,
72
+					$timezone
73
+				),
74
+				'TKT_end_date'    => new EE_Datetime_Field(
75
+					'TKT_end_date',
76
+					esc_html__('End time/date of Ticket', 'event_espresso'),
77
+					false,
78
+					EE_Datetime_Field::now,
79
+					$timezone
80
+				),
81
+				'TKT_min'         => new EE_Integer_Field(
82
+					'TKT_min',
83
+					esc_html__('Minimum quantity of this ticket that must be purchased', 'event_espresso'),
84
+					false,
85
+					0
86
+				),
87
+				'TKT_max'         => new EE_Infinite_Integer_Field(
88
+					'TKT_max',
89
+					esc_html__(
90
+						'Maximum quantity of this ticket that can be purchased in one transaction',
91
+						'event_espresso'
92
+					),
93
+					false,
94
+					EE_INF
95
+				),
96
+				'TKT_price'       => new EE_Money_Field(
97
+					'TKT_price',
98
+					esc_html__('Final calculated price for ticket', 'event_espresso'),
99
+					false,
100
+					0
101
+				),
102
+				'TKT_sold'        => new EE_Integer_Field(
103
+					'TKT_sold',
104
+					esc_html__('Number of this ticket sold', 'event_espresso'),
105
+					false,
106
+					0
107
+				),
108
+				'TKT_qty'         => new EE_Infinite_Integer_Field(
109
+					'TKT_qty',
110
+					esc_html__('Quantity of this ticket that is available', 'event_espresso'),
111
+					false,
112
+					EE_INF
113
+				),
114
+				'TKT_reserved'    => new EE_Integer_Field(
115
+					'TKT_reserved',
116
+					esc_html__(
117
+						'Quantity of this ticket that is reserved, but not yet fully purchased',
118
+						'event_espresso'
119
+					),
120
+					false,
121
+					0
122
+				),
123
+				'TKT_uses'        => new EE_Infinite_Integer_Field(
124
+					'TKT_uses',
125
+					esc_html__('Number of datetimes this ticket can be used at', 'event_espresso'),
126
+					false,
127
+					EE_INF
128
+				),
129
+				'TKT_required'    => new EE_Boolean_Field(
130
+					'TKT_required',
131
+					esc_html__(
132
+						'Flag indicating whether this ticket must be purchased with a transaction',
133
+						'event_espresso'
134
+					),
135
+					false,
136
+					false
137
+				),
138
+				'TKT_taxable'     => new EE_Boolean_Field(
139
+					'TKT_taxable',
140
+					esc_html__(
141
+						'Flag indicating whether there is tax applied on this ticket',
142
+						'event_espresso'
143
+					),
144
+					false,
145
+					false
146
+				),
147
+				'TKT_is_default'  => new EE_Boolean_Field(
148
+					'TKT_is_default',
149
+					esc_html__('Flag indicating that this ticket is a default ticket', 'event_espresso'),
150
+					false,
151
+					false
152
+				),
153
+				'TKT_order'       => new EE_Integer_Field(
154
+					'TKT_order',
155
+					esc_html__(
156
+						'The order in which the Ticket is displayed in the editor (used for autosaves when the form doesn\'t have the ticket ID yet)',
157
+						'event_espresso'
158
+					),
159
+					false,
160
+					0
161
+				),
162
+				'TKT_row'         => new EE_Integer_Field(
163
+					'TKT_row',
164
+					esc_html__('How tickets are displayed in the ui', 'event_espresso'),
165
+					false,
166
+					0
167
+				),
168
+				'TKT_deleted'     => new EE_Trashed_Flag_Field(
169
+					'TKT_deleted',
170
+					esc_html__('Flag indicating if this has been archived or not', 'event_espresso'),
171
+					false,
172
+					false
173
+				),
174
+				'TKT_wp_user'     => new EE_WP_User_Field(
175
+					'TKT_wp_user',
176
+					esc_html__('Ticket Creator ID', 'event_espresso'),
177
+					false
178
+				),
179
+				'TKT_parent'      => new EE_Integer_Field(
180
+					'TKT_parent',
181
+					esc_html__(
182
+						'Indicates what TKT_ID is the parent of this TKT_ID (used in autosaves/revisions)',
183
+						'event_espresso'
184
+					),
185
+					true,
186
+					0
187
+				),
188
+			],
189
+		];
190
+		$this->_model_relations = [
191
+			'Datetime'        => new EE_HABTM_Relation('Datetime_Ticket'),
192
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
193
+			'Price'           => new EE_HABTM_Relation('Ticket_Price'),
194
+			'Ticket_Template' => new EE_Belongs_To_Relation(),
195
+			'Registration'    => new EE_Has_Many_Relation(),
196
+			'WP_User'         => new EE_Belongs_To_Relation(),
197
+		];
198
+		// this model is generally available for reading
199
+		$path_to_event                                            = 'Datetime.Event';
200
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
201
+			'TKT_is_default',
202
+			$path_to_event
203
+		);
204 204
 
205
-        // account for default tickets in the caps
206
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
207
-            new EE_Restriction_Generator_Default_Protected(
208
-                'TKT_is_default',
209
-                $path_to_event
210
-            );
211
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
212
-            new EE_Restriction_Generator_Default_Protected(
213
-                'TKT_is_default',
214
-                $path_to_event
215
-            );
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
217
-            new EE_Restriction_Generator_Default_Protected(
218
-                'TKT_is_default',
219
-                $path_to_event
220
-            );
205
+		// account for default tickets in the caps
206
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
207
+			new EE_Restriction_Generator_Default_Protected(
208
+				'TKT_is_default',
209
+				$path_to_event
210
+			);
211
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
212
+			new EE_Restriction_Generator_Default_Protected(
213
+				'TKT_is_default',
214
+				$path_to_event
215
+			);
216
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
217
+			new EE_Restriction_Generator_Default_Protected(
218
+				'TKT_is_default',
219
+				$path_to_event
220
+			);
221 221
 
222
-        $this->model_chain_to_password = $path_to_event;
223
-        parent::__construct($timezone);
224
-    }
222
+		$this->model_chain_to_password = $path_to_event;
223
+		parent::__construct($timezone);
224
+	}
225 225
 
226 226
 
227
-    /**
228
-     * This returns all tickets that are defaults from the db
229
-     *
230
-     * @return EE_Ticket[]
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function get_all_default_tickets()
235
-    {
236
-        $tickets = $this->get_all([['TKT_is_default' => 1], 'order_by' => ['TKT_ID' => 'ASC']]);
237
-        // we need to set the start date and end date to today's date and the start of the default dtt
238
-        return $this->_set_default_dates($tickets);
239
-    }
227
+	/**
228
+	 * This returns all tickets that are defaults from the db
229
+	 *
230
+	 * @return EE_Ticket[]
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function get_all_default_tickets()
235
+	{
236
+		$tickets = $this->get_all([['TKT_is_default' => 1], 'order_by' => ['TKT_ID' => 'ASC']]);
237
+		// we need to set the start date and end date to today's date and the start of the default dtt
238
+		return $this->_set_default_dates($tickets);
239
+	}
240 240
 
241 241
 
242
-    /**
243
-     * sets up relevant start and end date for EE_Ticket (s)
244
-     *
245
-     * @param EE_Ticket[] $tickets
246
-     * @return EE_Ticket[]
247
-     * @throws EE_Error
248
-     * @throws ReflectionException
249
-     */
250
-    private function _set_default_dates($tickets)
251
-    {
252
-        foreach ($tickets as $ticket) {
253
-            $ticket->set(
254
-                'TKT_start_date',
255
-                (int) $this->current_time_for_query('TKT_start_date', true)
256
-            );
257
-            $ticket->set(
258
-                'TKT_end_date',
259
-                (int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
260
-            );
261
-            $ticket->set_end_time(
262
-                $this->convert_datetime_for_query(
263
-                    'TKT_end_date',
264
-                    '11:59 pm',
265
-                    'g:i a',
266
-                    $this->_timezone
267
-                )
268
-            );
269
-        }
270
-        return $tickets;
271
-    }
242
+	/**
243
+	 * sets up relevant start and end date for EE_Ticket (s)
244
+	 *
245
+	 * @param EE_Ticket[] $tickets
246
+	 * @return EE_Ticket[]
247
+	 * @throws EE_Error
248
+	 * @throws ReflectionException
249
+	 */
250
+	private function _set_default_dates($tickets)
251
+	{
252
+		foreach ($tickets as $ticket) {
253
+			$ticket->set(
254
+				'TKT_start_date',
255
+				(int) $this->current_time_for_query('TKT_start_date', true)
256
+			);
257
+			$ticket->set(
258
+				'TKT_end_date',
259
+				(int) $this->current_time_for_query('TKT_end_date', true) + MONTH_IN_SECONDS
260
+			);
261
+			$ticket->set_end_time(
262
+				$this->convert_datetime_for_query(
263
+					'TKT_end_date',
264
+					'11:59 pm',
265
+					'g:i a',
266
+					$this->_timezone
267
+				)
268
+			);
269
+		}
270
+		return $tickets;
271
+	}
272 272
 
273 273
 
274
-    /**
275
-     * Gets the total number of tickets available at a particular datetime (does
276
-     * NOT take int account the datetime's spaces available)
277
-     *
278
-     * @param int   $DTT_ID
279
-     * @param array $query_params
280
-     * @return int
281
-     * @throws EE_Error
282
-     * @throws EE_Error
283
-     */
284
-    public function sum_tickets_currently_available_at_datetime($DTT_ID, $query_params = [])
285
-    {
286
-        return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
287
-    }
274
+	/**
275
+	 * Gets the total number of tickets available at a particular datetime (does
276
+	 * NOT take int account the datetime's spaces available)
277
+	 *
278
+	 * @param int   $DTT_ID
279
+	 * @param array $query_params
280
+	 * @return int
281
+	 * @throws EE_Error
282
+	 * @throws EE_Error
283
+	 */
284
+	public function sum_tickets_currently_available_at_datetime($DTT_ID, $query_params = [])
285
+	{
286
+		return EEM_Datetime::instance()->sum_tickets_currently_available_at_datetime($DTT_ID, $query_params);
287
+	}
288 288
 
289 289
 
290
-    /**
291
-     * Updates the TKT_sold quantity on all the tickets matching $query_params
292
-     *
293
-     * @param EE_Ticket[] $tickets
294
-     * @return void
295
-     * @throws EE_Error
296
-     * @throws ReflectionException
297
-     */
298
-    public function update_tickets_sold($tickets)
299
-    {
300
-        foreach ($tickets as $ticket) {
301
-            $ticket->update_tickets_sold();
302
-        }
303
-    }
290
+	/**
291
+	 * Updates the TKT_sold quantity on all the tickets matching $query_params
292
+	 *
293
+	 * @param EE_Ticket[] $tickets
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 * @throws ReflectionException
297
+	 */
298
+	public function update_tickets_sold($tickets)
299
+	{
300
+		foreach ($tickets as $ticket) {
301
+			$ticket->update_tickets_sold();
302
+		}
303
+	}
304 304
 
305 305
 
306
-    /**
307
-     * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
308
-     *
309
-     * @return EE_Base_Class[]|EE_Ticket[]
310
-     * @throws EE_Error
311
-     */
312
-    public function get_tickets_with_reservations()
313
-    {
314
-        return $this->get_all([['TKT_reserved' => ['>', 0]]]);
315
-    }
306
+	/**
307
+	 * returns an array of EE_Ticket objects with a non-zero value for TKT_reserved
308
+	 *
309
+	 * @return EE_Base_Class[]|EE_Ticket[]
310
+	 * @throws EE_Error
311
+	 */
312
+	public function get_tickets_with_reservations()
313
+	{
314
+		return $this->get_all([['TKT_reserved' => ['>', 0]]]);
315
+	}
316 316
 
317 317
 
318
-    /**
319
-     * returns an array of EE_Ticket objects matching the supplied list of IDs
320
-     *
321
-     * @param array $ticket_IDs
322
-     * @return EE_Base_Class[]|EE_Ticket[]
323
-     * @throws EE_Error
324
-     */
325
-    public function get_tickets_with_IDs(array $ticket_IDs)
326
-    {
327
-        return $this->get_all([['TKT_ID' => ['IN', $ticket_IDs]]]);
328
-    }
318
+	/**
319
+	 * returns an array of EE_Ticket objects matching the supplied list of IDs
320
+	 *
321
+	 * @param array $ticket_IDs
322
+	 * @return EE_Base_Class[]|EE_Ticket[]
323
+	 * @throws EE_Error
324
+	 */
325
+	public function get_tickets_with_IDs(array $ticket_IDs)
326
+	{
327
+		return $this->get_all([['TKT_ID' => ['IN', $ticket_IDs]]]);
328
+	}
329 329
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -197,23 +197,23 @@
 block discarded – undo
197 197
         ];
198 198
         // this model is generally available for reading
199 199
         $path_to_event                                            = 'Datetime.Event';
200
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public(
200
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Default_Public(
201 201
             'TKT_is_default',
202 202
             $path_to_event
203 203
         );
204 204
 
205 205
         // account for default tickets in the caps
206
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
206
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
207 207
             new EE_Restriction_Generator_Default_Protected(
208 208
                 'TKT_is_default',
209 209
                 $path_to_event
210 210
             );
211
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
211
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] =
212 212
             new EE_Restriction_Generator_Default_Protected(
213 213
                 'TKT_is_default',
214 214
                 $path_to_event
215 215
             );
216
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
216
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] =
217 217
             new EE_Restriction_Generator_Default_Protected(
218 218
                 'TKT_is_default',
219 219
                 $path_to_event
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6481 added lines, -6481 removed lines patch added patch discarded remove patch
@@ -35,6487 +35,6487 @@
 block discarded – undo
35 35
  */
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    protected static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    esc_html__(
561
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(esc_html__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            esc_html__(
680
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results
848
-     *                             different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            esc_html__(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(esc_html__(
1375
-                        'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(esc_html__(
1478
-                'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1679
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            $field_settings = $this->field_settings();
1790
-            // no primary key, just grab the first column
1791
-            $field = reset($field_settings);
1792
-            // don't need this array now
1793
-            unset($field_settings);
1794
-        }
1795
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
-        $select_expressions = $field->get_qualified_column();
1797
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1798
-        return $this->_do_wpdb_query('get_col', array($SQL));
1799
-    }
1800
-
1801
-
1802
-
1803
-    /**
1804
-     * Returns a single column value for a single row from the database
1805
-     *
1806
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1807
-     * @param string $field_to_select @see EEM_Base::get_col()
1808
-     * @return string
1809
-     * @throws EE_Error
1810
-     */
1811
-    public function get_var($query_params = array(), $field_to_select = null)
1812
-    {
1813
-        $query_params['limit'] = 1;
1814
-        $col = $this->get_col($query_params, $field_to_select);
1815
-        if (! empty($col)) {
1816
-            return reset($col);
1817
-        }
1818
-        return null;
1819
-    }
1820
-
1821
-
1822
-
1823
-    /**
1824
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1825
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1826
-     * injection, but currently no further filtering is done
1827
-     *
1828
-     * @global      $wpdb
1829
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1830
-     *                               be updated to in the DB
1831
-     * @return string of SQL
1832
-     * @throws EE_Error
1833
-     */
1834
-    public function _construct_update_sql($fields_n_values)
1835
-    {
1836
-        /** @type WPDB $wpdb */
1837
-        global $wpdb;
1838
-        $cols_n_values = array();
1839
-        foreach ($fields_n_values as $field_name => $value) {
1840
-            $field_obj = $this->field_settings_for($field_name);
1841
-            // if the value is NULL, we want to assign the value to that.
1842
-            // wpdb->prepare doesn't really handle that properly
1843
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844
-            $value_sql = $prepared_value === null ? 'NULL'
1845
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1847
-        }
1848
-        return implode(",", $cols_n_values);
1849
-    }
1850
-
1851
-
1852
-
1853
-    /**
1854
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1855
-     * Performs a HARD delete, meaning the database row should always be removed,
1856
-     * not just have a flag field on it switched
1857
-     * Wrapper for EEM_Base::delete_permanently()
1858
-     *
1859
-     * @param mixed $id
1860
-     * @param boolean $allow_blocking
1861
-     * @return int the number of rows deleted
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1865
-    {
1866
-        return $this->delete_permanently(
1867
-            array(
1868
-                array($this->get_primary_key_field()->get_name() => $id),
1869
-                'limit' => 1,
1870
-            ),
1871
-            $allow_blocking
1872
-        );
1873
-    }
1874
-
1875
-
1876
-
1877
-    /**
1878
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1879
-     * Wrapper for EEM_Base::delete()
1880
-     *
1881
-     * @param mixed $id
1882
-     * @param boolean $allow_blocking
1883
-     * @return int the number of rows deleted
1884
-     * @throws EE_Error
1885
-     */
1886
-    public function delete_by_ID($id, $allow_blocking = true)
1887
-    {
1888
-        return $this->delete(
1889
-            array(
1890
-                array($this->get_primary_key_field()->get_name() => $id),
1891
-                'limit' => 1,
1892
-            ),
1893
-            $allow_blocking
1894
-        );
1895
-    }
1896
-
1897
-
1898
-
1899
-    /**
1900
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1901
-     * meaning if the model has a field that indicates its been "trashed" or
1902
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1903
-     *
1904
-     * @see EEM_Base::delete_permanently
1905
-     * @param array   $query_params
1906
-     * @param boolean $allow_blocking
1907
-     * @return int how many rows got deleted
1908
-     * @throws EE_Error
1909
-     */
1910
-    public function delete($query_params, $allow_blocking = true)
1911
-    {
1912
-        return $this->delete_permanently($query_params, $allow_blocking);
1913
-    }
1914
-
1915
-
1916
-
1917
-    /**
1918
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1919
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1920
-     * as archived, not actually deleted
1921
-     *
1922
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1923
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1924
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1925
-     *                                deletes regardless of other objects which may depend on it. Its generally
1926
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1927
-     *                                DB
1928
-     * @return int how many rows got deleted
1929
-     * @throws EE_Error
1930
-     */
1931
-    public function delete_permanently($query_params, $allow_blocking = true)
1932
-    {
1933
-        /**
1934
-         * Action called just before performing a real deletion query. You can use the
1935
-         * model and its $query_params to find exactly which items will be deleted
1936
-         *
1937
-         * @param EEM_Base $model
1938
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1939
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1940
-         *                                 to block (prevent) this deletion
1941
-         */
1942
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1943
-        // some MySQL databases may be running safe mode, which may restrict
1944
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1945
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1946
-        // to delete them
1947
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1948
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1949
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1950
-            $columns_and_ids_for_deleting
1951
-        );
1952
-        /**
1953
-         * Allows client code to act on the items being deleted before the query is actually executed.
1954
-         *
1955
-         * @param EEM_Base $this  The model instance being acted on.
1956
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1957
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1958
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1959
-         *                                                  derived from the incoming query parameters.
1960
-         *                                                  @see details on the structure of this array in the phpdocs
1961
-         *                                                  for the `_get_ids_for_delete_method`
1962
-         *
1963
-         */
1964
-        do_action(
1965
-            'AHEE__EEM_Base__delete__before_query',
1966
-            $this,
1967
-            $query_params,
1968
-            $allow_blocking,
1969
-            $columns_and_ids_for_deleting
1970
-        );
1971
-        if ($deletion_where_query_part) {
1972
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
-            $table_aliases = array_keys($this->_tables);
1974
-            $SQL = "DELETE "
1975
-                   . implode(", ", $table_aliases)
1976
-                   . " FROM "
1977
-                   . $model_query_info->get_full_join_sql()
1978
-                   . " WHERE "
1979
-                   . $deletion_where_query_part;
1980
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
-        } else {
1982
-            $rows_deleted = 0;
1983
-        }
1984
-
1985
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
-        // there was no error with the delete query.
1987
-        if (
1988
-            $this->has_primary_key_field()
1989
-            && $rows_deleted !== false
1990
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1991
-        ) {
1992
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1993
-            foreach ($ids_for_removal as $id) {
1994
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1996
-                }
1997
-            }
1998
-
1999
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2000
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2001
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2002
-            // (although it is possible).
2003
-            // Note this can be skipped by using the provided filter and returning false.
2004
-            if (
2005
-                apply_filters(
2006
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2007
-                    ! $this instanceof EEM_Extra_Meta,
2008
-                    $this
2009
-                )
2010
-            ) {
2011
-                EEM_Extra_Meta::instance()->delete_permanently(
2012
-                    [
2013
-                        0 => [
2014
-                            'OBJ_ID'   => ['IN', $ids_for_removal],
2015
-                            'EXM_type' => $this->get_this_model_name(),
2016
-                        ]
2017
-                    ]
2018
-                );
2019
-            }
2020
-        }
2021
-
2022
-        /**
2023
-         * Action called just after performing a real deletion query. Although at this point the
2024
-         * items should have been deleted
2025
-         *
2026
-         * @param EEM_Base $model
2027
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2028
-         * @param int      $rows_deleted
2029
-         */
2030
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
-        return $rows_deleted;// how many supposedly got deleted
2032
-    }
2033
-
2034
-
2035
-
2036
-    /**
2037
-     * Checks all the relations that throw error messages when there are blocking related objects
2038
-     * for related model objects. If there are any related model objects on those relations,
2039
-     * adds an EE_Error, and return true
2040
-     *
2041
-     * @param EE_Base_Class|int $this_model_obj_or_id
2042
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2043
-     *                                                 should be ignored when determining whether there are related
2044
-     *                                                 model objects which block this model object's deletion. Useful
2045
-     *                                                 if you know A is related to B and are considering deleting A,
2046
-     *                                                 but want to see if A has any other objects blocking its deletion
2047
-     *                                                 before removing the relation between A and B
2048
-     * @return boolean
2049
-     * @throws EE_Error
2050
-     */
2051
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2052
-    {
2053
-        // first, if $ignore_this_model_obj was supplied, get its model
2054
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2055
-            $ignored_model = $ignore_this_model_obj->get_model();
2056
-        } else {
2057
-            $ignored_model = null;
2058
-        }
2059
-        // now check all the relations of $this_model_obj_or_id and see if there
2060
-        // are any related model objects blocking it?
2061
-        $is_blocked = false;
2062
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2063
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2064
-                // if $ignore_this_model_obj was supplied, then for the query
2065
-                // on that model needs to be told to ignore $ignore_this_model_obj
2066
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2067
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2068
-                        array(
2069
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2070
-                                '!=',
2071
-                                $ignore_this_model_obj->ID(),
2072
-                            ),
2073
-                        ),
2074
-                    ));
2075
-                } else {
2076
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2077
-                }
2078
-                if ($related_model_objects) {
2079
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2080
-                    $is_blocked = true;
2081
-                }
2082
-            }
2083
-        }
2084
-        return $is_blocked;
2085
-    }
2086
-
2087
-
2088
-    /**
2089
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2090
-     * @param array $row_results_for_deleting
2091
-     * @param bool  $allow_blocking
2092
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2093
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2094
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2095
-     *                 deleted. Example:
2096
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2097
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2098
-     *                 where each element is a group of columns and values that get deleted. Example:
2099
-     *                      array(
2100
-     *                          0 => array(
2101
-     *                              'Term_Relationship.object_id' => 1
2102
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2103
-     *                          ),
2104
-     *                          1 => array(
2105
-     *                              'Term_Relationship.object_id' => 1
2106
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2107
-     *                          )
2108
-     *                      )
2109
-     * @throws EE_Error
2110
-     */
2111
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2112
-    {
2113
-        $ids_to_delete_indexed_by_column = array();
2114
-        if ($this->has_primary_key_field()) {
2115
-            $primary_table = $this->_get_main_table();
2116
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2117
-            $other_tables = $this->_get_other_tables();
2118
-            $ids_to_delete_indexed_by_column = $query = array();
2119
-            foreach ($row_results_for_deleting as $item_to_delete) {
2120
-                // before we mark this item for deletion,
2121
-                // make sure there's no related entities blocking its deletion (if we're checking)
2122
-                if (
2123
-                    $allow_blocking
2124
-                    && $this->delete_is_blocked_by_related_models(
2125
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2126
-                    )
2127
-                ) {
2128
-                    continue;
2129
-                }
2130
-                // primary table deletes
2131
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2134
-                }
2135
-            }
2136
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2137
-            $fields = $this->get_combined_primary_key_fields();
2138
-            foreach ($row_results_for_deleting as $item_to_delete) {
2139
-                $ids_to_delete_indexed_by_column_for_row = array();
2140
-                foreach ($fields as $cpk_field) {
2141
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2142
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2144
-                    }
2145
-                }
2146
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2147
-            }
2148
-        } else {
2149
-            // so there's no primary key and no combined key...
2150
-            // sorry, can't help you
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2155
-                        "event_espresso"
2156
-                    ),
2157
-                    get_class($this)
2158
-                )
2159
-            );
2160
-        }
2161
-        return $ids_to_delete_indexed_by_column;
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2167
-     * the corresponding query_part for the query performing the delete.
2168
-     *
2169
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2170
-     * @return string
2171
-     * @throws EE_Error
2172
-     */
2173
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2174
-    {
2175
-        $query_part = '';
2176
-        if (empty($ids_to_delete_indexed_by_column)) {
2177
-            return $query_part;
2178
-        } elseif ($this->has_primary_key_field()) {
2179
-            $query = array();
2180
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2182
-            }
2183
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
-            $ways_to_identify_a_row = array();
2186
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
-                $values_for_each_combined_primary_key_for_a_row = array();
2188
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
-                }
2191
-                $ways_to_identify_a_row[] = '('
2192
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
-                                            . ')';
2194
-            }
2195
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2196
-        }
2197
-        return $query_part;
2198
-    }
2199
-
2200
-
2201
-
2202
-    /**
2203
-     * Gets the model field by the fully qualified name
2204
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
-     * @return EE_Model_Field_Base
2206
-     */
2207
-    public function get_field_by_column($qualified_column_name)
2208
-    {
2209
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
-                return $field_obj;
2212
-            }
2213
-        }
2214
-        throw new EE_Error(
2215
-            sprintf(
2216
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
-                $this->get_this_model_name(),
2218
-                $qualified_column_name
2219
-            )
2220
-        );
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Count all the rows that match criteria the model query params.
2227
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
-     * column
2229
-     *
2230
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
-     * @param string $field_to_count field on model to count by (not column name)
2232
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
-     *                               that by the setting $distinct to TRUE;
2234
-     * @return int
2235
-     * @throws EE_Error
2236
-     */
2237
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
-    {
2239
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
-        if ($field_to_count) {
2241
-            $field_obj = $this->field_settings_for($field_to_count);
2242
-            $column_to_count = $field_obj->get_qualified_column();
2243
-        } elseif ($this->has_primary_key_field()) {
2244
-            $pk_field_obj = $this->get_primary_key_field();
2245
-            $column_to_count = $pk_field_obj->get_qualified_column();
2246
-        } else {
2247
-            // there's no primary key
2248
-            // if we're counting distinct items, and there's no primary key,
2249
-            // we need to list out the columns for distinction;
2250
-            // otherwise we can just use star
2251
-            if ($distinct) {
2252
-                $columns_to_use = array();
2253
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2255
-                }
2256
-                $column_to_count = implode(',', $columns_to_use);
2257
-            } else {
2258
-                $column_to_count = '*';
2259
-            }
2260
-        }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
-    }
2265
-
2266
-
2267
-
2268
-    /**
2269
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
-     *
2271
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
-     * @param string $field_to_sum name of field (array key in $_fields array)
2273
-     * @return float
2274
-     * @throws EE_Error
2275
-     */
2276
-    public function sum($query_params, $field_to_sum = null)
2277
-    {
2278
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
-        if ($field_to_sum) {
2280
-            $field_obj = $this->field_settings_for($field_to_sum);
2281
-        } else {
2282
-            $field_obj = $this->get_primary_key_field();
2283
-        }
2284
-        $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
-        $data_type = $field_obj->get_wpdb_data_type();
2288
-        if ($data_type === '%d' || $data_type === '%s') {
2289
-            return (float) $return_value;
2290
-        }
2291
-        // must be %f
2292
-        return (float) $return_value;
2293
-    }
2294
-
2295
-
2296
-
2297
-    /**
2298
-     * Just calls the specified method on $wpdb with the given arguments
2299
-     * Consolidates a little extra error handling code
2300
-     *
2301
-     * @param string $wpdb_method
2302
-     * @param array  $arguments_to_provide
2303
-     * @throws EE_Error
2304
-     * @global wpdb  $wpdb
2305
-     * @return mixed
2306
-     */
2307
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        // if we're in maintenance mode level 2, DON'T run any queries
2310
-        // because level 2 indicates the database needs updating and
2311
-        // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
-            throw new EE_Error(sprintf(esc_html__(
2314
-                "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2315
-                "event_espresso"
2316
-            )));
2317
-        }
2318
-        /** @type WPDB $wpdb */
2319
-        global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2321
-            throw new EE_Error(sprintf(esc_html__(
2322
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2323
-                'event_espresso'
2324
-            ), $wpdb_method));
2325
-        }
2326
-        if (WP_DEBUG) {
2327
-            $old_show_errors_value = $wpdb->show_errors;
2328
-            $wpdb->show_errors(false);
2329
-        }
2330
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2332
-        if (WP_DEBUG) {
2333
-            $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2335
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
-            }
2337
-            if ($result === false) {
2338
-                throw new EE_Error(sprintf(esc_html__(
2339
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
-                    'event_espresso'
2341
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2342
-            }
2343
-        } elseif ($result === false) {
2344
-            EE_Error::add_error(
2345
-                sprintf(
2346
-                    esc_html__(
2347
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2348
-                        'event_espresso'
2349
-                    ),
2350
-                    $wpdb_method,
2351
-                    var_export($arguments_to_provide, true),
2352
-                    $wpdb->last_error
2353
-                ),
2354
-                __FILE__,
2355
-                __FUNCTION__,
2356
-                __LINE__
2357
-            );
2358
-        }
2359
-        return $result;
2360
-    }
2361
-
2362
-
2363
-
2364
-    /**
2365
-     * Attempts to run the indicated WPDB method with the provided arguments,
2366
-     * and if there's an error tries to verify the DB is correct. Uses
2367
-     * the static property EEM_Base::$_db_verification_level to determine whether
2368
-     * we should try to fix the EE core db, the addons, or just give up
2369
-     *
2370
-     * @param string $wpdb_method
2371
-     * @param array  $arguments_to_provide
2372
-     * @return mixed
2373
-     */
2374
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
-    {
2376
-        /** @type WPDB $wpdb */
2377
-        global $wpdb;
2378
-        $wpdb->last_error = null;
2379
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
-        // was there an error running the query? but we don't care on new activations
2381
-        // (we're going to setup the DB anyway on new activations)
2382
-        if (
2383
-            ($result === false || ! empty($wpdb->last_error))
2384
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
-        ) {
2386
-            switch (EEM_Base::$_db_verification_level) {
2387
-                case EEM_Base::db_verified_none:
2388
-                    // let's double-check core's DB
2389
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
-                    break;
2391
-                case EEM_Base::db_verified_core:
2392
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
-                    break;
2395
-                case EEM_Base::db_verified_addons:
2396
-                    // ummmm... you in trouble
2397
-                    return $result;
2398
-                    break;
2399
-            }
2400
-            if (! empty($error_message)) {
2401
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
-                trigger_error($error_message);
2403
-            }
2404
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
-        }
2406
-        return $result;
2407
-    }
2408
-
2409
-
2410
-
2411
-    /**
2412
-     * Verifies the EE core database is up-to-date and records that we've done it on
2413
-     * EEM_Base::$_db_verification_level
2414
-     *
2415
-     * @param string $wpdb_method
2416
-     * @param array  $arguments_to_provide
2417
-     * @return string
2418
-     */
2419
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
-    {
2421
-        /** @type WPDB $wpdb */
2422
-        global $wpdb;
2423
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2424
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
-        $error_message = sprintf(
2426
-            esc_html__(
2427
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
-                'event_espresso'
2429
-            ),
2430
-            $wpdb->last_error,
2431
-            $wpdb_method,
2432
-            wp_json_encode($arguments_to_provide)
2433
-        );
2434
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
-        return $error_message;
2436
-    }
2437
-
2438
-
2439
-
2440
-    /**
2441
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
-     * EEM_Base::$_db_verification_level
2443
-     *
2444
-     * @param $wpdb_method
2445
-     * @param $arguments_to_provide
2446
-     * @return string
2447
-     */
2448
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
-    {
2450
-        /** @type WPDB $wpdb */
2451
-        global $wpdb;
2452
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
-        $error_message = sprintf(
2455
-            esc_html__(
2456
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
-                'event_espresso'
2458
-            ),
2459
-            $wpdb->last_error,
2460
-            $wpdb_method,
2461
-            wp_json_encode($arguments_to_provide)
2462
-        );
2463
-        EE_System::instance()->initialize_addons();
2464
-        return $error_message;
2465
-    }
2466
-
2467
-
2468
-
2469
-    /**
2470
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
-     * ..."
2474
-     *
2475
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2476
-     * @return string
2477
-     */
2478
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
-    {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2485
-               $model_query_info->get_limit_sql();
2486
-    }
2487
-
2488
-
2489
-
2490
-    /**
2491
-     * Set to easily debug the next X queries ran from this model.
2492
-     *
2493
-     * @param int $count
2494
-     */
2495
-    public function show_next_x_db_queries($count = 1)
2496
-    {
2497
-        $this->_show_next_x_db_queries = $count;
2498
-    }
2499
-
2500
-
2501
-
2502
-    /**
2503
-     * @param $sql_query
2504
-     */
2505
-    public function show_db_query_if_previously_requested($sql_query)
2506
-    {
2507
-        if ($this->_show_next_x_db_queries > 0) {
2508
-            echo esc_html($sql_query);
2509
-            $this->_show_next_x_db_queries--;
2510
-        }
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
-     * There are the 3 cases:
2518
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
-     * $otherModelObject has no ID, it is first saved.
2520
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
-     * has no ID, it is first saved.
2522
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
-     * join table
2525
-     *
2526
-     * @param        EE_Base_Class                     /int $thisModelObject
2527
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
-     * @param string $relationName                     , key in EEM_Base::_relations
2529
-     *                                                 an attendee to a group, you also want to specify which role they
2530
-     *                                                 will have in that group. So you would use this parameter to
2531
-     *                                                 specify array('role-column-name'=>'role-id')
2532
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
-     *                                                 to for relation to methods that allow you to further specify
2534
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
-     *                                                 because these will be inserted in any new rows created as well.
2537
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
-     * @throws EE_Error
2539
-     */
2540
-    public function add_relationship_to(
2541
-        $id_or_obj,
2542
-        $other_model_id_or_obj,
2543
-        $relationName,
2544
-        $extra_join_model_fields_n_values = array()
2545
-    ) {
2546
-        $relation_obj = $this->related_settings_for($relationName);
2547
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
-    }
2549
-
2550
-
2551
-
2552
-    /**
2553
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
-     * There are the 3 cases:
2555
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
-     * error
2557
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
-     * an error
2559
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
-     *
2561
-     * @param        EE_Base_Class /int $id_or_obj
2562
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
-     * @param string $relationName key in EEM_Base::_relations
2564
-     * @return boolean of success
2565
-     * @throws EE_Error
2566
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
-     *                             because these will be inserted in any new rows created as well.
2570
-     */
2571
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
-    {
2573
-        $relation_obj = $this->related_settings_for($relationName);
2574
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * @param mixed           $id_or_obj
2581
-     * @param string          $relationName
2582
-     * @param array           $where_query_params
2583
-     * @param EE_Base_Class[] objects to which relations were removed
2584
-     * @return \EE_Base_Class[]
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
-    {
2589
-        $relation_obj = $this->related_settings_for($relationName);
2590
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
-    }
2592
-
2593
-
2594
-
2595
-    /**
2596
-     * Gets all the related items of the specified $model_name, using $query_params.
2597
-     * Note: by default, we remove the "default query params"
2598
-     * because we want to get even deleted items etc.
2599
-     *
2600
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
-     * @return EE_Base_Class[]
2604
-     * @throws EE_Error
2605
-     */
2606
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
-    {
2608
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2609
-        $relation_settings = $this->related_settings_for($model_name);
2610
-        return $relation_settings->get_all_related($model_obj, $query_params);
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Deletes all the model objects across the relation indicated by $model_name
2617
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2619
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
-     *
2621
-     * @param EE_Base_Class|int|string $id_or_obj
2622
-     * @param string                   $model_name
2623
-     * @param array                    $query_params
2624
-     * @return int how many deleted
2625
-     * @throws EE_Error
2626
-     */
2627
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
-    {
2629
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2630
-        $relation_settings = $this->related_settings_for($model_name);
2631
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2632
-    }
2633
-
2634
-
2635
-
2636
-    /**
2637
-     * Hard deletes all the model objects across the relation indicated by $model_name
2638
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
-     * the model objects can't be hard deleted because of blocking related model objects,
2640
-     * just does a soft-delete on them instead.
2641
-     *
2642
-     * @param EE_Base_Class|int|string $id_or_obj
2643
-     * @param string                   $model_name
2644
-     * @param array                    $query_params
2645
-     * @return int how many deleted
2646
-     * @throws EE_Error
2647
-     */
2648
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
-    {
2650
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2651
-        $relation_settings = $this->related_settings_for($model_name);
2652
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
-    }
2654
-
2655
-
2656
-
2657
-    /**
2658
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
-     * unless otherwise specified in the $query_params
2660
-     *
2661
-     * @param        int             /EE_Base_Class $id_or_obj
2662
-     * @param string $model_name     like 'Event', or 'Registration'
2663
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2665
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
-     *                               that by the setting $distinct to TRUE;
2667
-     * @return int
2668
-     * @throws EE_Error
2669
-     */
2670
-    public function count_related(
2671
-        $id_or_obj,
2672
-        $model_name,
2673
-        $query_params = array(),
2674
-        $field_to_count = null,
2675
-        $distinct = false
2676
-    ) {
2677
-        $related_model = $this->get_related_model_obj($model_name);
2678
-        // we're just going to use the query params on the related model's normal get_all query,
2679
-        // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2681
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
-        }
2683
-        $this_model_name = $this->get_this_model_name();
2684
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
-        return $related_model->count($query_params, $field_to_count, $distinct);
2687
-    }
2688
-
2689
-
2690
-
2691
-    /**
2692
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
-     *
2695
-     * @param        int           /EE_Base_Class $id_or_obj
2696
-     * @param string $model_name   like 'Event', or 'Registration'
2697
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
-     * @return float
2700
-     * @throws EE_Error
2701
-     */
2702
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
-    {
2704
-        $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2706
-            EE_Error::doing_it_wrong(
2707
-                'EEM_Base::sum_related',
2708
-                sprintf(
2709
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
-                    gettype($query_params)
2711
-                ),
2712
-                '4.6.0'
2713
-            );
2714
-            $query_params = array();
2715
-        }
2716
-        // we're just going to use the query params on the related model's normal get_all query,
2717
-        // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2719
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
-        }
2721
-        $this_model_name = $this->get_this_model_name();
2722
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
-        return $related_model->sum($query_params, $field_to_sum);
2725
-    }
2726
-
2727
-
2728
-
2729
-    /**
2730
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
-     * $modelObject
2732
-     *
2733
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
-     * @return EE_Base_Class
2737
-     * @throws EE_Error
2738
-     */
2739
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
-    {
2741
-        $query_params['limit'] = 1;
2742
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
-        if ($results) {
2744
-            return array_shift($results);
2745
-        }
2746
-        return null;
2747
-    }
2748
-
2749
-
2750
-
2751
-    /**
2752
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
-     *
2754
-     * @return string
2755
-     */
2756
-    public function get_this_model_name()
2757
-    {
2758
-        return str_replace("EEM_", "", get_class($this));
2759
-    }
2760
-
2761
-
2762
-
2763
-    /**
2764
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
-     *
2766
-     * @return EE_Any_Foreign_Model_Name_Field
2767
-     * @throws EE_Error
2768
-     */
2769
-    public function get_field_containing_related_model_name()
2770
-    {
2771
-        foreach ($this->field_settings(true) as $field) {
2772
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
-                $field_with_model_name = $field;
2774
-            }
2775
-        }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
-            throw new EE_Error(sprintf(
2778
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
-                $this->get_this_model_name()
2780
-            ));
2781
-        }
2782
-        return $field_with_model_name;
2783
-    }
2784
-
2785
-
2786
-
2787
-    /**
2788
-     * Inserts a new entry into the database, for each table.
2789
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
-     *
2796
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
-     *                              of EEM_Base)
2800
-     * @return int|string new primary key on main table that got inserted
2801
-     * @throws EE_Error
2802
-     */
2803
-    public function insert($field_n_values)
2804
-    {
2805
-        /**
2806
-         * Filters the fields and their values before inserting an item using the models
2807
-         *
2808
-         * @param array    $fields_n_values keys are the fields and values are their new values
2809
-         * @param EEM_Base $model           the model used
2810
-         */
2811
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
-            $main_table = $this->_get_main_table();
2814
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
-            if ($new_id !== false) {
2816
-                foreach ($this->_get_other_tables() as $other_table) {
2817
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
-                }
2819
-            }
2820
-            /**
2821
-             * Done just after attempting to insert a new model object
2822
-             *
2823
-             * @param EEM_Base   $model           used
2824
-             * @param array      $fields_n_values fields and their values
2825
-             * @param int|string the              ID of the newly-inserted model object
2826
-             */
2827
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
-            return $new_id;
2829
-        }
2830
-        return false;
2831
-    }
2832
-
2833
-
2834
-
2835
-    /**
2836
-     * Checks that the result would satisfy the unique indexes on this model
2837
-     *
2838
-     * @param array  $field_n_values
2839
-     * @param string $action
2840
-     * @return boolean
2841
-     * @throws EE_Error
2842
-     */
2843
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
-    {
2845
-        foreach ($this->unique_indexes() as $index_name => $index) {
2846
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
-            if ($this->exists(array($uniqueness_where_params))) {
2848
-                EE_Error::add_error(
2849
-                    sprintf(
2850
-                        esc_html__(
2851
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
-                            "event_espresso"
2853
-                        ),
2854
-                        $action,
2855
-                        $this->_get_class_name(),
2856
-                        $index_name,
2857
-                        implode(",", $index->field_names()),
2858
-                        http_build_query($uniqueness_where_params)
2859
-                    ),
2860
-                    __FILE__,
2861
-                    __FUNCTION__,
2862
-                    __LINE__
2863
-                );
2864
-                return false;
2865
-            }
2866
-        }
2867
-        return true;
2868
-    }
2869
-
2870
-
2871
-
2872
-    /**
2873
-     * Checks the database for an item that conflicts (ie, if this item were
2874
-     * saved to the DB would break some uniqueness requirement, like a primary key
2875
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
-     * can be either an EE_Base_Class or an array of fields n values
2877
-     *
2878
-     * @param EE_Base_Class|array $obj_or_fields_array
2879
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2880
-     *                                                 when looking for conflicts
2881
-     *                                                 (ie, if false, we ignore the model object's primary key
2882
-     *                                                 when finding "conflicts". If true, it's also considered).
2883
-     *                                                 Only works for INT primary key,
2884
-     *                                                 STRING primary keys cannot be ignored
2885
-     * @throws EE_Error
2886
-     * @return EE_Base_Class|array
2887
-     */
2888
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
-    {
2890
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2892
-        } elseif (is_array($obj_or_fields_array)) {
2893
-            $fields_n_values = $obj_or_fields_array;
2894
-        } else {
2895
-            throw new EE_Error(
2896
-                sprintf(
2897
-                    esc_html__(
2898
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
-                        "event_espresso"
2900
-                    ),
2901
-                    get_class($this),
2902
-                    $obj_or_fields_array
2903
-                )
2904
-            );
2905
-        }
2906
-        $query_params = array();
2907
-        if (
2908
-            $this->has_primary_key_field()
2909
-            && ($include_primary_key
2910
-                || $this->get_primary_key_field()
2911
-                   instanceof
2912
-                   EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2914
-        ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
-        }
2917
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
-        }
2921
-        // if there is nothing to base this search on, then we shouldn't find anything
2922
-        if (empty($query_params)) {
2923
-            return array();
2924
-        }
2925
-        return $this->get_one($query_params);
2926
-    }
2927
-
2928
-
2929
-
2930
-    /**
2931
-     * Like count, but is optimized and returns a boolean instead of an int
2932
-     *
2933
-     * @param array $query_params
2934
-     * @return boolean
2935
-     * @throws EE_Error
2936
-     */
2937
-    public function exists($query_params)
2938
-    {
2939
-        $query_params['limit'] = 1;
2940
-        return $this->count($query_params) > 0;
2941
-    }
2942
-
2943
-
2944
-
2945
-    /**
2946
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
-     *
2948
-     * @param int|string $id
2949
-     * @return boolean
2950
-     * @throws EE_Error
2951
-     */
2952
-    public function exists_by_ID($id)
2953
-    {
2954
-        return $this->exists(
2955
-            array(
2956
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
-                array(
2958
-                    $this->primary_key_name() => $id,
2959
-                ),
2960
-            )
2961
-        );
2962
-    }
2963
-
2964
-
2965
-
2966
-    /**
2967
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
-     * on the main table)
2971
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
-     * cases where we want to call it directly rather than via insert().
2973
-     *
2974
-     * @access   protected
2975
-     * @param EE_Table_Base $table
2976
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
-     *                                       float
2978
-     * @param int           $new_id          for now we assume only int keys
2979
-     * @throws EE_Error
2980
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
-     * @return int ID of new row inserted, or FALSE on failure
2982
-     */
2983
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
-    {
2985
-        global $wpdb;
2986
-        $insertion_col_n_values = array();
2987
-        $format_for_insertion = array();
2988
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
-        foreach ($fields_on_table as $field_name => $field_obj) {
2990
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
-            if ($field_obj->is_auto_increment()) {
2992
-                continue;
2993
-            }
2994
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
-            if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
-            }
3000
-        }
3001
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3002
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3003
-            // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
-        }
3007
-        // insert the new entry
3008
-        $result = $this->_do_wpdb_query(
3009
-            'insert',
3010
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
-        );
3012
-        if ($result === false) {
3013
-            return false;
3014
-        }
3015
-        // ok, now what do we return for the ID of the newly-inserted thing?
3016
-        if ($this->has_primary_key_field()) {
3017
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3018
-                return $wpdb->insert_id;
3019
-            }
3020
-            // it's not an auto-increment primary key, so
3021
-            // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
-        }
3024
-        // we can't return a  primary key because there is none. instead return
3025
-        // a unique string indicating this model
3026
-        return $this->get_index_primary_key_string($fields_n_values);
3027
-    }
3028
-
3029
-
3030
-
3031
-    /**
3032
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
-     * and there is no default, we pass it along. WPDB will take care of it)
3035
-     *
3036
-     * @param EE_Model_Field_Base $field_obj
3037
-     * @param array               $fields_n_values
3038
-     * @return mixed string|int|float depending on what the table column will be expecting
3039
-     * @throws EE_Error
3040
-     */
3041
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
-    {
3043
-        // if this field doesn't allow nullable, don't allow it
3044
-        if (
3045
-            ! $field_obj->is_nullable()
3046
-            && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3049
-            )
3050
-        ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
-        }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3055
-            : null;
3056
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
-    }
3058
-
3059
-
3060
-
3061
-    /**
3062
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
-     * the field's prepare_for_set() method.
3065
-     *
3066
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
-     *                                   top of file)
3069
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
-     *                                   $value is a custom selection
3071
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
-     */
3073
-    private function _prepare_value_for_use_in_db($value, $field)
3074
-    {
3075
-        if ($field && $field instanceof EE_Model_Field_Base) {
3076
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
-            switch ($this->_values_already_prepared_by_model_object) {
3078
-                /** @noinspection PhpMissingBreakStatementInspection */
3079
-                case self::not_prepared_by_model_object:
3080
-                    $value = $field->prepare_for_set($value);
3081
-                // purposefully left out "return"
3082
-                case self::prepared_by_model_object:
3083
-                    /** @noinspection SuspiciousAssignmentsInspection */
3084
-                    $value = $field->prepare_for_use_in_db($value);
3085
-                case self::prepared_for_use_in_db:
3086
-                    // leave the value alone
3087
-            }
3088
-            return $value;
3089
-            // phpcs:enable
3090
-        }
3091
-        return $value;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Returns the main table on this model
3098
-     *
3099
-     * @return EE_Primary_Table
3100
-     * @throws EE_Error
3101
-     */
3102
-    protected function _get_main_table()
3103
-    {
3104
-        foreach ($this->_tables as $table) {
3105
-            if ($table instanceof EE_Primary_Table) {
3106
-                return $table;
3107
-            }
3108
-        }
3109
-        throw new EE_Error(sprintf(esc_html__(
3110
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
-            'event_espresso'
3112
-        ), get_class($this)));
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * table
3119
-     * returns EE_Primary_Table table name
3120
-     *
3121
-     * @return string
3122
-     * @throws EE_Error
3123
-     */
3124
-    public function table()
3125
-    {
3126
-        return $this->_get_main_table()->get_table_name();
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * table
3133
-     * returns first EE_Secondary_Table table name
3134
-     *
3135
-     * @return string
3136
-     */
3137
-    public function second_table()
3138
-    {
3139
-        // grab second table from tables array
3140
-        $second_table = end($this->_tables);
3141
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * get_table_obj_by_alias
3148
-     * returns table name given it's alias
3149
-     *
3150
-     * @param string $table_alias
3151
-     * @return EE_Primary_Table | EE_Secondary_Table
3152
-     */
3153
-    public function get_table_obj_by_alias($table_alias = '')
3154
-    {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
-     *
3163
-     * @return EE_Secondary_Table[]
3164
-     */
3165
-    protected function _get_other_tables()
3166
-    {
3167
-        $other_tables = array();
3168
-        foreach ($this->_tables as $table_alias => $table) {
3169
-            if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3171
-            }
3172
-        }
3173
-        return $other_tables;
3174
-    }
3175
-
3176
-
3177
-
3178
-    /**
3179
-     * Finds all the fields that correspond to the given table
3180
-     *
3181
-     * @param string $table_alias , array key in EEM_Base::_tables
3182
-     * @return EE_Model_Field_Base[]
3183
-     */
3184
-    public function _get_fields_for_table($table_alias)
3185
-    {
3186
-        return $this->_fields[ $table_alias ];
3187
-    }
3188
-
3189
-
3190
-
3191
-    /**
3192
-     * Recurses through all the where parameters, and finds all the related models we'll need
3193
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
-     * related Registration, Transaction, and Payment models.
3197
-     *
3198
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     * @throws EE_Error
3201
-     */
3202
-    public function _extract_related_models_from_query($query_params)
3203
-    {
3204
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
-        if (array_key_exists(0, $query_params)) {
3206
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
-        }
3208
-        if (array_key_exists('group_by', $query_params)) {
3209
-            if (is_array($query_params['group_by'])) {
3210
-                $this->_extract_related_models_from_sub_params_array_values(
3211
-                    $query_params['group_by'],
3212
-                    $query_info_carrier,
3213
-                    'group_by'
3214
-                );
3215
-            } elseif (! empty($query_params['group_by'])) {
3216
-                $this->_extract_related_model_info_from_query_param(
3217
-                    $query_params['group_by'],
3218
-                    $query_info_carrier,
3219
-                    'group_by'
3220
-                );
3221
-            }
3222
-        }
3223
-        if (array_key_exists('having', $query_params)) {
3224
-            $this->_extract_related_models_from_sub_params_array_keys(
3225
-                $query_params[0],
3226
-                $query_info_carrier,
3227
-                'having'
3228
-            );
3229
-        }
3230
-        if (array_key_exists('order_by', $query_params)) {
3231
-            if (is_array($query_params['order_by'])) {
3232
-                $this->_extract_related_models_from_sub_params_array_keys(
3233
-                    $query_params['order_by'],
3234
-                    $query_info_carrier,
3235
-                    'order_by'
3236
-                );
3237
-            } elseif (! empty($query_params['order_by'])) {
3238
-                $this->_extract_related_model_info_from_query_param(
3239
-                    $query_params['order_by'],
3240
-                    $query_info_carrier,
3241
-                    'order_by'
3242
-                );
3243
-            }
3244
-        }
3245
-        if (array_key_exists('force_join', $query_params)) {
3246
-            $this->_extract_related_models_from_sub_params_array_values(
3247
-                $query_params['force_join'],
3248
-                $query_info_carrier,
3249
-                'force_join'
3250
-            );
3251
-        }
3252
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
-        return $query_info_carrier;
3254
-    }
3255
-
3256
-
3257
-
3258
-    /**
3259
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
-     *
3261
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3262
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3264
-     * @throws EE_Error
3265
-     * @return \EE_Model_Query_Info_Carrier
3266
-     */
3267
-    private function _extract_related_models_from_sub_params_array_keys(
3268
-        $sub_query_params,
3269
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
-        $query_param_type
3271
-    ) {
3272
-        if (! empty($sub_query_params)) {
3273
-            $sub_query_params = (array) $sub_query_params;
3274
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
-                $this->_extract_related_model_info_from_query_param(
3277
-                    $param,
3278
-                    $model_query_info_carrier,
3279
-                    $query_param_type
3280
-                );
3281
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
-                // of array('Registration.TXN_ID'=>23)
3285
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3288
-                        throw new EE_Error(sprintf(
3289
-                            esc_html__(
3290
-                                "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3291
-                                "event_espresso"
3292
-                            ),
3293
-                            $param,
3294
-                            $possibly_array_of_params
3295
-                        ));
3296
-                    }
3297
-                    $this->_extract_related_models_from_sub_params_array_keys(
3298
-                        $possibly_array_of_params,
3299
-                        $model_query_info_carrier,
3300
-                        $query_param_type
3301
-                    );
3302
-                } elseif (
3303
-                    $query_param_type === 0 // ie WHERE
3304
-                          && is_array($possibly_array_of_params)
3305
-                          && isset($possibly_array_of_params[2])
3306
-                          && $possibly_array_of_params[2] == true
3307
-                ) {
3308
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3310
-                    // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
-                        throw new EE_Error(sprintf(esc_html__(
3313
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
-                            "event_espresso"
3315
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3316
-                    }
3317
-                    $this->_extract_related_model_info_from_query_param(
3318
-                        $possibly_array_of_params[1],
3319
-                        $model_query_info_carrier,
3320
-                        $query_param_type
3321
-                    );
3322
-                }
3323
-            }
3324
-        }
3325
-        return $model_query_info_carrier;
3326
-    }
3327
-
3328
-
3329
-
3330
-    /**
3331
-     * For extracting related models from forced_joins, where the array values contain the info about what
3332
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
-     *
3334
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3335
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3337
-     * @throws EE_Error
3338
-     * @return \EE_Model_Query_Info_Carrier
3339
-     */
3340
-    private function _extract_related_models_from_sub_params_array_values(
3341
-        $sub_query_params,
3342
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
-        $query_param_type
3344
-    ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3347
-                throw new EE_Error(sprintf(
3348
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
-                    $sub_query_params
3350
-                ));
3351
-            }
3352
-            foreach ($sub_query_params as $param) {
3353
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
-                $this->_extract_related_model_info_from_query_param(
3355
-                    $param,
3356
-                    $model_query_info_carrier,
3357
-                    $query_param_type
3358
-                );
3359
-            }
3360
-        }
3361
-        return $model_query_info_carrier;
3362
-    }
3363
-
3364
-
3365
-    /**
3366
-     * Extract all the query parts from  model query params
3367
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
-     * but use them in a different order. Eg, we need to know what models we are querying
3370
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
-     * other models before we can finalize the where clause SQL.
3372
-     *
3373
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
-     * @throws EE_Error
3375
-     * @return EE_Model_Query_Info_Carrier
3376
-     * @throws ModelConfigurationException
3377
-     */
3378
-    public function _create_model_query_info_carrier($query_params)
3379
-    {
3380
-        if (! is_array($query_params)) {
3381
-            EE_Error::doing_it_wrong(
3382
-                'EEM_Base::_create_model_query_info_carrier',
3383
-                sprintf(
3384
-                    esc_html__(
3385
-                        '$query_params should be an array, you passed a variable of type %s',
3386
-                        'event_espresso'
3387
-                    ),
3388
-                    gettype($query_params)
3389
-                ),
3390
-                '4.6.0'
3391
-            );
3392
-            $query_params = array();
3393
-        }
3394
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
-        // first check if we should alter the query to account for caps or not
3396
-        // because the caps might require us to do extra joins
3397
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
-            $query_params[0] = array_replace_recursive(
3399
-                $query_params[0],
3400
-                $this->caps_where_conditions(
3401
-                    $query_params['caps']
3402
-                )
3403
-            );
3404
-        }
3405
-
3406
-        // check if we should alter the query to remove data related to protected
3407
-        // custom post types
3408
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
-            $where_param_key_for_password = $this->modelChainAndPassword();
3410
-            // only include if related to a cpt where no password has been set
3411
-            $query_params[0]['OR*nopassword'] = array(
3412
-                $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3414
-            );
3415
-        }
3416
-        $query_object = $this->_extract_related_models_from_query($query_params);
3417
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
-        foreach ($query_params[0] as $key => $value) {
3419
-            if (is_int($key)) {
3420
-                throw new EE_Error(
3421
-                    sprintf(
3422
-                        esc_html__(
3423
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3424
-                            "event_espresso"
3425
-                        ),
3426
-                        $key,
3427
-                        var_export($value, true),
3428
-                        var_export($query_params, true),
3429
-                        get_class($this)
3430
-                    )
3431
-                );
3432
-            }
3433
-        }
3434
-        if (
3435
-            array_key_exists('default_where_conditions', $query_params)
3436
-            && ! empty($query_params['default_where_conditions'])
3437
-        ) {
3438
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3439
-        } else {
3440
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
-        }
3442
-        $query_params[0] = array_merge(
3443
-            $this->_get_default_where_conditions_for_models_in_query(
3444
-                $query_object,
3445
-                $use_default_where_conditions,
3446
-                $query_params[0]
3447
-            ),
3448
-            $query_params[0]
3449
-        );
3450
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
-        // So we need to setup a subquery and use that for the main join.
3453
-        // Note for now this only works on the primary table for the model.
3454
-        // So for instance, you could set the limit array like this:
3455
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
-            $query_object->set_main_model_join_sql(
3458
-                $this->_construct_limit_join_select(
3459
-                    $query_params['on_join_limit'][0],
3460
-                    $query_params['on_join_limit'][1]
3461
-                )
3462
-            );
3463
-        }
3464
-        // set limit
3465
-        if (array_key_exists('limit', $query_params)) {
3466
-            if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
-                    $e = sprintf(
3469
-                        esc_html__(
3470
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3471
-                            "event_espresso"
3472
-                        ),
3473
-                        http_build_query($query_params['limit'])
3474
-                    );
3475
-                    throw new EE_Error($e . "|" . $e);
3476
-                }
3477
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
-            }
3482
-        }
3483
-        // set order by
3484
-        if (array_key_exists('order_by', $query_params)) {
3485
-            if (is_array($query_params['order_by'])) {
3486
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
-                if (array_key_exists('order', $query_params)) {
3490
-                    throw new EE_Error(
3491
-                        sprintf(
3492
-                            esc_html__(
3493
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3494
-                                "event_espresso"
3495
-                            ),
3496
-                            get_class($this),
3497
-                            implode(", ", array_keys($query_params['order_by'])),
3498
-                            implode(", ", $query_params['order_by']),
3499
-                            $query_params['order']
3500
-                        )
3501
-                    );
3502
-                }
3503
-                $this->_extract_related_models_from_sub_params_array_keys(
3504
-                    $query_params['order_by'],
3505
-                    $query_object,
3506
-                    'order_by'
3507
-                );
3508
-                // assume it's an array of fields to order by
3509
-                $order_array = array();
3510
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
-                    $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
-                }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3516
-                $this->_extract_related_model_info_from_query_param(
3517
-                    $query_params['order_by'],
3518
-                    $query_object,
3519
-                    'order',
3520
-                    $query_params['order_by']
3521
-                );
3522
-                $order = isset($query_params['order'])
3523
-                    ? $this->_extract_order($query_params['order'])
3524
-                    : 'DESC';
3525
-                $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
-                );
3528
-            }
3529
-        }
3530
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
-        if (
3532
-            ! array_key_exists('order_by', $query_params)
3533
-            && array_key_exists('order', $query_params)
3534
-            && ! empty($query_params['order'])
3535
-        ) {
3536
-            $pk_field = $this->get_primary_key_field();
3537
-            $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
-        }
3540
-        // set group by
3541
-        if (array_key_exists('group_by', $query_params)) {
3542
-            if (is_array($query_params['group_by'])) {
3543
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3544
-                $group_by_array = array();
3545
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
-                }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3550
-                $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
-                );
3553
-            }
3554
-        }
3555
-        // set having
3556
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
-        }
3559
-        // now, just verify they didn't pass anything wack
3560
-        foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
-                throw new EE_Error(
3563
-                    sprintf(
3564
-                        esc_html__(
3565
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
-                            'event_espresso'
3567
-                        ),
3568
-                        $query_key,
3569
-                        get_class($this),
3570
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3571
-                        implode(',', $this->_allowed_query_params)
3572
-                    )
3573
-                );
3574
-            }
3575
-        }
3576
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3577
-        if (empty($main_model_join_sql)) {
3578
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
-        }
3580
-        return $query_object;
3581
-    }
3582
-
3583
-
3584
-
3585
-    /**
3586
-     * Gets the where conditions that should be imposed on the query based on the
3587
-     * context (eg reading frontend, backend, edit or delete).
3588
-     *
3589
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3590
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
-     * @throws EE_Error
3592
-     */
3593
-    public function caps_where_conditions($context = self::caps_read)
3594
-    {
3595
-        EEM_Base::verify_is_valid_cap_context($context);
3596
-        $cap_where_conditions = array();
3597
-        $cap_restrictions = $this->caps_missing($context);
3598
-        /**
3599
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
-         */
3601
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
-            $cap_where_conditions = array_replace_recursive(
3603
-                $cap_where_conditions,
3604
-                $restriction_if_no_cap->get_default_where_conditions()
3605
-            );
3606
-        }
3607
-        return apply_filters(
3608
-            'FHEE__EEM_Base__caps_where_conditions__return',
3609
-            $cap_where_conditions,
3610
-            $this,
3611
-            $context,
3612
-            $cap_restrictions
3613
-        );
3614
-    }
3615
-
3616
-
3617
-
3618
-    /**
3619
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
-     * otherwise throws an exception
3621
-     *
3622
-     * @param string $should_be_order_string
3623
-     * @return string either ASC, asc, DESC or desc
3624
-     * @throws EE_Error
3625
-     */
3626
-    private function _extract_order($should_be_order_string)
3627
-    {
3628
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
-            return $should_be_order_string;
3630
-        }
3631
-        throw new EE_Error(
3632
-            sprintf(
3633
-                esc_html__(
3634
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
-                    "event_espresso"
3636
-                ),
3637
-                get_class($this),
3638
-                $should_be_order_string
3639
-            )
3640
-        );
3641
-    }
3642
-
3643
-
3644
-
3645
-    /**
3646
-     * Looks at all the models which are included in this query, and asks each
3647
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
-     * so they can be merged
3649
-     *
3650
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
-     *                                                                  'none' means NO default where conditions will
3653
-     *                                                                  be used AT ALL during this query.
3654
-     *                                                                  'other_models_only' means default where
3655
-     *                                                                  conditions from other models will be used, but
3656
-     *                                                                  not for this primary model. 'all', the default,
3657
-     *                                                                  means default where conditions will apply as
3658
-     *                                                                  normal
3659
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     * @throws EE_Error
3661
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
-     */
3663
-    private function _get_default_where_conditions_for_models_in_query(
3664
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3665
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
-        $where_query_params = array()
3667
-    ) {
3668
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
-            throw new EE_Error(sprintf(
3671
-                esc_html__(
3672
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
-                    "event_espresso"
3674
-                ),
3675
-                $use_default_where_conditions,
3676
-                implode(", ", $allowed_used_default_where_conditions_values)
3677
-            ));
3678
-        }
3679
-        $universal_query_params = array();
3680
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_default_where_conditions();
3682
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
-            $universal_query_params = $this->_get_minimum_where_conditions();
3684
-        }
3685
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
-            $related_model = $this->get_related_model_obj($model_name);
3687
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
-            } else {
3692
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3693
-                continue;
3694
-            }
3695
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3696
-                $related_model_universal_where_params,
3697
-                $where_query_params,
3698
-                $related_model,
3699
-                $model_relation_path
3700
-            );
3701
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
-                $universal_query_params,
3703
-                $overrides
3704
-            );
3705
-        }
3706
-        return $universal_query_params;
3707
-    }
3708
-
3709
-
3710
-
3711
-    /**
3712
-     * Determines whether or not we should use default where conditions for the model in question
3713
-     * (this model, or other related models).
3714
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
-     * We should use default where conditions on related models when they requested to use default where conditions
3717
-     * on all models, or specifically just on other related models
3718
-     * @param      $default_where_conditions_value
3719
-     * @param bool $for_this_model false means this is for OTHER related models
3720
-     * @return bool
3721
-     */
3722
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
-    {
3724
-        return (
3725
-                   $for_this_model
3726
-                   && in_array(
3727
-                       $default_where_conditions_value,
3728
-                       array(
3729
-                           EEM_Base::default_where_conditions_all,
3730
-                           EEM_Base::default_where_conditions_this_only,
3731
-                           EEM_Base::default_where_conditions_minimum_others,
3732
-                       ),
3733
-                       true
3734
-                   )
3735
-               )
3736
-               || (
3737
-                   ! $for_this_model
3738
-                   && in_array(
3739
-                       $default_where_conditions_value,
3740
-                       array(
3741
-                           EEM_Base::default_where_conditions_all,
3742
-                           EEM_Base::default_where_conditions_others_only,
3743
-                       ),
3744
-                       true
3745
-                   )
3746
-               );
3747
-    }
3748
-
3749
-    /**
3750
-     * Determines whether or not we should use default minimum conditions for the model in question
3751
-     * (this model, or other related models).
3752
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
-     * where conditions.
3754
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
-     * on this model or others
3756
-     * @param      $default_where_conditions_value
3757
-     * @param bool $for_this_model false means this is for OTHER related models
3758
-     * @return bool
3759
-     */
3760
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
-    {
3762
-        return (
3763
-                   $for_this_model
3764
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
-               )
3766
-               || (
3767
-                   ! $for_this_model
3768
-                   && in_array(
3769
-                       $default_where_conditions_value,
3770
-                       array(
3771
-                           EEM_Base::default_where_conditions_minimum_others,
3772
-                           EEM_Base::default_where_conditions_minimum_all,
3773
-                       ),
3774
-                       true
3775
-                   )
3776
-               );
3777
-    }
3778
-
3779
-
3780
-    /**
3781
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
-     * then we also add a special where condition which allows for that model's primary key
3783
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
-     *
3786
-     * @param array    $default_where_conditions
3787
-     * @param array    $provided_where_conditions
3788
-     * @param EEM_Base $model
3789
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3790
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
-     * @throws EE_Error
3792
-     */
3793
-    private function _override_defaults_or_make_null_friendly(
3794
-        $default_where_conditions,
3795
-        $provided_where_conditions,
3796
-        $model,
3797
-        $model_relation_path
3798
-    ) {
3799
-        $null_friendly_where_conditions = array();
3800
-        $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
-        foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3804
-                $none_overridden = false;
3805
-            } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
-            }
3808
-        }
3809
-        if ($none_overridden && $default_where_conditions) {
3810
-            if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
-                                                                                . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3814
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	protected static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					esc_html__(
561
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(esc_html__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							esc_html__(
680
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results
848
+	 *                             different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							esc_html__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(esc_html__(
1375
+						'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(esc_html__(
1478
+				'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1679
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			$field_settings = $this->field_settings();
1790
+			// no primary key, just grab the first column
1791
+			$field = reset($field_settings);
1792
+			// don't need this array now
1793
+			unset($field_settings);
1794
+		}
1795
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1796
+		$select_expressions = $field->get_qualified_column();
1797
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1798
+		return $this->_do_wpdb_query('get_col', array($SQL));
1799
+	}
1800
+
1801
+
1802
+
1803
+	/**
1804
+	 * Returns a single column value for a single row from the database
1805
+	 *
1806
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1807
+	 * @param string $field_to_select @see EEM_Base::get_col()
1808
+	 * @return string
1809
+	 * @throws EE_Error
1810
+	 */
1811
+	public function get_var($query_params = array(), $field_to_select = null)
1812
+	{
1813
+		$query_params['limit'] = 1;
1814
+		$col = $this->get_col($query_params, $field_to_select);
1815
+		if (! empty($col)) {
1816
+			return reset($col);
1817
+		}
1818
+		return null;
1819
+	}
1820
+
1821
+
1822
+
1823
+	/**
1824
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1825
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1826
+	 * injection, but currently no further filtering is done
1827
+	 *
1828
+	 * @global      $wpdb
1829
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1830
+	 *                               be updated to in the DB
1831
+	 * @return string of SQL
1832
+	 * @throws EE_Error
1833
+	 */
1834
+	public function _construct_update_sql($fields_n_values)
1835
+	{
1836
+		/** @type WPDB $wpdb */
1837
+		global $wpdb;
1838
+		$cols_n_values = array();
1839
+		foreach ($fields_n_values as $field_name => $value) {
1840
+			$field_obj = $this->field_settings_for($field_name);
1841
+			// if the value is NULL, we want to assign the value to that.
1842
+			// wpdb->prepare doesn't really handle that properly
1843
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844
+			$value_sql = $prepared_value === null ? 'NULL'
1845
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1847
+		}
1848
+		return implode(",", $cols_n_values);
1849
+	}
1850
+
1851
+
1852
+
1853
+	/**
1854
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1855
+	 * Performs a HARD delete, meaning the database row should always be removed,
1856
+	 * not just have a flag field on it switched
1857
+	 * Wrapper for EEM_Base::delete_permanently()
1858
+	 *
1859
+	 * @param mixed $id
1860
+	 * @param boolean $allow_blocking
1861
+	 * @return int the number of rows deleted
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1865
+	{
1866
+		return $this->delete_permanently(
1867
+			array(
1868
+				array($this->get_primary_key_field()->get_name() => $id),
1869
+				'limit' => 1,
1870
+			),
1871
+			$allow_blocking
1872
+		);
1873
+	}
1874
+
1875
+
1876
+
1877
+	/**
1878
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1879
+	 * Wrapper for EEM_Base::delete()
1880
+	 *
1881
+	 * @param mixed $id
1882
+	 * @param boolean $allow_blocking
1883
+	 * @return int the number of rows deleted
1884
+	 * @throws EE_Error
1885
+	 */
1886
+	public function delete_by_ID($id, $allow_blocking = true)
1887
+	{
1888
+		return $this->delete(
1889
+			array(
1890
+				array($this->get_primary_key_field()->get_name() => $id),
1891
+				'limit' => 1,
1892
+			),
1893
+			$allow_blocking
1894
+		);
1895
+	}
1896
+
1897
+
1898
+
1899
+	/**
1900
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1901
+	 * meaning if the model has a field that indicates its been "trashed" or
1902
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1903
+	 *
1904
+	 * @see EEM_Base::delete_permanently
1905
+	 * @param array   $query_params
1906
+	 * @param boolean $allow_blocking
1907
+	 * @return int how many rows got deleted
1908
+	 * @throws EE_Error
1909
+	 */
1910
+	public function delete($query_params, $allow_blocking = true)
1911
+	{
1912
+		return $this->delete_permanently($query_params, $allow_blocking);
1913
+	}
1914
+
1915
+
1916
+
1917
+	/**
1918
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1919
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1920
+	 * as archived, not actually deleted
1921
+	 *
1922
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1923
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1924
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1925
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1926
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1927
+	 *                                DB
1928
+	 * @return int how many rows got deleted
1929
+	 * @throws EE_Error
1930
+	 */
1931
+	public function delete_permanently($query_params, $allow_blocking = true)
1932
+	{
1933
+		/**
1934
+		 * Action called just before performing a real deletion query. You can use the
1935
+		 * model and its $query_params to find exactly which items will be deleted
1936
+		 *
1937
+		 * @param EEM_Base $model
1938
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1939
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1940
+		 *                                 to block (prevent) this deletion
1941
+		 */
1942
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1943
+		// some MySQL databases may be running safe mode, which may restrict
1944
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1945
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1946
+		// to delete them
1947
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1948
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1949
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1950
+			$columns_and_ids_for_deleting
1951
+		);
1952
+		/**
1953
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1954
+		 *
1955
+		 * @param EEM_Base $this  The model instance being acted on.
1956
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1957
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1958
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1959
+		 *                                                  derived from the incoming query parameters.
1960
+		 *                                                  @see details on the structure of this array in the phpdocs
1961
+		 *                                                  for the `_get_ids_for_delete_method`
1962
+		 *
1963
+		 */
1964
+		do_action(
1965
+			'AHEE__EEM_Base__delete__before_query',
1966
+			$this,
1967
+			$query_params,
1968
+			$allow_blocking,
1969
+			$columns_and_ids_for_deleting
1970
+		);
1971
+		if ($deletion_where_query_part) {
1972
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
+			$table_aliases = array_keys($this->_tables);
1974
+			$SQL = "DELETE "
1975
+				   . implode(", ", $table_aliases)
1976
+				   . " FROM "
1977
+				   . $model_query_info->get_full_join_sql()
1978
+				   . " WHERE "
1979
+				   . $deletion_where_query_part;
1980
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
+		} else {
1982
+			$rows_deleted = 0;
1983
+		}
1984
+
1985
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
+		// there was no error with the delete query.
1987
+		if (
1988
+			$this->has_primary_key_field()
1989
+			&& $rows_deleted !== false
1990
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1991
+		) {
1992
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1993
+			foreach ($ids_for_removal as $id) {
1994
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1996
+				}
1997
+			}
1998
+
1999
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2000
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2001
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2002
+			// (although it is possible).
2003
+			// Note this can be skipped by using the provided filter and returning false.
2004
+			if (
2005
+				apply_filters(
2006
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2007
+					! $this instanceof EEM_Extra_Meta,
2008
+					$this
2009
+				)
2010
+			) {
2011
+				EEM_Extra_Meta::instance()->delete_permanently(
2012
+					[
2013
+						0 => [
2014
+							'OBJ_ID'   => ['IN', $ids_for_removal],
2015
+							'EXM_type' => $this->get_this_model_name(),
2016
+						]
2017
+					]
2018
+				);
2019
+			}
2020
+		}
2021
+
2022
+		/**
2023
+		 * Action called just after performing a real deletion query. Although at this point the
2024
+		 * items should have been deleted
2025
+		 *
2026
+		 * @param EEM_Base $model
2027
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2028
+		 * @param int      $rows_deleted
2029
+		 */
2030
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
+		return $rows_deleted;// how many supposedly got deleted
2032
+	}
2033
+
2034
+
2035
+
2036
+	/**
2037
+	 * Checks all the relations that throw error messages when there are blocking related objects
2038
+	 * for related model objects. If there are any related model objects on those relations,
2039
+	 * adds an EE_Error, and return true
2040
+	 *
2041
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2042
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2043
+	 *                                                 should be ignored when determining whether there are related
2044
+	 *                                                 model objects which block this model object's deletion. Useful
2045
+	 *                                                 if you know A is related to B and are considering deleting A,
2046
+	 *                                                 but want to see if A has any other objects blocking its deletion
2047
+	 *                                                 before removing the relation between A and B
2048
+	 * @return boolean
2049
+	 * @throws EE_Error
2050
+	 */
2051
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2052
+	{
2053
+		// first, if $ignore_this_model_obj was supplied, get its model
2054
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2055
+			$ignored_model = $ignore_this_model_obj->get_model();
2056
+		} else {
2057
+			$ignored_model = null;
2058
+		}
2059
+		// now check all the relations of $this_model_obj_or_id and see if there
2060
+		// are any related model objects blocking it?
2061
+		$is_blocked = false;
2062
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2063
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2064
+				// if $ignore_this_model_obj was supplied, then for the query
2065
+				// on that model needs to be told to ignore $ignore_this_model_obj
2066
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2067
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2068
+						array(
2069
+							$ignored_model->get_primary_key_field()->get_name() => array(
2070
+								'!=',
2071
+								$ignore_this_model_obj->ID(),
2072
+							),
2073
+						),
2074
+					));
2075
+				} else {
2076
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2077
+				}
2078
+				if ($related_model_objects) {
2079
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2080
+					$is_blocked = true;
2081
+				}
2082
+			}
2083
+		}
2084
+		return $is_blocked;
2085
+	}
2086
+
2087
+
2088
+	/**
2089
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2090
+	 * @param array $row_results_for_deleting
2091
+	 * @param bool  $allow_blocking
2092
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2093
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2094
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2095
+	 *                 deleted. Example:
2096
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2097
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2098
+	 *                 where each element is a group of columns and values that get deleted. Example:
2099
+	 *                      array(
2100
+	 *                          0 => array(
2101
+	 *                              'Term_Relationship.object_id' => 1
2102
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2103
+	 *                          ),
2104
+	 *                          1 => array(
2105
+	 *                              'Term_Relationship.object_id' => 1
2106
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2107
+	 *                          )
2108
+	 *                      )
2109
+	 * @throws EE_Error
2110
+	 */
2111
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2112
+	{
2113
+		$ids_to_delete_indexed_by_column = array();
2114
+		if ($this->has_primary_key_field()) {
2115
+			$primary_table = $this->_get_main_table();
2116
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2117
+			$other_tables = $this->_get_other_tables();
2118
+			$ids_to_delete_indexed_by_column = $query = array();
2119
+			foreach ($row_results_for_deleting as $item_to_delete) {
2120
+				// before we mark this item for deletion,
2121
+				// make sure there's no related entities blocking its deletion (if we're checking)
2122
+				if (
2123
+					$allow_blocking
2124
+					&& $this->delete_is_blocked_by_related_models(
2125
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2126
+					)
2127
+				) {
2128
+					continue;
2129
+				}
2130
+				// primary table deletes
2131
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2134
+				}
2135
+			}
2136
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2137
+			$fields = $this->get_combined_primary_key_fields();
2138
+			foreach ($row_results_for_deleting as $item_to_delete) {
2139
+				$ids_to_delete_indexed_by_column_for_row = array();
2140
+				foreach ($fields as $cpk_field) {
2141
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2142
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2144
+					}
2145
+				}
2146
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2147
+			}
2148
+		} else {
2149
+			// so there's no primary key and no combined key...
2150
+			// sorry, can't help you
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2155
+						"event_espresso"
2156
+					),
2157
+					get_class($this)
2158
+				)
2159
+			);
2160
+		}
2161
+		return $ids_to_delete_indexed_by_column;
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2167
+	 * the corresponding query_part for the query performing the delete.
2168
+	 *
2169
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2170
+	 * @return string
2171
+	 * @throws EE_Error
2172
+	 */
2173
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2174
+	{
2175
+		$query_part = '';
2176
+		if (empty($ids_to_delete_indexed_by_column)) {
2177
+			return $query_part;
2178
+		} elseif ($this->has_primary_key_field()) {
2179
+			$query = array();
2180
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2182
+			}
2183
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
+			$ways_to_identify_a_row = array();
2186
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187
+				$values_for_each_combined_primary_key_for_a_row = array();
2188
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2190
+				}
2191
+				$ways_to_identify_a_row[] = '('
2192
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2193
+											. ')';
2194
+			}
2195
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2196
+		}
2197
+		return $query_part;
2198
+	}
2199
+
2200
+
2201
+
2202
+	/**
2203
+	 * Gets the model field by the fully qualified name
2204
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2205
+	 * @return EE_Model_Field_Base
2206
+	 */
2207
+	public function get_field_by_column($qualified_column_name)
2208
+	{
2209
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2210
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2211
+				return $field_obj;
2212
+			}
2213
+		}
2214
+		throw new EE_Error(
2215
+			sprintf(
2216
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2217
+				$this->get_this_model_name(),
2218
+				$qualified_column_name
2219
+			)
2220
+		);
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Count all the rows that match criteria the model query params.
2227
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2228
+	 * column
2229
+	 *
2230
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2231
+	 * @param string $field_to_count field on model to count by (not column name)
2232
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2233
+	 *                               that by the setting $distinct to TRUE;
2234
+	 * @return int
2235
+	 * @throws EE_Error
2236
+	 */
2237
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2238
+	{
2239
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2240
+		if ($field_to_count) {
2241
+			$field_obj = $this->field_settings_for($field_to_count);
2242
+			$column_to_count = $field_obj->get_qualified_column();
2243
+		} elseif ($this->has_primary_key_field()) {
2244
+			$pk_field_obj = $this->get_primary_key_field();
2245
+			$column_to_count = $pk_field_obj->get_qualified_column();
2246
+		} else {
2247
+			// there's no primary key
2248
+			// if we're counting distinct items, and there's no primary key,
2249
+			// we need to list out the columns for distinction;
2250
+			// otherwise we can just use star
2251
+			if ($distinct) {
2252
+				$columns_to_use = array();
2253
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2254
+					$columns_to_use[] = $field_obj->get_qualified_column();
2255
+				}
2256
+				$column_to_count = implode(',', $columns_to_use);
2257
+			} else {
2258
+				$column_to_count = '*';
2259
+			}
2260
+		}
2261
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2263
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264
+	}
2265
+
2266
+
2267
+
2268
+	/**
2269
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2270
+	 *
2271
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2272
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2273
+	 * @return float
2274
+	 * @throws EE_Error
2275
+	 */
2276
+	public function sum($query_params, $field_to_sum = null)
2277
+	{
2278
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2279
+		if ($field_to_sum) {
2280
+			$field_obj = $this->field_settings_for($field_to_sum);
2281
+		} else {
2282
+			$field_obj = $this->get_primary_key_field();
2283
+		}
2284
+		$column_to_count = $field_obj->get_qualified_column();
2285
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2286
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287
+		$data_type = $field_obj->get_wpdb_data_type();
2288
+		if ($data_type === '%d' || $data_type === '%s') {
2289
+			return (float) $return_value;
2290
+		}
2291
+		// must be %f
2292
+		return (float) $return_value;
2293
+	}
2294
+
2295
+
2296
+
2297
+	/**
2298
+	 * Just calls the specified method on $wpdb with the given arguments
2299
+	 * Consolidates a little extra error handling code
2300
+	 *
2301
+	 * @param string $wpdb_method
2302
+	 * @param array  $arguments_to_provide
2303
+	 * @throws EE_Error
2304
+	 * @global wpdb  $wpdb
2305
+	 * @return mixed
2306
+	 */
2307
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		// if we're in maintenance mode level 2, DON'T run any queries
2310
+		// because level 2 indicates the database needs updating and
2311
+		// is probably out of sync with the code
2312
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2313
+			throw new EE_Error(sprintf(esc_html__(
2314
+				"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2315
+				"event_espresso"
2316
+			)));
2317
+		}
2318
+		/** @type WPDB $wpdb */
2319
+		global $wpdb;
2320
+		if (! method_exists($wpdb, $wpdb_method)) {
2321
+			throw new EE_Error(sprintf(esc_html__(
2322
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2323
+				'event_espresso'
2324
+			), $wpdb_method));
2325
+		}
2326
+		if (WP_DEBUG) {
2327
+			$old_show_errors_value = $wpdb->show_errors;
2328
+			$wpdb->show_errors(false);
2329
+		}
2330
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2332
+		if (WP_DEBUG) {
2333
+			$wpdb->show_errors($old_show_errors_value);
2334
+			if (! empty($wpdb->last_error)) {
2335
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336
+			}
2337
+			if ($result === false) {
2338
+				throw new EE_Error(sprintf(esc_html__(
2339
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2340
+					'event_espresso'
2341
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2342
+			}
2343
+		} elseif ($result === false) {
2344
+			EE_Error::add_error(
2345
+				sprintf(
2346
+					esc_html__(
2347
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2348
+						'event_espresso'
2349
+					),
2350
+					$wpdb_method,
2351
+					var_export($arguments_to_provide, true),
2352
+					$wpdb->last_error
2353
+				),
2354
+				__FILE__,
2355
+				__FUNCTION__,
2356
+				__LINE__
2357
+			);
2358
+		}
2359
+		return $result;
2360
+	}
2361
+
2362
+
2363
+
2364
+	/**
2365
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2366
+	 * and if there's an error tries to verify the DB is correct. Uses
2367
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2368
+	 * we should try to fix the EE core db, the addons, or just give up
2369
+	 *
2370
+	 * @param string $wpdb_method
2371
+	 * @param array  $arguments_to_provide
2372
+	 * @return mixed
2373
+	 */
2374
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2375
+	{
2376
+		/** @type WPDB $wpdb */
2377
+		global $wpdb;
2378
+		$wpdb->last_error = null;
2379
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2380
+		// was there an error running the query? but we don't care on new activations
2381
+		// (we're going to setup the DB anyway on new activations)
2382
+		if (
2383
+			($result === false || ! empty($wpdb->last_error))
2384
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2385
+		) {
2386
+			switch (EEM_Base::$_db_verification_level) {
2387
+				case EEM_Base::db_verified_none:
2388
+					// let's double-check core's DB
2389
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2390
+					break;
2391
+				case EEM_Base::db_verified_core:
2392
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2393
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2394
+					break;
2395
+				case EEM_Base::db_verified_addons:
2396
+					// ummmm... you in trouble
2397
+					return $result;
2398
+					break;
2399
+			}
2400
+			if (! empty($error_message)) {
2401
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402
+				trigger_error($error_message);
2403
+			}
2404
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2405
+		}
2406
+		return $result;
2407
+	}
2408
+
2409
+
2410
+
2411
+	/**
2412
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2413
+	 * EEM_Base::$_db_verification_level
2414
+	 *
2415
+	 * @param string $wpdb_method
2416
+	 * @param array  $arguments_to_provide
2417
+	 * @return string
2418
+	 */
2419
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2420
+	{
2421
+		/** @type WPDB $wpdb */
2422
+		global $wpdb;
2423
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2424
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2425
+		$error_message = sprintf(
2426
+			esc_html__(
2427
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
+				'event_espresso'
2429
+			),
2430
+			$wpdb->last_error,
2431
+			$wpdb_method,
2432
+			wp_json_encode($arguments_to_provide)
2433
+		);
2434
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2435
+		return $error_message;
2436
+	}
2437
+
2438
+
2439
+
2440
+	/**
2441
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2442
+	 * EEM_Base::$_db_verification_level
2443
+	 *
2444
+	 * @param $wpdb_method
2445
+	 * @param $arguments_to_provide
2446
+	 * @return string
2447
+	 */
2448
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2449
+	{
2450
+		/** @type WPDB $wpdb */
2451
+		global $wpdb;
2452
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2453
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2454
+		$error_message = sprintf(
2455
+			esc_html__(
2456
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2457
+				'event_espresso'
2458
+			),
2459
+			$wpdb->last_error,
2460
+			$wpdb_method,
2461
+			wp_json_encode($arguments_to_provide)
2462
+		);
2463
+		EE_System::instance()->initialize_addons();
2464
+		return $error_message;
2465
+	}
2466
+
2467
+
2468
+
2469
+	/**
2470
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2471
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2472
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2473
+	 * ..."
2474
+	 *
2475
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2476
+	 * @return string
2477
+	 */
2478
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479
+	{
2480
+		return " FROM " . $model_query_info->get_full_join_sql() .
2481
+			   $model_query_info->get_where_sql() .
2482
+			   $model_query_info->get_group_by_sql() .
2483
+			   $model_query_info->get_having_sql() .
2484
+			   $model_query_info->get_order_by_sql() .
2485
+			   $model_query_info->get_limit_sql();
2486
+	}
2487
+
2488
+
2489
+
2490
+	/**
2491
+	 * Set to easily debug the next X queries ran from this model.
2492
+	 *
2493
+	 * @param int $count
2494
+	 */
2495
+	public function show_next_x_db_queries($count = 1)
2496
+	{
2497
+		$this->_show_next_x_db_queries = $count;
2498
+	}
2499
+
2500
+
2501
+
2502
+	/**
2503
+	 * @param $sql_query
2504
+	 */
2505
+	public function show_db_query_if_previously_requested($sql_query)
2506
+	{
2507
+		if ($this->_show_next_x_db_queries > 0) {
2508
+			echo esc_html($sql_query);
2509
+			$this->_show_next_x_db_queries--;
2510
+		}
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2517
+	 * There are the 3 cases:
2518
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2519
+	 * $otherModelObject has no ID, it is first saved.
2520
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2521
+	 * has no ID, it is first saved.
2522
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2523
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2524
+	 * join table
2525
+	 *
2526
+	 * @param        EE_Base_Class                     /int $thisModelObject
2527
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2528
+	 * @param string $relationName                     , key in EEM_Base::_relations
2529
+	 *                                                 an attendee to a group, you also want to specify which role they
2530
+	 *                                                 will have in that group. So you would use this parameter to
2531
+	 *                                                 specify array('role-column-name'=>'role-id')
2532
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2533
+	 *                                                 to for relation to methods that allow you to further specify
2534
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2535
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2536
+	 *                                                 because these will be inserted in any new rows created as well.
2537
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2538
+	 * @throws EE_Error
2539
+	 */
2540
+	public function add_relationship_to(
2541
+		$id_or_obj,
2542
+		$other_model_id_or_obj,
2543
+		$relationName,
2544
+		$extra_join_model_fields_n_values = array()
2545
+	) {
2546
+		$relation_obj = $this->related_settings_for($relationName);
2547
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2548
+	}
2549
+
2550
+
2551
+
2552
+	/**
2553
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2554
+	 * There are the 3 cases:
2555
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2556
+	 * error
2557
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2558
+	 * an error
2559
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2560
+	 *
2561
+	 * @param        EE_Base_Class /int $id_or_obj
2562
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2563
+	 * @param string $relationName key in EEM_Base::_relations
2564
+	 * @return boolean of success
2565
+	 * @throws EE_Error
2566
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2567
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2568
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2569
+	 *                             because these will be inserted in any new rows created as well.
2570
+	 */
2571
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2572
+	{
2573
+		$relation_obj = $this->related_settings_for($relationName);
2574
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * @param mixed           $id_or_obj
2581
+	 * @param string          $relationName
2582
+	 * @param array           $where_query_params
2583
+	 * @param EE_Base_Class[] objects to which relations were removed
2584
+	 * @return \EE_Base_Class[]
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2588
+	{
2589
+		$relation_obj = $this->related_settings_for($relationName);
2590
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2591
+	}
2592
+
2593
+
2594
+
2595
+	/**
2596
+	 * Gets all the related items of the specified $model_name, using $query_params.
2597
+	 * Note: by default, we remove the "default query params"
2598
+	 * because we want to get even deleted items etc.
2599
+	 *
2600
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2601
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2602
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2603
+	 * @return EE_Base_Class[]
2604
+	 * @throws EE_Error
2605
+	 */
2606
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2607
+	{
2608
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2609
+		$relation_settings = $this->related_settings_for($model_name);
2610
+		return $relation_settings->get_all_related($model_obj, $query_params);
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Deletes all the model objects across the relation indicated by $model_name
2617
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2618
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2619
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2620
+	 *
2621
+	 * @param EE_Base_Class|int|string $id_or_obj
2622
+	 * @param string                   $model_name
2623
+	 * @param array                    $query_params
2624
+	 * @return int how many deleted
2625
+	 * @throws EE_Error
2626
+	 */
2627
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2628
+	{
2629
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2630
+		$relation_settings = $this->related_settings_for($model_name);
2631
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2632
+	}
2633
+
2634
+
2635
+
2636
+	/**
2637
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2638
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2639
+	 * the model objects can't be hard deleted because of blocking related model objects,
2640
+	 * just does a soft-delete on them instead.
2641
+	 *
2642
+	 * @param EE_Base_Class|int|string $id_or_obj
2643
+	 * @param string                   $model_name
2644
+	 * @param array                    $query_params
2645
+	 * @return int how many deleted
2646
+	 * @throws EE_Error
2647
+	 */
2648
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2649
+	{
2650
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2651
+		$relation_settings = $this->related_settings_for($model_name);
2652
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2653
+	}
2654
+
2655
+
2656
+
2657
+	/**
2658
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2659
+	 * unless otherwise specified in the $query_params
2660
+	 *
2661
+	 * @param        int             /EE_Base_Class $id_or_obj
2662
+	 * @param string $model_name     like 'Event', or 'Registration'
2663
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2664
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2665
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2666
+	 *                               that by the setting $distinct to TRUE;
2667
+	 * @return int
2668
+	 * @throws EE_Error
2669
+	 */
2670
+	public function count_related(
2671
+		$id_or_obj,
2672
+		$model_name,
2673
+		$query_params = array(),
2674
+		$field_to_count = null,
2675
+		$distinct = false
2676
+	) {
2677
+		$related_model = $this->get_related_model_obj($model_name);
2678
+		// we're just going to use the query params on the related model's normal get_all query,
2679
+		// except add a condition to say to match the current mod
2680
+		if (! isset($query_params['default_where_conditions'])) {
2681
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
+		}
2683
+		$this_model_name = $this->get_this_model_name();
2684
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2686
+		return $related_model->count($query_params, $field_to_count, $distinct);
2687
+	}
2688
+
2689
+
2690
+
2691
+	/**
2692
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2693
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2694
+	 *
2695
+	 * @param        int           /EE_Base_Class $id_or_obj
2696
+	 * @param string $model_name   like 'Event', or 'Registration'
2697
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2698
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2699
+	 * @return float
2700
+	 * @throws EE_Error
2701
+	 */
2702
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703
+	{
2704
+		$related_model = $this->get_related_model_obj($model_name);
2705
+		if (! is_array($query_params)) {
2706
+			EE_Error::doing_it_wrong(
2707
+				'EEM_Base::sum_related',
2708
+				sprintf(
2709
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2710
+					gettype($query_params)
2711
+				),
2712
+				'4.6.0'
2713
+			);
2714
+			$query_params = array();
2715
+		}
2716
+		// we're just going to use the query params on the related model's normal get_all query,
2717
+		// except add a condition to say to match the current mod
2718
+		if (! isset($query_params['default_where_conditions'])) {
2719
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720
+		}
2721
+		$this_model_name = $this->get_this_model_name();
2722
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2724
+		return $related_model->sum($query_params, $field_to_sum);
2725
+	}
2726
+
2727
+
2728
+
2729
+	/**
2730
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2731
+	 * $modelObject
2732
+	 *
2733
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2734
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2735
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2736
+	 * @return EE_Base_Class
2737
+	 * @throws EE_Error
2738
+	 */
2739
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2740
+	{
2741
+		$query_params['limit'] = 1;
2742
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2743
+		if ($results) {
2744
+			return array_shift($results);
2745
+		}
2746
+		return null;
2747
+	}
2748
+
2749
+
2750
+
2751
+	/**
2752
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2753
+	 *
2754
+	 * @return string
2755
+	 */
2756
+	public function get_this_model_name()
2757
+	{
2758
+		return str_replace("EEM_", "", get_class($this));
2759
+	}
2760
+
2761
+
2762
+
2763
+	/**
2764
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2765
+	 *
2766
+	 * @return EE_Any_Foreign_Model_Name_Field
2767
+	 * @throws EE_Error
2768
+	 */
2769
+	public function get_field_containing_related_model_name()
2770
+	{
2771
+		foreach ($this->field_settings(true) as $field) {
2772
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2773
+				$field_with_model_name = $field;
2774
+			}
2775
+		}
2776
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2777
+			throw new EE_Error(sprintf(
2778
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779
+				$this->get_this_model_name()
2780
+			));
2781
+		}
2782
+		return $field_with_model_name;
2783
+	}
2784
+
2785
+
2786
+
2787
+	/**
2788
+	 * Inserts a new entry into the database, for each table.
2789
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2790
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2791
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2792
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2793
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2794
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2795
+	 *
2796
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2797
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2798
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2799
+	 *                              of EEM_Base)
2800
+	 * @return int|string new primary key on main table that got inserted
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	public function insert($field_n_values)
2804
+	{
2805
+		/**
2806
+		 * Filters the fields and their values before inserting an item using the models
2807
+		 *
2808
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2809
+		 * @param EEM_Base $model           the model used
2810
+		 */
2811
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2812
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2813
+			$main_table = $this->_get_main_table();
2814
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2815
+			if ($new_id !== false) {
2816
+				foreach ($this->_get_other_tables() as $other_table) {
2817
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2818
+				}
2819
+			}
2820
+			/**
2821
+			 * Done just after attempting to insert a new model object
2822
+			 *
2823
+			 * @param EEM_Base   $model           used
2824
+			 * @param array      $fields_n_values fields and their values
2825
+			 * @param int|string the              ID of the newly-inserted model object
2826
+			 */
2827
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2828
+			return $new_id;
2829
+		}
2830
+		return false;
2831
+	}
2832
+
2833
+
2834
+
2835
+	/**
2836
+	 * Checks that the result would satisfy the unique indexes on this model
2837
+	 *
2838
+	 * @param array  $field_n_values
2839
+	 * @param string $action
2840
+	 * @return boolean
2841
+	 * @throws EE_Error
2842
+	 */
2843
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2844
+	{
2845
+		foreach ($this->unique_indexes() as $index_name => $index) {
2846
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2847
+			if ($this->exists(array($uniqueness_where_params))) {
2848
+				EE_Error::add_error(
2849
+					sprintf(
2850
+						esc_html__(
2851
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2852
+							"event_espresso"
2853
+						),
2854
+						$action,
2855
+						$this->_get_class_name(),
2856
+						$index_name,
2857
+						implode(",", $index->field_names()),
2858
+						http_build_query($uniqueness_where_params)
2859
+					),
2860
+					__FILE__,
2861
+					__FUNCTION__,
2862
+					__LINE__
2863
+				);
2864
+				return false;
2865
+			}
2866
+		}
2867
+		return true;
2868
+	}
2869
+
2870
+
2871
+
2872
+	/**
2873
+	 * Checks the database for an item that conflicts (ie, if this item were
2874
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2875
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2876
+	 * can be either an EE_Base_Class or an array of fields n values
2877
+	 *
2878
+	 * @param EE_Base_Class|array $obj_or_fields_array
2879
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2880
+	 *                                                 when looking for conflicts
2881
+	 *                                                 (ie, if false, we ignore the model object's primary key
2882
+	 *                                                 when finding "conflicts". If true, it's also considered).
2883
+	 *                                                 Only works for INT primary key,
2884
+	 *                                                 STRING primary keys cannot be ignored
2885
+	 * @throws EE_Error
2886
+	 * @return EE_Base_Class|array
2887
+	 */
2888
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2889
+	{
2890
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2891
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2892
+		} elseif (is_array($obj_or_fields_array)) {
2893
+			$fields_n_values = $obj_or_fields_array;
2894
+		} else {
2895
+			throw new EE_Error(
2896
+				sprintf(
2897
+					esc_html__(
2898
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2899
+						"event_espresso"
2900
+					),
2901
+					get_class($this),
2902
+					$obj_or_fields_array
2903
+				)
2904
+			);
2905
+		}
2906
+		$query_params = array();
2907
+		if (
2908
+			$this->has_primary_key_field()
2909
+			&& ($include_primary_key
2910
+				|| $this->get_primary_key_field()
2911
+				   instanceof
2912
+				   EE_Primary_Key_String_Field)
2913
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2914
+		) {
2915
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2916
+		}
2917
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2920
+		}
2921
+		// if there is nothing to base this search on, then we shouldn't find anything
2922
+		if (empty($query_params)) {
2923
+			return array();
2924
+		}
2925
+		return $this->get_one($query_params);
2926
+	}
2927
+
2928
+
2929
+
2930
+	/**
2931
+	 * Like count, but is optimized and returns a boolean instead of an int
2932
+	 *
2933
+	 * @param array $query_params
2934
+	 * @return boolean
2935
+	 * @throws EE_Error
2936
+	 */
2937
+	public function exists($query_params)
2938
+	{
2939
+		$query_params['limit'] = 1;
2940
+		return $this->count($query_params) > 0;
2941
+	}
2942
+
2943
+
2944
+
2945
+	/**
2946
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2947
+	 *
2948
+	 * @param int|string $id
2949
+	 * @return boolean
2950
+	 * @throws EE_Error
2951
+	 */
2952
+	public function exists_by_ID($id)
2953
+	{
2954
+		return $this->exists(
2955
+			array(
2956
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2957
+				array(
2958
+					$this->primary_key_name() => $id,
2959
+				),
2960
+			)
2961
+		);
2962
+	}
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2968
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2969
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2970
+	 * on the main table)
2971
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2972
+	 * cases where we want to call it directly rather than via insert().
2973
+	 *
2974
+	 * @access   protected
2975
+	 * @param EE_Table_Base $table
2976
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2977
+	 *                                       float
2978
+	 * @param int           $new_id          for now we assume only int keys
2979
+	 * @throws EE_Error
2980
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2981
+	 * @return int ID of new row inserted, or FALSE on failure
2982
+	 */
2983
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2984
+	{
2985
+		global $wpdb;
2986
+		$insertion_col_n_values = array();
2987
+		$format_for_insertion = array();
2988
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2989
+		foreach ($fields_on_table as $field_name => $field_obj) {
2990
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2991
+			if ($field_obj->is_auto_increment()) {
2992
+				continue;
2993
+			}
2994
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2996
+			if ($prepared_value !== null) {
2997
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2998
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999
+			}
3000
+		}
3001
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3002
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3003
+			// so add the fk to the main table as a column
3004
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3006
+		}
3007
+		// insert the new entry
3008
+		$result = $this->_do_wpdb_query(
3009
+			'insert',
3010
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3011
+		);
3012
+		if ($result === false) {
3013
+			return false;
3014
+		}
3015
+		// ok, now what do we return for the ID of the newly-inserted thing?
3016
+		if ($this->has_primary_key_field()) {
3017
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3018
+				return $wpdb->insert_id;
3019
+			}
3020
+			// it's not an auto-increment primary key, so
3021
+			// it must have been supplied
3022
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3023
+		}
3024
+		// we can't return a  primary key because there is none. instead return
3025
+		// a unique string indicating this model
3026
+		return $this->get_index_primary_key_string($fields_n_values);
3027
+	}
3028
+
3029
+
3030
+
3031
+	/**
3032
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3033
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3034
+	 * and there is no default, we pass it along. WPDB will take care of it)
3035
+	 *
3036
+	 * @param EE_Model_Field_Base $field_obj
3037
+	 * @param array               $fields_n_values
3038
+	 * @return mixed string|int|float depending on what the table column will be expecting
3039
+	 * @throws EE_Error
3040
+	 */
3041
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3042
+	{
3043
+		// if this field doesn't allow nullable, don't allow it
3044
+		if (
3045
+			! $field_obj->is_nullable()
3046
+			&& (
3047
+				! isset($fields_n_values[ $field_obj->get_name() ])
3048
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3049
+			)
3050
+		) {
3051
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3052
+		}
3053
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
+			? $fields_n_values[ $field_obj->get_name() ]
3055
+			: null;
3056
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057
+	}
3058
+
3059
+
3060
+
3061
+	/**
3062
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3063
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3064
+	 * the field's prepare_for_set() method.
3065
+	 *
3066
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3067
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3068
+	 *                                   top of file)
3069
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3070
+	 *                                   $value is a custom selection
3071
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3072
+	 */
3073
+	private function _prepare_value_for_use_in_db($value, $field)
3074
+	{
3075
+		if ($field && $field instanceof EE_Model_Field_Base) {
3076
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3077
+			switch ($this->_values_already_prepared_by_model_object) {
3078
+				/** @noinspection PhpMissingBreakStatementInspection */
3079
+				case self::not_prepared_by_model_object:
3080
+					$value = $field->prepare_for_set($value);
3081
+				// purposefully left out "return"
3082
+				case self::prepared_by_model_object:
3083
+					/** @noinspection SuspiciousAssignmentsInspection */
3084
+					$value = $field->prepare_for_use_in_db($value);
3085
+				case self::prepared_for_use_in_db:
3086
+					// leave the value alone
3087
+			}
3088
+			return $value;
3089
+			// phpcs:enable
3090
+		}
3091
+		return $value;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Returns the main table on this model
3098
+	 *
3099
+	 * @return EE_Primary_Table
3100
+	 * @throws EE_Error
3101
+	 */
3102
+	protected function _get_main_table()
3103
+	{
3104
+		foreach ($this->_tables as $table) {
3105
+			if ($table instanceof EE_Primary_Table) {
3106
+				return $table;
3107
+			}
3108
+		}
3109
+		throw new EE_Error(sprintf(esc_html__(
3110
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3111
+			'event_espresso'
3112
+		), get_class($this)));
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * table
3119
+	 * returns EE_Primary_Table table name
3120
+	 *
3121
+	 * @return string
3122
+	 * @throws EE_Error
3123
+	 */
3124
+	public function table()
3125
+	{
3126
+		return $this->_get_main_table()->get_table_name();
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * table
3133
+	 * returns first EE_Secondary_Table table name
3134
+	 *
3135
+	 * @return string
3136
+	 */
3137
+	public function second_table()
3138
+	{
3139
+		// grab second table from tables array
3140
+		$second_table = end($this->_tables);
3141
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * get_table_obj_by_alias
3148
+	 * returns table name given it's alias
3149
+	 *
3150
+	 * @param string $table_alias
3151
+	 * @return EE_Primary_Table | EE_Secondary_Table
3152
+	 */
3153
+	public function get_table_obj_by_alias($table_alias = '')
3154
+	{
3155
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
+	 *
3163
+	 * @return EE_Secondary_Table[]
3164
+	 */
3165
+	protected function _get_other_tables()
3166
+	{
3167
+		$other_tables = array();
3168
+		foreach ($this->_tables as $table_alias => $table) {
3169
+			if ($table instanceof EE_Secondary_Table) {
3170
+				$other_tables[ $table_alias ] = $table;
3171
+			}
3172
+		}
3173
+		return $other_tables;
3174
+	}
3175
+
3176
+
3177
+
3178
+	/**
3179
+	 * Finds all the fields that correspond to the given table
3180
+	 *
3181
+	 * @param string $table_alias , array key in EEM_Base::_tables
3182
+	 * @return EE_Model_Field_Base[]
3183
+	 */
3184
+	public function _get_fields_for_table($table_alias)
3185
+	{
3186
+		return $this->_fields[ $table_alias ];
3187
+	}
3188
+
3189
+
3190
+
3191
+	/**
3192
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3193
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
+	 * related Registration, Transaction, and Payment models.
3197
+	 *
3198
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 * @throws EE_Error
3201
+	 */
3202
+	public function _extract_related_models_from_query($query_params)
3203
+	{
3204
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
+		if (array_key_exists(0, $query_params)) {
3206
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
+		}
3208
+		if (array_key_exists('group_by', $query_params)) {
3209
+			if (is_array($query_params['group_by'])) {
3210
+				$this->_extract_related_models_from_sub_params_array_values(
3211
+					$query_params['group_by'],
3212
+					$query_info_carrier,
3213
+					'group_by'
3214
+				);
3215
+			} elseif (! empty($query_params['group_by'])) {
3216
+				$this->_extract_related_model_info_from_query_param(
3217
+					$query_params['group_by'],
3218
+					$query_info_carrier,
3219
+					'group_by'
3220
+				);
3221
+			}
3222
+		}
3223
+		if (array_key_exists('having', $query_params)) {
3224
+			$this->_extract_related_models_from_sub_params_array_keys(
3225
+				$query_params[0],
3226
+				$query_info_carrier,
3227
+				'having'
3228
+			);
3229
+		}
3230
+		if (array_key_exists('order_by', $query_params)) {
3231
+			if (is_array($query_params['order_by'])) {
3232
+				$this->_extract_related_models_from_sub_params_array_keys(
3233
+					$query_params['order_by'],
3234
+					$query_info_carrier,
3235
+					'order_by'
3236
+				);
3237
+			} elseif (! empty($query_params['order_by'])) {
3238
+				$this->_extract_related_model_info_from_query_param(
3239
+					$query_params['order_by'],
3240
+					$query_info_carrier,
3241
+					'order_by'
3242
+				);
3243
+			}
3244
+		}
3245
+		if (array_key_exists('force_join', $query_params)) {
3246
+			$this->_extract_related_models_from_sub_params_array_values(
3247
+				$query_params['force_join'],
3248
+				$query_info_carrier,
3249
+				'force_join'
3250
+			);
3251
+		}
3252
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
+		return $query_info_carrier;
3254
+	}
3255
+
3256
+
3257
+
3258
+	/**
3259
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
+	 *
3261
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3262
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3264
+	 * @throws EE_Error
3265
+	 * @return \EE_Model_Query_Info_Carrier
3266
+	 */
3267
+	private function _extract_related_models_from_sub_params_array_keys(
3268
+		$sub_query_params,
3269
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
+		$query_param_type
3271
+	) {
3272
+		if (! empty($sub_query_params)) {
3273
+			$sub_query_params = (array) $sub_query_params;
3274
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
+				$this->_extract_related_model_info_from_query_param(
3277
+					$param,
3278
+					$model_query_info_carrier,
3279
+					$query_param_type
3280
+				);
3281
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3282
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3283
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3284
+				// of array('Registration.TXN_ID'=>23)
3285
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
+					if (! is_array($possibly_array_of_params)) {
3288
+						throw new EE_Error(sprintf(
3289
+							esc_html__(
3290
+								"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3291
+								"event_espresso"
3292
+							),
3293
+							$param,
3294
+							$possibly_array_of_params
3295
+						));
3296
+					}
3297
+					$this->_extract_related_models_from_sub_params_array_keys(
3298
+						$possibly_array_of_params,
3299
+						$model_query_info_carrier,
3300
+						$query_param_type
3301
+					);
3302
+				} elseif (
3303
+					$query_param_type === 0 // ie WHERE
3304
+						  && is_array($possibly_array_of_params)
3305
+						  && isset($possibly_array_of_params[2])
3306
+						  && $possibly_array_of_params[2] == true
3307
+				) {
3308
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309
+					// indicating that $possible_array_of_params[1] is actually a field name,
3310
+					// from which we should extract query parameters!
3311
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312
+						throw new EE_Error(sprintf(esc_html__(
3313
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314
+							"event_espresso"
3315
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3316
+					}
3317
+					$this->_extract_related_model_info_from_query_param(
3318
+						$possibly_array_of_params[1],
3319
+						$model_query_info_carrier,
3320
+						$query_param_type
3321
+					);
3322
+				}
3323
+			}
3324
+		}
3325
+		return $model_query_info_carrier;
3326
+	}
3327
+
3328
+
3329
+
3330
+	/**
3331
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3332
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3333
+	 *
3334
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3335
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3336
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3337
+	 * @throws EE_Error
3338
+	 * @return \EE_Model_Query_Info_Carrier
3339
+	 */
3340
+	private function _extract_related_models_from_sub_params_array_values(
3341
+		$sub_query_params,
3342
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343
+		$query_param_type
3344
+	) {
3345
+		if (! empty($sub_query_params)) {
3346
+			if (! is_array($sub_query_params)) {
3347
+				throw new EE_Error(sprintf(
3348
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349
+					$sub_query_params
3350
+				));
3351
+			}
3352
+			foreach ($sub_query_params as $param) {
3353
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3354
+				$this->_extract_related_model_info_from_query_param(
3355
+					$param,
3356
+					$model_query_info_carrier,
3357
+					$query_param_type
3358
+				);
3359
+			}
3360
+		}
3361
+		return $model_query_info_carrier;
3362
+	}
3363
+
3364
+
3365
+	/**
3366
+	 * Extract all the query parts from  model query params
3367
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3368
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3369
+	 * but use them in a different order. Eg, we need to know what models we are querying
3370
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3371
+	 * other models before we can finalize the where clause SQL.
3372
+	 *
3373
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3374
+	 * @throws EE_Error
3375
+	 * @return EE_Model_Query_Info_Carrier
3376
+	 * @throws ModelConfigurationException
3377
+	 */
3378
+	public function _create_model_query_info_carrier($query_params)
3379
+	{
3380
+		if (! is_array($query_params)) {
3381
+			EE_Error::doing_it_wrong(
3382
+				'EEM_Base::_create_model_query_info_carrier',
3383
+				sprintf(
3384
+					esc_html__(
3385
+						'$query_params should be an array, you passed a variable of type %s',
3386
+						'event_espresso'
3387
+					),
3388
+					gettype($query_params)
3389
+				),
3390
+				'4.6.0'
3391
+			);
3392
+			$query_params = array();
3393
+		}
3394
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3395
+		// first check if we should alter the query to account for caps or not
3396
+		// because the caps might require us to do extra joins
3397
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3398
+			$query_params[0] = array_replace_recursive(
3399
+				$query_params[0],
3400
+				$this->caps_where_conditions(
3401
+					$query_params['caps']
3402
+				)
3403
+			);
3404
+		}
3405
+
3406
+		// check if we should alter the query to remove data related to protected
3407
+		// custom post types
3408
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3409
+			$where_param_key_for_password = $this->modelChainAndPassword();
3410
+			// only include if related to a cpt where no password has been set
3411
+			$query_params[0]['OR*nopassword'] = array(
3412
+				$where_param_key_for_password => '',
3413
+				$where_param_key_for_password . '*' => array('IS_NULL')
3414
+			);
3415
+		}
3416
+		$query_object = $this->_extract_related_models_from_query($query_params);
3417
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3418
+		foreach ($query_params[0] as $key => $value) {
3419
+			if (is_int($key)) {
3420
+				throw new EE_Error(
3421
+					sprintf(
3422
+						esc_html__(
3423
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3424
+							"event_espresso"
3425
+						),
3426
+						$key,
3427
+						var_export($value, true),
3428
+						var_export($query_params, true),
3429
+						get_class($this)
3430
+					)
3431
+				);
3432
+			}
3433
+		}
3434
+		if (
3435
+			array_key_exists('default_where_conditions', $query_params)
3436
+			&& ! empty($query_params['default_where_conditions'])
3437
+		) {
3438
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3439
+		} else {
3440
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3441
+		}
3442
+		$query_params[0] = array_merge(
3443
+			$this->_get_default_where_conditions_for_models_in_query(
3444
+				$query_object,
3445
+				$use_default_where_conditions,
3446
+				$query_params[0]
3447
+			),
3448
+			$query_params[0]
3449
+		);
3450
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3451
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3452
+		// So we need to setup a subquery and use that for the main join.
3453
+		// Note for now this only works on the primary table for the model.
3454
+		// So for instance, you could set the limit array like this:
3455
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3456
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3457
+			$query_object->set_main_model_join_sql(
3458
+				$this->_construct_limit_join_select(
3459
+					$query_params['on_join_limit'][0],
3460
+					$query_params['on_join_limit'][1]
3461
+				)
3462
+			);
3463
+		}
3464
+		// set limit
3465
+		if (array_key_exists('limit', $query_params)) {
3466
+			if (is_array($query_params['limit'])) {
3467
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468
+					$e = sprintf(
3469
+						esc_html__(
3470
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3471
+							"event_espresso"
3472
+						),
3473
+						http_build_query($query_params['limit'])
3474
+					);
3475
+					throw new EE_Error($e . "|" . $e);
3476
+				}
3477
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
+			} elseif (! empty($query_params['limit'])) {
3480
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3481
+			}
3482
+		}
3483
+		// set order by
3484
+		if (array_key_exists('order_by', $query_params)) {
3485
+			if (is_array($query_params['order_by'])) {
3486
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3487
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3488
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3489
+				if (array_key_exists('order', $query_params)) {
3490
+					throw new EE_Error(
3491
+						sprintf(
3492
+							esc_html__(
3493
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3494
+								"event_espresso"
3495
+							),
3496
+							get_class($this),
3497
+							implode(", ", array_keys($query_params['order_by'])),
3498
+							implode(", ", $query_params['order_by']),
3499
+							$query_params['order']
3500
+						)
3501
+					);
3502
+				}
3503
+				$this->_extract_related_models_from_sub_params_array_keys(
3504
+					$query_params['order_by'],
3505
+					$query_object,
3506
+					'order_by'
3507
+				);
3508
+				// assume it's an array of fields to order by
3509
+				$order_array = array();
3510
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511
+					$order = $this->_extract_order($order);
3512
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3513
+				}
3514
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
+			} elseif (! empty($query_params['order_by'])) {
3516
+				$this->_extract_related_model_info_from_query_param(
3517
+					$query_params['order_by'],
3518
+					$query_object,
3519
+					'order',
3520
+					$query_params['order_by']
3521
+				);
3522
+				$order = isset($query_params['order'])
3523
+					? $this->_extract_order($query_params['order'])
3524
+					: 'DESC';
3525
+				$query_object->set_order_by_sql(
3526
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3527
+				);
3528
+			}
3529
+		}
3530
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3531
+		if (
3532
+			! array_key_exists('order_by', $query_params)
3533
+			&& array_key_exists('order', $query_params)
3534
+			&& ! empty($query_params['order'])
3535
+		) {
3536
+			$pk_field = $this->get_primary_key_field();
3537
+			$order = $this->_extract_order($query_params['order']);
3538
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3539
+		}
3540
+		// set group by
3541
+		if (array_key_exists('group_by', $query_params)) {
3542
+			if (is_array($query_params['group_by'])) {
3543
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3544
+				$group_by_array = array();
3545
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547
+				}
3548
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
+			} elseif (! empty($query_params['group_by'])) {
3550
+				$query_object->set_group_by_sql(
3551
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3552
+				);
3553
+			}
3554
+		}
3555
+		// set having
3556
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3557
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3558
+		}
3559
+		// now, just verify they didn't pass anything wack
3560
+		foreach ($query_params as $query_key => $query_value) {
3561
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3562
+				throw new EE_Error(
3563
+					sprintf(
3564
+						esc_html__(
3565
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3566
+							'event_espresso'
3567
+						),
3568
+						$query_key,
3569
+						get_class($this),
3570
+						//                      print_r( $this->_allowed_query_params, TRUE )
3571
+						implode(',', $this->_allowed_query_params)
3572
+					)
3573
+				);
3574
+			}
3575
+		}
3576
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3577
+		if (empty($main_model_join_sql)) {
3578
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3579
+		}
3580
+		return $query_object;
3581
+	}
3582
+
3583
+
3584
+
3585
+	/**
3586
+	 * Gets the where conditions that should be imposed on the query based on the
3587
+	 * context (eg reading frontend, backend, edit or delete).
3588
+	 *
3589
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3590
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3591
+	 * @throws EE_Error
3592
+	 */
3593
+	public function caps_where_conditions($context = self::caps_read)
3594
+	{
3595
+		EEM_Base::verify_is_valid_cap_context($context);
3596
+		$cap_where_conditions = array();
3597
+		$cap_restrictions = $this->caps_missing($context);
3598
+		/**
3599
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3600
+		 */
3601
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3602
+			$cap_where_conditions = array_replace_recursive(
3603
+				$cap_where_conditions,
3604
+				$restriction_if_no_cap->get_default_where_conditions()
3605
+			);
3606
+		}
3607
+		return apply_filters(
3608
+			'FHEE__EEM_Base__caps_where_conditions__return',
3609
+			$cap_where_conditions,
3610
+			$this,
3611
+			$context,
3612
+			$cap_restrictions
3613
+		);
3614
+	}
3615
+
3616
+
3617
+
3618
+	/**
3619
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3620
+	 * otherwise throws an exception
3621
+	 *
3622
+	 * @param string $should_be_order_string
3623
+	 * @return string either ASC, asc, DESC or desc
3624
+	 * @throws EE_Error
3625
+	 */
3626
+	private function _extract_order($should_be_order_string)
3627
+	{
3628
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3629
+			return $should_be_order_string;
3630
+		}
3631
+		throw new EE_Error(
3632
+			sprintf(
3633
+				esc_html__(
3634
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3635
+					"event_espresso"
3636
+				),
3637
+				get_class($this),
3638
+				$should_be_order_string
3639
+			)
3640
+		);
3641
+	}
3642
+
3643
+
3644
+
3645
+	/**
3646
+	 * Looks at all the models which are included in this query, and asks each
3647
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3648
+	 * so they can be merged
3649
+	 *
3650
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3651
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3652
+	 *                                                                  'none' means NO default where conditions will
3653
+	 *                                                                  be used AT ALL during this query.
3654
+	 *                                                                  'other_models_only' means default where
3655
+	 *                                                                  conditions from other models will be used, but
3656
+	 *                                                                  not for this primary model. 'all', the default,
3657
+	 *                                                                  means default where conditions will apply as
3658
+	 *                                                                  normal
3659
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 * @throws EE_Error
3661
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3662
+	 */
3663
+	private function _get_default_where_conditions_for_models_in_query(
3664
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3665
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3666
+		$where_query_params = array()
3667
+	) {
3668
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670
+			throw new EE_Error(sprintf(
3671
+				esc_html__(
3672
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3673
+					"event_espresso"
3674
+				),
3675
+				$use_default_where_conditions,
3676
+				implode(", ", $allowed_used_default_where_conditions_values)
3677
+			));
3678
+		}
3679
+		$universal_query_params = array();
3680
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_default_where_conditions();
3682
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3683
+			$universal_query_params = $this->_get_minimum_where_conditions();
3684
+		}
3685
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3686
+			$related_model = $this->get_related_model_obj($model_name);
3687
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3689
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3690
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3691
+			} else {
3692
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3693
+				continue;
3694
+			}
3695
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3696
+				$related_model_universal_where_params,
3697
+				$where_query_params,
3698
+				$related_model,
3699
+				$model_relation_path
3700
+			);
3701
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3702
+				$universal_query_params,
3703
+				$overrides
3704
+			);
3705
+		}
3706
+		return $universal_query_params;
3707
+	}
3708
+
3709
+
3710
+
3711
+	/**
3712
+	 * Determines whether or not we should use default where conditions for the model in question
3713
+	 * (this model, or other related models).
3714
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3715
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3716
+	 * We should use default where conditions on related models when they requested to use default where conditions
3717
+	 * on all models, or specifically just on other related models
3718
+	 * @param      $default_where_conditions_value
3719
+	 * @param bool $for_this_model false means this is for OTHER related models
3720
+	 * @return bool
3721
+	 */
3722
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3723
+	{
3724
+		return (
3725
+				   $for_this_model
3726
+				   && in_array(
3727
+					   $default_where_conditions_value,
3728
+					   array(
3729
+						   EEM_Base::default_where_conditions_all,
3730
+						   EEM_Base::default_where_conditions_this_only,
3731
+						   EEM_Base::default_where_conditions_minimum_others,
3732
+					   ),
3733
+					   true
3734
+				   )
3735
+			   )
3736
+			   || (
3737
+				   ! $for_this_model
3738
+				   && in_array(
3739
+					   $default_where_conditions_value,
3740
+					   array(
3741
+						   EEM_Base::default_where_conditions_all,
3742
+						   EEM_Base::default_where_conditions_others_only,
3743
+					   ),
3744
+					   true
3745
+				   )
3746
+			   );
3747
+	}
3748
+
3749
+	/**
3750
+	 * Determines whether or not we should use default minimum conditions for the model in question
3751
+	 * (this model, or other related models).
3752
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3753
+	 * where conditions.
3754
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3755
+	 * on this model or others
3756
+	 * @param      $default_where_conditions_value
3757
+	 * @param bool $for_this_model false means this is for OTHER related models
3758
+	 * @return bool
3759
+	 */
3760
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3761
+	{
3762
+		return (
3763
+				   $for_this_model
3764
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3765
+			   )
3766
+			   || (
3767
+				   ! $for_this_model
3768
+				   && in_array(
3769
+					   $default_where_conditions_value,
3770
+					   array(
3771
+						   EEM_Base::default_where_conditions_minimum_others,
3772
+						   EEM_Base::default_where_conditions_minimum_all,
3773
+					   ),
3774
+					   true
3775
+				   )
3776
+			   );
3777
+	}
3778
+
3779
+
3780
+	/**
3781
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3782
+	 * then we also add a special where condition which allows for that model's primary key
3783
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3784
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3785
+	 *
3786
+	 * @param array    $default_where_conditions
3787
+	 * @param array    $provided_where_conditions
3788
+	 * @param EEM_Base $model
3789
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3790
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3791
+	 * @throws EE_Error
3792
+	 */
3793
+	private function _override_defaults_or_make_null_friendly(
3794
+		$default_where_conditions,
3795
+		$provided_where_conditions,
3796
+		$model,
3797
+		$model_relation_path
3798
+	) {
3799
+		$null_friendly_where_conditions = array();
3800
+		$none_overridden = true;
3801
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3802
+		foreach ($default_where_conditions as $key => $val) {
3803
+			if (isset($provided_where_conditions[ $key ])) {
3804
+				$none_overridden = false;
3805
+			} else {
3806
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3807
+			}
3808
+		}
3809
+		if ($none_overridden && $default_where_conditions) {
3810
+			if ($model->has_primary_key_field()) {
3811
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3812
+																				. "."
3813
+																				. $model->primary_key_name() ] = array('IS NULL');
3814
+			}/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
3817
-        }
3818
-        return $null_friendly_where_conditions;
3819
-    }
3820
-
3821
-
3822
-
3823
-    /**
3824
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3825
-     * default where conditions on all get_all, update, and delete queries done by this model.
3826
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3828
-     *
3829
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
-     */
3832
-    private function _get_default_where_conditions($model_relation_path = null)
3833
-    {
3834
-        if ($this->_ignore_where_strategy) {
3835
-            return array();
3836
-        }
3837
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
-    }
3839
-
3840
-
3841
-
3842
-    /**
3843
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3847
-     * Similar to _get_default_where_conditions
3848
-     *
3849
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
-     */
3852
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3853
-    {
3854
-        if ($this->_ignore_where_strategy) {
3855
-            return array();
3856
-        }
3857
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
-    }
3859
-
3860
-
3861
-
3862
-    /**
3863
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
-     *
3866
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3867
-     * @return string
3868
-     * @throws EE_Error
3869
-     */
3870
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
-    {
3872
-        $selects = $this->_get_columns_to_select_for_this_model();
3873
-        foreach (
3874
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3875
-        ) {
3876
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3877
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3878
-            foreach ($other_model_selects as $key => $value) {
3879
-                $selects[] = $value;
3880
-            }
3881
-        }
3882
-        return implode(", ", $selects);
3883
-    }
3884
-
3885
-
3886
-
3887
-    /**
3888
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3889
-     * So that's going to be the columns for all the fields on the model
3890
-     *
3891
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3892
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3893
-     */
3894
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3895
-    {
3896
-        $fields = $this->field_settings();
3897
-        $selects = array();
3898
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3899
-            $model_relation_chain,
3900
-            $this->get_this_model_name()
3901
-        );
3902
-        foreach ($fields as $field_obj) {
3903
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3904
-                         . $field_obj->get_table_alias()
3905
-                         . "."
3906
-                         . $field_obj->get_table_column()
3907
-                         . " AS '"
3908
-                         . $table_alias_with_model_relation_chain_prefix
3909
-                         . $field_obj->get_table_alias()
3910
-                         . "."
3911
-                         . $field_obj->get_table_column()
3912
-                         . "'";
3913
-        }
3914
-        // make sure we are also getting the PKs of each table
3915
-        $tables = $this->get_tables();
3916
-        if (count($tables) > 1) {
3917
-            foreach ($tables as $table_obj) {
3918
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919
-                                       . $table_obj->get_fully_qualified_pk_column();
3920
-                if (! in_array($qualified_pk_column, $selects)) {
3921
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922
-                }
3923
-            }
3924
-        }
3925
-        return $selects;
3926
-    }
3927
-
3928
-
3929
-
3930
-    /**
3931
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3932
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3933
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3934
-     * SQL for joining, and the data types
3935
-     *
3936
-     * @param null|string                 $original_query_param
3937
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3938
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3939
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3940
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3941
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3942
-     *                                                          or 'Registration's
3943
-     * @param string                      $original_query_param what it originally was (eg
3944
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3945
-     *                                                          matches $query_param
3946
-     * @throws EE_Error
3947
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3948
-     */
3949
-    private function _extract_related_model_info_from_query_param(
3950
-        $query_param,
3951
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3952
-        $query_param_type,
3953
-        $original_query_param = null
3954
-    ) {
3955
-        if ($original_query_param === null) {
3956
-            $original_query_param = $query_param;
3957
-        }
3958
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3959
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3960
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3961
-        $allow_fields = in_array(
3962
-            $query_param_type,
3963
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3964
-            true
3965
-        );
3966
-        // check to see if we have a field on this model
3967
-        $this_model_fields = $this->field_settings(true);
3968
-        if (array_key_exists($query_param, $this_model_fields)) {
3969
-            if ($allow_fields) {
3970
-                return;
3971
-            }
3972
-            throw new EE_Error(
3973
-                sprintf(
3974
-                    esc_html__(
3975
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3976
-                        "event_espresso"
3977
-                    ),
3978
-                    $query_param,
3979
-                    get_class($this),
3980
-                    $query_param_type,
3981
-                    $original_query_param
3982
-                )
3983
-            );
3984
-        }
3985
-        // check if this is a special logic query param
3986
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3987
-            if ($allow_logic_query_params) {
3988
-                return;
3989
-            }
3990
-            throw new EE_Error(
3991
-                sprintf(
3992
-                    esc_html__(
3993
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3994
-                        'event_espresso'
3995
-                    ),
3996
-                    implode('", "', $this->_logic_query_param_keys),
3997
-                    $query_param,
3998
-                    get_class($this),
3999
-                    '<br />',
4000
-                    "\t"
4001
-                    . ' $passed_in_query_info = <pre>'
4002
-                    . print_r($passed_in_query_info, true)
4003
-                    . '</pre>'
4004
-                    . "\n\t"
4005
-                    . ' $query_param_type = '
4006
-                    . $query_param_type
4007
-                    . "\n\t"
4008
-                    . ' $original_query_param = '
4009
-                    . $original_query_param
4010
-                )
4011
-            );
4012
-        }
4013
-        // check if it's a custom selection
4014
-        if (
4015
-            $this->_custom_selections instanceof CustomSelects
4016
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4017
-        ) {
4018
-            return;
4019
-        }
4020
-        // check if has a model name at the beginning
4021
-        // and
4022
-        // check if it's a field on a related model
4023
-        if (
4024
-            $this->extractJoinModelFromQueryParams(
4025
-                $passed_in_query_info,
4026
-                $query_param,
4027
-                $original_query_param,
4028
-                $query_param_type
4029
-            )
4030
-        ) {
4031
-            return;
4032
-        }
4033
-
4034
-        // ok so $query_param didn't start with a model name
4035
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4036
-        // it's wack, that's what it is
4037
-        throw new EE_Error(
4038
-            sprintf(
4039
-                esc_html__(
4040
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4041
-                    "event_espresso"
4042
-                ),
4043
-                $query_param,
4044
-                get_class($this),
4045
-                $query_param_type,
4046
-                $original_query_param
4047
-            )
4048
-        );
4049
-    }
4050
-
4051
-
4052
-    /**
4053
-     * Extracts any possible join model information from the provided possible_join_string.
4054
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4055
-     * parts that should be added to the query.
4056
-     *
4057
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4058
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4059
-     * @param null|string                 $original_query_param
4060
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4061
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4062
-     * @return bool  returns true if a join was added and false if not.
4063
-     * @throws EE_Error
4064
-     */
4065
-    private function extractJoinModelFromQueryParams(
4066
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4067
-        $possible_join_string,
4068
-        $original_query_param,
4069
-        $query_parameter_type
4070
-    ) {
4071
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4073
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4075
-                if ($possible_join_string === '') {
4076
-                    // nothing left to $query_param
4077
-                    // we should actually end in a field name, not a model like this!
4078
-                    throw new EE_Error(
4079
-                        sprintf(
4080
-                            esc_html__(
4081
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4082
-                                "event_espresso"
4083
-                            ),
4084
-                            $possible_join_string,
4085
-                            $query_parameter_type,
4086
-                            get_class($this),
4087
-                            $valid_related_model_name
4088
-                        )
4089
-                    );
4090
-                }
4091
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4092
-                $related_model_obj->_extract_related_model_info_from_query_param(
4093
-                    $possible_join_string,
4094
-                    $query_info_carrier,
4095
-                    $query_parameter_type,
4096
-                    $original_query_param
4097
-                );
4098
-                return true;
4099
-            }
4100
-            if ($possible_join_string === $valid_related_model_name) {
4101
-                $this->_add_join_to_model(
4102
-                    $valid_related_model_name,
4103
-                    $query_info_carrier,
4104
-                    $original_query_param
4105
-                );
4106
-                return true;
4107
-            }
4108
-        }
4109
-        return false;
4110
-    }
4111
-
4112
-
4113
-    /**
4114
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4115
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4116
-     * @throws EE_Error
4117
-     */
4118
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4119
-    {
4120
-        if (
4121
-            $this->_custom_selections instanceof CustomSelects
4122
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4123
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4124
-            )
4125
-        ) {
4126
-            $original_selects = $this->_custom_selections->originalSelects();
4127
-            foreach ($original_selects as $alias => $select_configuration) {
4128
-                $this->extractJoinModelFromQueryParams(
4129
-                    $query_info_carrier,
4130
-                    $select_configuration[0],
4131
-                    $select_configuration[0],
4132
-                    'custom_selects'
4133
-                );
4134
-            }
4135
-        }
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4142
-     * and store it on $passed_in_query_info
4143
-     *
4144
-     * @param string                      $model_name
4145
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4146
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4147
-     *                                                          model and $model_name. Eg, if we are querying Event,
4148
-     *                                                          and are adding a join to 'Payment' with the original
4149
-     *                                                          query param key
4150
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4151
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4152
-     *                                                          Payment wants to add default query params so that it
4153
-     *                                                          will know what models to prepend onto its default query
4154
-     *                                                          params or in case it wants to rename tables (in case
4155
-     *                                                          there are multiple joins to the same table)
4156
-     * @return void
4157
-     * @throws EE_Error
4158
-     */
4159
-    private function _add_join_to_model(
4160
-        $model_name,
4161
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4162
-        $original_query_param
4163
-    ) {
4164
-        $relation_obj = $this->related_settings_for($model_name);
4165
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4166
-        // check if the relation is HABTM, because then we're essentially doing two joins
4167
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4168
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4169
-            $join_model_obj = $relation_obj->get_join_model();
4170
-            // replace the model specified with the join model for this relation chain, whi
4171
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4172
-                $model_name,
4173
-                $join_model_obj->get_this_model_name(),
4174
-                $model_relation_chain
4175
-            );
4176
-            $passed_in_query_info->merge(
4177
-                new EE_Model_Query_Info_Carrier(
4178
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4179
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4180
-                )
4181
-            );
4182
-        }
4183
-        // now just join to the other table pointed to by the relation object, and add its data types
4184
-        $passed_in_query_info->merge(
4185
-            new EE_Model_Query_Info_Carrier(
4186
-                array($model_relation_chain => $model_name),
4187
-                $relation_obj->get_join_statement($model_relation_chain)
4188
-            )
4189
-        );
4190
-    }
4191
-
4192
-
4193
-
4194
-    /**
4195
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4196
-     *
4197
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4198
-     * @return string of SQL
4199
-     * @throws EE_Error
4200
-     */
4201
-    private function _construct_where_clause($where_params)
4202
-    {
4203
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204
-        if ($SQL) {
4205
-            return " WHERE " . $SQL;
4206
-        }
4207
-        return '';
4208
-    }
4209
-
4210
-
4211
-
4212
-    /**
4213
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4214
-     * and should be passed HAVING parameters, not WHERE parameters
4215
-     *
4216
-     * @param array $having_params
4217
-     * @return string
4218
-     * @throws EE_Error
4219
-     */
4220
-    private function _construct_having_clause($having_params)
4221
-    {
4222
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223
-        if ($SQL) {
4224
-            return " HAVING " . $SQL;
4225
-        }
4226
-        return '';
4227
-    }
4228
-
4229
-
4230
-    /**
4231
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4232
-     * Event_Meta.meta_value = 'foo'))"
4233
-     *
4234
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4235
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4236
-     * @throws EE_Error
4237
-     * @return string of SQL
4238
-     */
4239
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4240
-    {
4241
-        $where_clauses = array();
4242
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4244
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4245
-                switch ($query_param) {
4246
-                    case 'not':
4247
-                    case 'NOT':
4248
-                        $where_clauses[] = "! ("
4249
-                                           . $this->_construct_condition_clause_recursive(
4250
-                                               $op_and_value_or_sub_condition,
4251
-                                               $glue
4252
-                                           )
4253
-                                           . ")";
4254
-                        break;
4255
-                    case 'and':
4256
-                    case 'AND':
4257
-                        $where_clauses[] = " ("
4258
-                                           . $this->_construct_condition_clause_recursive(
4259
-                                               $op_and_value_or_sub_condition,
4260
-                                               ' AND '
4261
-                                           )
4262
-                                           . ")";
4263
-                        break;
4264
-                    case 'or':
4265
-                    case 'OR':
4266
-                        $where_clauses[] = " ("
4267
-                                           . $this->_construct_condition_clause_recursive(
4268
-                                               $op_and_value_or_sub_condition,
4269
-                                               ' OR '
4270
-                                           )
4271
-                                           . ")";
4272
-                        break;
4273
-                }
4274
-            } else {
4275
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4276
-                // if it's not a normal field, maybe it's a custom selection?
4277
-                if (! $field_obj) {
4278
-                    if ($this->_custom_selections instanceof CustomSelects) {
4279
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280
-                    } else {
4281
-                        throw new EE_Error(sprintf(esc_html__(
4282
-                            "%s is neither a valid model field name, nor a custom selection",
4283
-                            "event_espresso"
4284
-                        ), $query_param));
4285
-                    }
4286
-                }
4287
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4289
-            }
4290
-        }
4291
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4292
-    }
4293
-
4294
-
4295
-
4296
-    /**
4297
-     * Takes the input parameter and extract the table name (alias) and column name
4298
-     *
4299
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4300
-     * @throws EE_Error
4301
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4302
-     */
4303
-    private function _deduce_column_name_from_query_param($query_param)
4304
-    {
4305
-        $field = $this->_deduce_field_from_query_param($query_param);
4306
-        if ($field) {
4307
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4308
-                $field->get_model_name(),
4309
-                $query_param
4310
-            );
4311
-            return $table_alias_prefix . $field->get_qualified_column();
4312
-        }
4313
-        if (
4314
-            $this->_custom_selections instanceof CustomSelects
4315
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4316
-        ) {
4317
-            // maybe it's custom selection item?
4318
-            // if so, just use it as the "column name"
4319
-            return $query_param;
4320
-        }
4321
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4322
-            ? implode(',', $this->_custom_selections->columnAliases())
4323
-            : '';
4324
-        throw new EE_Error(
4325
-            sprintf(
4326
-                esc_html__(
4327
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4328
-                    "event_espresso"
4329
-                ),
4330
-                $query_param,
4331
-                $custom_select_aliases
4332
-            )
4333
-        );
4334
-    }
4335
-
4336
-
4337
-
4338
-    /**
4339
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4340
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4341
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4342
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4343
-     *
4344
-     * @param string $condition_query_param_key
4345
-     * @return string
4346
-     */
4347
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4348
-    {
4349
-        $pos_of_star = strpos($condition_query_param_key, '*');
4350
-        if ($pos_of_star === false) {
4351
-            return $condition_query_param_key;
4352
-        }
4353
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4354
-        return $condition_query_param_sans_star;
4355
-    }
4356
-
4357
-
4358
-
4359
-    /**
4360
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4361
-     *
4362
-     * @param                            mixed      array | string    $op_and_value
4363
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4364
-     * @throws EE_Error
4365
-     * @return string
4366
-     */
4367
-    private function _construct_op_and_value($op_and_value, $field_obj)
4368
-    {
4369
-        if (is_array($op_and_value)) {
4370
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
-            if (! $operator) {
4372
-                $php_array_like_string = array();
4373
-                foreach ($op_and_value as $key => $value) {
4374
-                    $php_array_like_string[] = "$key=>$value";
4375
-                }
4376
-                throw new EE_Error(
4377
-                    sprintf(
4378
-                        esc_html__(
4379
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4380
-                            "event_espresso"
4381
-                        ),
4382
-                        implode(",", $php_array_like_string)
4383
-                    )
4384
-                );
4385
-            }
4386
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4387
-        } else {
4388
-            $operator = '=';
4389
-            $value = $op_and_value;
4390
-        }
4391
-        // check to see if the value is actually another field
4392
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4394
-        }
4395
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396
-            // in this case, the value should be an array, or at least a comma-separated list
4397
-            // it will need to handle a little differently
4398
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4399
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4400
-            return $operator . SP . $cleaned_value;
4401
-        }
4402
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403
-            // the value should be an array with count of two.
4404
-            if (count($value) !== 2) {
4405
-                throw new EE_Error(
4406
-                    sprintf(
4407
-                        esc_html__(
4408
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4409
-                            'event_espresso'
4410
-                        ),
4411
-                        "BETWEEN"
4412
-                    )
4413
-                );
4414
-            }
4415
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
-            return $operator . SP . $cleaned_value;
4417
-        }
4418
-        if (in_array($operator, $this->valid_null_style_operators())) {
4419
-            if ($value !== null) {
4420
-                throw new EE_Error(
4421
-                    sprintf(
4422
-                        esc_html__(
4423
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4424
-                            "event_espresso"
4425
-                        ),
4426
-                        $value,
4427
-                        $operator
4428
-                    )
4429
-                );
4430
-            }
4431
-            return $operator;
4432
-        }
4433
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4435
-            // remove other junk. So just treat it as a string.
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4437
-        }
4438
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4440
-        }
4441
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442
-            throw new EE_Error(
4443
-                sprintf(
4444
-                    esc_html__(
4445
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4446
-                        'event_espresso'
4447
-                    ),
4448
-                    $operator,
4449
-                    $operator
4450
-                )
4451
-            );
4452
-        }
4453
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454
-            throw new EE_Error(
4455
-                sprintf(
4456
-                    esc_html__(
4457
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4458
-                        'event_espresso'
4459
-                    ),
4460
-                    $operator,
4461
-                    $operator
4462
-                )
4463
-            );
4464
-        }
4465
-        throw new EE_Error(
4466
-            sprintf(
4467
-                esc_html__(
4468
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4469
-                    "event_espresso"
4470
-                ),
4471
-                http_build_query($op_and_value)
4472
-            )
4473
-        );
4474
-    }
4475
-
4476
-
4477
-
4478
-    /**
4479
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4480
-     *
4481
-     * @param array                      $values
4482
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4483
-     *                                              '%s'
4484
-     * @return string
4485
-     * @throws EE_Error
4486
-     */
4487
-    public function _construct_between_value($values, $field_obj)
4488
-    {
4489
-        $cleaned_values = array();
4490
-        foreach ($values as $value) {
4491
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492
-        }
4493
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4494
-    }
4495
-
4496
-
4497
-    /**
4498
-     * Takes an array or a comma-separated list of $values and cleans them
4499
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4500
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4501
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4502
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4503
-     *
4504
-     * @param mixed                      $values    array or comma-separated string
4505
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4506
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4507
-     * @throws EE_Error
4508
-     */
4509
-    public function _construct_in_value($values, $field_obj)
4510
-    {
4511
-        $prepped = [];
4512
-        // check if the value is a CSV list
4513
-        if (is_string($values)) {
4514
-            // in which case, turn it into an array
4515
-            $values = explode(',', $values);
4516
-        }
4517
-        // make sure we only have one of each value in the list
4518
-        $values = array_unique($values);
4519
-        foreach ($values as $value) {
4520
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4521
-        }
4522
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4523
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4524
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525
-        if (empty($prepped)) {
4526
-            $all_fields = $this->field_settings();
4527
-            $first_field    = reset($all_fields);
4528
-            $main_table = $this->_get_main_table();
4529
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530
-        }
4531
-        return '(' . implode(',', $prepped) . ')';
4532
-    }
4533
-
4534
-
4535
-
4536
-    /**
4537
-     * @param mixed                      $value
4538
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
-     * @throws EE_Error
4540
-     * @return false|null|string
4541
-     */
4542
-    private function _wpdb_prepare_using_field($value, $field_obj)
4543
-    {
4544
-        /** @type WPDB $wpdb */
4545
-        global $wpdb;
4546
-        if ($field_obj instanceof EE_Model_Field_Base) {
4547
-            return $wpdb->prepare(
4548
-                $field_obj->get_wpdb_data_type(),
4549
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4550
-            );
4551
-        } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
-            throw new EE_Error(
4554
-                sprintf(
4555
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
-                    $field_obj,
4557
-                    implode(",", $this->_valid_wpdb_data_types)
4558
-                )
4559
-            );
4560
-        }
4561
-        return $wpdb->prepare($field_obj, $value);
4562
-    }
4563
-
4564
-
4565
-
4566
-    /**
4567
-     * Takes the input parameter and finds the model field that it indicates.
4568
-     *
4569
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
-     * @throws EE_Error
4571
-     * @return EE_Model_Field_Base
4572
-     */
4573
-    protected function _deduce_field_from_query_param($query_param_name)
4574
-    {
4575
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
-        // which will help us find the database table and column
4577
-        $query_param_parts = explode(".", $query_param_name);
4578
-        if (empty($query_param_parts)) {
4579
-            throw new EE_Error(sprintf(esc_html__(
4580
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4581
-                'event_espresso'
4582
-            ), $query_param_name));
4583
-        }
4584
-        $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
-        if ($number_of_parts === 1) {
4587
-            $field_name = $last_query_param_part;
4588
-            $model_obj = $this;
4589
-        } else {// $number_of_parts >= 2
4590
-            // the last part is the column name, and there are only 2parts. therefore...
4591
-            $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
-        }
4594
-        try {
4595
-            return $model_obj->field_settings_for($field_name);
4596
-        } catch (EE_Error $e) {
4597
-            return null;
4598
-        }
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
-     * alias and column which corresponds to it
4606
-     *
4607
-     * @param string $field_name
4608
-     * @throws EE_Error
4609
-     * @return string
4610
-     */
4611
-    public function _get_qualified_column_for_field($field_name)
4612
-    {
4613
-        $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
-        if ($field) {
4616
-            return $field->get_qualified_column();
4617
-        }
4618
-        throw new EE_Error(
4619
-            sprintf(
4620
-                esc_html__(
4621
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4622
-                    'event_espresso'
4623
-                ),
4624
-                $field_name,
4625
-                get_class($this)
4626
-            )
4627
-        );
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
-     * Example usage:
4635
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4636
-     *      array(),
4637
-     *      ARRAY_A,
4638
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
-     *  );
4640
-     * is equivalent to
4641
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
-     * and
4643
-     *  EEM_Event::instance()->get_all_wpdb_results(
4644
-     *      array(
4645
-     *          array(
4646
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
-     *          ),
4648
-     *          ARRAY_A,
4649
-     *          implode(
4650
-     *              ', ',
4651
-     *              array_merge(
4652
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
-     *              )
4655
-     *          )
4656
-     *      )
4657
-     *  );
4658
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
-     *
4660
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
-     *                                            and the one whose fields you are selecting for example: when querying
4662
-     *                                            tickets model and selecting fields from the tickets model you would
4663
-     *                                            leave this parameter empty, because no models are needed to join
4664
-     *                                            between the queried model and the selected one. Likewise when
4665
-     *                                            querying the datetime model and selecting fields from the tickets
4666
-     *                                            model, it would also be left empty, because there is a direct
4667
-     *                                            relation from datetimes to tickets, so no model is needed to join
4668
-     *                                            them together. However, when querying from the event model and
4669
-     *                                            selecting fields from the ticket model, you should provide the string
4670
-     *                                            'Datetime', indicating that the event model must first join to the
4671
-     *                                            datetime model in order to find its relation to ticket model.
4672
-     *                                            Also, when querying from the venue model and selecting fields from
4673
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
-     *                                            indicating you need to join the venue model to the event model,
4675
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4676
-     *                                            This string is used to deduce the prefix that gets added onto the
4677
-     *                                            models' tables qualified columns
4678
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4680
-     *                                            qualified column names
4681
-     * @return array|string
4682
-     */
4683
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
-    {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
-        $qualified_columns = array();
4687
-        foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
-        }
4690
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
-    }
4692
-
4693
-
4694
-
4695
-    /**
4696
-     * constructs the select use on special limit joins
4697
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
-     * (as that is typically where the limits would be set).
4700
-     *
4701
-     * @param  string       $table_alias The table the select is being built for
4702
-     * @param  mixed|string $limit       The limit for this select
4703
-     * @return string                The final select join element for the query.
4704
-     */
4705
-    public function _construct_limit_join_select($table_alias, $limit)
4706
-    {
4707
-        $SQL = '';
4708
-        foreach ($this->_tables as $table_obj) {
4709
-            if ($table_obj instanceof EE_Primary_Table) {
4710
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4711
-                    ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4714
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4715
-                    ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4717
-            }
4718
-        }
4719
-        return $SQL;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
-     *
4728
-     * @return string SQL
4729
-     * @throws EE_Error
4730
-     */
4731
-    public function _construct_internal_join()
4732
-    {
4733
-        $SQL = $this->_get_main_table()->get_table_sql();
4734
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
-        return $SQL;
4736
-    }
4737
-
4738
-
4739
-
4740
-    /**
4741
-     * Constructs the SQL for joining all the tables on this model.
4742
-     * Normally $alias should be the primary table's alias, but in cases where
4743
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
-     * alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     * With $alias being a secondary table's alias, this will construct SQL like:
4748
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
-     *
4750
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
-     * @return string
4752
-     */
4753
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
-    {
4755
-        $SQL = '';
4756
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
-        foreach ($this->_tables as $table_obj) {
4758
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
-                    // so we're joining to this table, meaning the table is already in
4761
-                    // the FROM statement, BUT the primary table isn't. So we want
4762
-                    // to add the inverse join sql
4763
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
-                } else {
4765
-                    // just add a regular JOIN to this table from the primary table
4766
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
-                }
4768
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
-        }
4770
-        return $SQL;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
-     * their data type (eg, '%s', '%d', etc)
4779
-     *
4780
-     * @return array
4781
-     */
4782
-    public function _get_data_types()
4783
-    {
4784
-        $data_types = array();
4785
-        foreach ($this->field_settings() as $field_obj) {
4786
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
-            /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
-        }
4790
-        return $data_types;
4791
-    }
4792
-
4793
-
4794
-
4795
-    /**
4796
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
-     *
4798
-     * @param string $model_name
4799
-     * @throws EE_Error
4800
-     * @return EEM_Base
4801
-     */
4802
-    public function get_related_model_obj($model_name)
4803
-    {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4806
-            throw new EE_Error(sprintf(esc_html__(
4807
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
-                'event_espresso'
4809
-            ), $model_name, $model_classname));
4810
-        }
4811
-        return call_user_func($model_classname . "::instance");
4812
-    }
4813
-
4814
-
4815
-
4816
-    /**
4817
-     * Returns the array of EE_ModelRelations for this model.
4818
-     *
4819
-     * @return EE_Model_Relation_Base[]
4820
-     */
4821
-    public function relation_settings()
4822
-    {
4823
-        return $this->_model_relations;
4824
-    }
4825
-
4826
-
4827
-
4828
-    /**
4829
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
-     * because without THOSE models, this model probably doesn't have much purpose.
4831
-     * (Eg, without an event, datetimes have little purpose.)
4832
-     *
4833
-     * @return EE_Belongs_To_Relation[]
4834
-     */
4835
-    public function belongs_to_relations()
4836
-    {
4837
-        $belongs_to_relations = array();
4838
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4841
-            }
4842
-        }
4843
-        return $belongs_to_relations;
4844
-    }
4845
-
4846
-
4847
-
4848
-    /**
4849
-     * Returns the specified EE_Model_Relation, or throws an exception
4850
-     *
4851
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4852
-     * @throws EE_Error
4853
-     * @return EE_Model_Relation_Base
4854
-     */
4855
-    public function related_settings_for($relation_name)
4856
-    {
4857
-        $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4859
-            throw new EE_Error(
4860
-                sprintf(
4861
-                    esc_html__(
4862
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
-                        'event_espresso'
4864
-                    ),
4865
-                    $relation_name,
4866
-                    $this->_get_class_name(),
4867
-                    implode(', ', array_keys($relatedModels))
4868
-                )
4869
-            );
4870
-        }
4871
-        return $relatedModels[ $relation_name ];
4872
-    }
4873
-
4874
-
4875
-
4876
-    /**
4877
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
-     * fields
4879
-     *
4880
-     * @param string $fieldName
4881
-     * @param boolean $include_db_only_fields
4882
-     * @throws EE_Error
4883
-     * @return EE_Model_Field_Base
4884
-     */
4885
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
-    {
4887
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4889
-            throw new EE_Error(sprintf(
4890
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
-                $fieldName,
4892
-                get_class($this)
4893
-            ));
4894
-        }
4895
-        return $fieldSettings[ $fieldName ];
4896
-    }
4897
-
4898
-
4899
-
4900
-    /**
4901
-     * Checks if this field exists on this model
4902
-     *
4903
-     * @param string $fieldName a key in the model's _field_settings array
4904
-     * @return boolean
4905
-     */
4906
-    public function has_field($fieldName)
4907
-    {
4908
-        $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4910
-            return true;
4911
-        }
4912
-        return false;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Returns whether or not this model has a relation to the specified model
4919
-     *
4920
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4921
-     * @return boolean
4922
-     */
4923
-    public function has_relation($relation_name)
4924
-    {
4925
-        $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4927
-            return true;
4928
-        }
4929
-        return false;
4930
-    }
4931
-
4932
-
4933
-
4934
-    /**
4935
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
-     * Eg, on EE_Answer that would be ANS_ID field object
4937
-     *
4938
-     * @param $field_obj
4939
-     * @return boolean
4940
-     */
4941
-    public function is_primary_key_field($field_obj)
4942
-    {
4943
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
-    }
4945
-
4946
-
4947
-
4948
-    /**
4949
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
-     * Eg, on EE_Answer that would be ANS_ID field object
4951
-     *
4952
-     * @return EE_Model_Field_Base
4953
-     * @throws EE_Error
4954
-     */
4955
-    public function get_primary_key_field()
4956
-    {
4957
-        if ($this->_primary_key_field === null) {
4958
-            foreach ($this->field_settings(true) as $field_obj) {
4959
-                if ($this->is_primary_key_field($field_obj)) {
4960
-                    $this->_primary_key_field = $field_obj;
4961
-                    break;
4962
-                }
4963
-            }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
-                throw new EE_Error(sprintf(
4966
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967
-                    get_class($this)
4968
-                ));
4969
-            }
4970
-        }
4971
-        return $this->_primary_key_field;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * Returns whether or not not there is a primary key on this model.
4978
-     * Internally does some caching.
4979
-     *
4980
-     * @return boolean
4981
-     */
4982
-    public function has_primary_key_field()
4983
-    {
4984
-        if ($this->_has_primary_key_field === null) {
4985
-            try {
4986
-                $this->get_primary_key_field();
4987
-                $this->_has_primary_key_field = true;
4988
-            } catch (EE_Error $e) {
4989
-                $this->_has_primary_key_field = false;
4990
-            }
4991
-        }
4992
-        return $this->_has_primary_key_field;
4993
-    }
4994
-
4995
-
4996
-
4997
-    /**
4998
-     * Finds the first field of type $field_class_name.
4999
-     *
5000
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
-     *                                 EE_Foreign_Key_Field, etc
5002
-     * @return EE_Model_Field_Base or null if none is found
5003
-     */
5004
-    public function get_a_field_of_type($field_class_name)
5005
-    {
5006
-        foreach ($this->field_settings() as $field) {
5007
-            if ($field instanceof $field_class_name) {
5008
-                return $field;
5009
-            }
5010
-        }
5011
-        return null;
5012
-    }
5013
-
5014
-
5015
-
5016
-    /**
5017
-     * Gets a foreign key field pointing to model.
5018
-     *
5019
-     * @param string $model_name eg Event, Registration, not EEM_Event
5020
-     * @return EE_Foreign_Key_Field_Base
5021
-     * @throws EE_Error
5022
-     */
5023
-    public function get_foreign_key_to($model_name)
5024
-    {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
-            foreach ($this->field_settings() as $field) {
5027
-                if (
5028
-                    $field instanceof EE_Foreign_Key_Field_Base
5029
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5030
-                ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
-                    break;
5033
-                }
5034
-            }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
-                throw new EE_Error(sprintf(esc_html__(
5037
-                    "There is no foreign key field pointing to model %s on model %s",
5038
-                    'event_espresso'
5039
-                ), $model_name, get_class($this)));
5040
-            }
5041
-        }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
-    }
5044
-
5045
-
5046
-
5047
-    /**
5048
-     * Gets the table name (including $wpdb->prefix) for the table alias
5049
-     *
5050
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
-     *                            Either one works
5053
-     * @return string
5054
-     */
5055
-    public function get_table_for_alias($table_alias)
5056
-    {
5057
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
-    }
5060
-
5061
-
5062
-
5063
-    /**
5064
-     * Returns a flat array of all field son this model, instead of organizing them
5065
-     * by table_alias as they are in the constructor.
5066
-     *
5067
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5069
-     */
5070
-    public function field_settings($include_db_only_fields = false)
5071
-    {
5072
-        if ($include_db_only_fields) {
5073
-            if ($this->_cached_fields === null) {
5074
-                $this->_cached_fields = array();
5075
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5076
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5078
-                    }
5079
-                }
5080
-            }
5081
-            return $this->_cached_fields;
5082
-        }
5083
-        if ($this->_cached_fields_non_db_only === null) {
5084
-            $this->_cached_fields_non_db_only = array();
5085
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5086
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
-                    /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
-                    }
5091
-                }
5092
-            }
5093
-        }
5094
-        return $this->_cached_fields_non_db_only;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     *        cycle though array of attendees and create objects out of each item
5101
-     *
5102
-     * @access        private
5103
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
-     *                           numerically indexed)
5106
-     * @throws EE_Error
5107
-     */
5108
-    protected function _create_objects($rows = array())
5109
-    {
5110
-        $array_of_objects = array();
5111
-        if (empty($rows)) {
5112
-            return array();
5113
-        }
5114
-        $count_if_model_has_no_primary_key = 0;
5115
-        $has_primary_key = $this->has_primary_key_field();
5116
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
-        foreach ((array) $rows as $row) {
5118
-            if (empty($row)) {
5119
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
-                return array();
5121
-            }
5122
-            // check if we've already set this object in the results array,
5123
-            // in which case there's no need to process it further (again)
5124
-            if ($has_primary_key) {
5125
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
-                    $row,
5127
-                    $primary_key_field->get_qualified_column(),
5128
-                    $primary_key_field->get_table_column()
5129
-                );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
-                    continue;
5132
-                }
5133
-            }
5134
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5136
-                throw new EE_Error(
5137
-                    sprintf(
5138
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5139
-                        $this->get_this_model_name(),
5140
-                        http_build_query($row)
5141
-                    )
5142
-                );
5143
-            }
5144
-            // set the timezone on the instantiated objects
5145
-            $classInstance->set_timezone($this->_timezone);
5146
-            // make sure if there is any timezone setting present that we set the timezone for the object
5147
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5149
-            // also, for all the relations of type BelongsTo, see if we can cache
5150
-            // those related models
5151
-            // (we could do this for other relations too, but if there are conditions
5152
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5153
-            // so it requires a little more thought than just caching them immediately...)
5154
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
-                    // check if this model's INFO is present. If so, cache it on the model
5157
-                    $other_model = $relation_obj->get_other_model();
5158
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
-                    // if we managed to make a model object from the results, cache it on the main model object
5160
-                    if ($other_model_obj_maybe) {
5161
-                        // set timezone on these other model objects if they are present
5162
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5163
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5164
-                    }
5165
-                }
5166
-            }
5167
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
-            // the field in the CustomSelects object
5170
-            if ($this->_custom_selections instanceof CustomSelects) {
5171
-                $classInstance->setCustomSelectsValues(
5172
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5173
-                );
5174
-            }
5175
-        }
5176
-        return $array_of_objects;
5177
-    }
5178
-
5179
-
5180
-    /**
5181
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
-     *
5184
-     * @param array $db_results_row
5185
-     * @return array
5186
-     */
5187
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
-    {
5189
-        $results = array();
5190
-        if ($this->_custom_selections instanceof CustomSelects) {
5191
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5195
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5196
-                    );
5197
-                }
5198
-            }
5199
-        }
5200
-        return $results;
5201
-    }
5202
-
5203
-
5204
-    /**
5205
-     * This will set the value for the given alias
5206
-     * @param string $value
5207
-     * @param string $datatype (one of %d, %s, %f)
5208
-     * @return int|string|float (int for %d, string for %s, float for %f)
5209
-     */
5210
-    protected function convertValueToDataType($value, $datatype)
5211
-    {
5212
-        switch ($datatype) {
5213
-            case '%f':
5214
-                return (float) $value;
5215
-            case '%d':
5216
-                return (int) $value;
5217
-            default:
5218
-                return (string) $value;
5219
-        }
5220
-    }
5221
-
5222
-
5223
-    /**
5224
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
-     * object (as set in the model_field!).
5228
-     *
5229
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
-     */
5231
-    public function create_default_object()
5232
-    {
5233
-        $this_model_fields_and_values = array();
5234
-        // setup the row using default values;
5235
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
-        }
5238
-        $className = $this->_get_class_name();
5239
-        $classInstance = EE_Registry::instance()
5240
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5241
-        return $classInstance;
5242
-    }
5243
-
5244
-
5245
-
5246
-    /**
5247
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
-     *                             or an stdClass where each property is the name of a column,
5249
-     * @return EE_Base_Class
5250
-     * @throws EE_Error
5251
-     */
5252
-    public function instantiate_class_from_array_or_object($cols_n_values)
5253
-    {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
-            $cols_n_values = get_object_vars($cols_n_values);
5256
-        }
5257
-        $primary_key = null;
5258
-        // make sure the array only has keys that are fields/columns on this model
5259
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
-        }
5263
-        $className = $this->_get_class_name();
5264
-        // check we actually found results that we can use to build our model object
5265
-        // if not, return null
5266
-        if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
-                return null;
5269
-            }
5270
-        } elseif ($this->unique_indexes()) {
5271
-            $first_column = reset($this_model_fields_n_values);
5272
-            if (empty($first_column)) {
5273
-                return null;
5274
-            }
5275
-        }
5276
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
-        if ($primary_key) {
5278
-            $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5280
-                $classInstance = EE_Registry::instance()
5281
-                                            ->load_class(
5282
-                                                $className,
5283
-                                                array($this_model_fields_n_values, $this->_timezone),
5284
-                                                true,
5285
-                                                false
5286
-                                            );
5287
-                // add this new object to the entity map
5288
-                $classInstance = $this->add_to_entity_map($classInstance);
5289
-            }
5290
-        } else {
5291
-            $classInstance = EE_Registry::instance()
5292
-                                        ->load_class(
5293
-                                            $className,
5294
-                                            array($this_model_fields_n_values, $this->_timezone),
5295
-                                            true,
5296
-                                            false
5297
-                                        );
5298
-        }
5299
-        return $classInstance;
5300
-    }
5301
-
5302
-
5303
-
5304
-    /**
5305
-     * Gets the model object from the  entity map if it exists
5306
-     *
5307
-     * @param int|string $id the ID of the model object
5308
-     * @return EE_Base_Class
5309
-     */
5310
-    public function get_from_entity_map($id)
5311
-    {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
-    }
5315
-
5316
-
5317
-
5318
-    /**
5319
-     * add_to_entity_map
5320
-     * Adds the object to the model's entity mappings
5321
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
-     *        then this method should be called immediately after the update query
5326
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5328
-     *
5329
-     * @param    EE_Base_Class $object
5330
-     * @throws EE_Error
5331
-     * @return \EE_Base_Class
5332
-     */
5333
-    public function add_to_entity_map(EE_Base_Class $object)
5334
-    {
5335
-        $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5337
-            throw new EE_Error(sprintf(
5338
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
-                is_object($object) ? get_class($object) : $object,
5340
-                $className
5341
-            ));
5342
-        }
5343
-        /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5345
-            throw new EE_Error(sprintf(esc_html__(
5346
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5347
-                "event_espresso"
5348
-            ), get_class($this)));
5349
-        }
5350
-        // double check it's not already there
5351
-        $classInstance = $this->get_from_entity_map($object->ID());
5352
-        if ($classInstance) {
5353
-            return $classInstance;
5354
-        }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
-        return $object;
5357
-    }
5358
-
5359
-
5360
-
5361
-    /**
5362
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5363
-     * if no identifier is provided, then the entire entity map is emptied
5364
-     *
5365
-     * @param int|string $id the ID of the model object
5366
-     * @return boolean
5367
-     */
5368
-    public function clear_entity_map($id = null)
5369
-    {
5370
-        if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
-            return true;
5373
-        }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
-            return true;
5377
-        }
5378
-        return false;
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
-     * Given an array where keys are column (or column alias) names and values,
5386
-     * returns an array of their corresponding field names and database values
5387
-     *
5388
-     * @param array $cols_n_values
5389
-     * @return array
5390
-     */
5391
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
-    {
5393
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * _deduce_fields_n_values_from_cols_n_values
5400
-     * Given an array where keys are column (or column alias) names and values,
5401
-     * returns an array of their corresponding field names and database values
5402
-     *
5403
-     * @param string $cols_n_values
5404
-     * @return array
5405
-     */
5406
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
-    {
5408
-        $this_model_fields_n_values = array();
5409
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
-                $cols_n_values,
5412
-                $table_obj->get_fully_qualified_pk_column(),
5413
-                $table_obj->get_pk_column()
5414
-            );
5415
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5416
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5419
-                        // prepare field as if its coming from db
5420
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
-                    }
5423
-                }
5424
-            } else {
5425
-                // the table's rows existed. Use their values
5426
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
-                            $cols_n_values,
5430
-                            $field_obj->get_qualified_column(),
5431
-                            $field_obj->get_table_column()
5432
-                        );
5433
-                    }
5434
-                }
5435
-            }
5436
-        }
5437
-        return $this_model_fields_n_values;
5438
-    }
5439
-
5440
-
5441
-    /**
5442
-     * @param $cols_n_values
5443
-     * @param $qualified_column
5444
-     * @param $regular_column
5445
-     * @return null
5446
-     * @throws EE_Error
5447
-     * @throws ReflectionException
5448
-     */
5449
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
-    {
5451
-        $value = null;
5452
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
-        // does the field on the model relate to this column retrieved from the db?
5454
-        // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5460
-            // no PK?  ok check if there is a foreign key alias set for this table
5461
-            // then check if that alias exists in the incoming data
5462
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5466
-                    [$pk_class] = explode('.', $PK_column);
5467
-                    $pk_model_name = "EEM_{$pk_class}";
5468
-                    /** @var EEM_Base $pk_model */
5469
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
-                    if ($pk_model instanceof EEM_Base) {
5471
-                        // make sure object is pulled from db and added to entity map
5472
-                        $pk_model->get_one_by_ID($value);
5473
-                    }
5474
-                    break;
5475
-                }
5476
-            }
5477
-        }
5478
-        return $value;
5479
-    }
5480
-
5481
-
5482
-
5483
-    /**
5484
-     * refresh_entity_map_from_db
5485
-     * Makes sure the model object in the entity map at $id assumes the values
5486
-     * of the database (opposite of EE_base_Class::save())
5487
-     *
5488
-     * @param int|string $id
5489
-     * @return EE_Base_Class
5490
-     * @throws EE_Error
5491
-     */
5492
-    public function refresh_entity_map_from_db($id)
5493
-    {
5494
-        $obj_in_map = $this->get_from_entity_map($id);
5495
-        if ($obj_in_map) {
5496
-            $wpdb_results = $this->_get_all_wpdb_results(
5497
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
-            );
5499
-            if ($wpdb_results && is_array($wpdb_results)) {
5500
-                $one_row = reset($wpdb_results);
5501
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
-                    $obj_in_map->set_from_db($field_name, $db_value);
5503
-                }
5504
-                // clear the cache of related model objects
5505
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
-                    $obj_in_map->clear_cache($relation_name, null, true);
5507
-                }
5508
-            }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
-            return $obj_in_map;
5511
-        }
5512
-        return $this->get_one_by_ID($id);
5513
-    }
5514
-
5515
-
5516
-
5517
-    /**
5518
-     * refresh_entity_map_with
5519
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5520
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
-     *
5524
-     * @param int|string    $id
5525
-     * @param EE_Base_Class $replacing_model_obj
5526
-     * @return \EE_Base_Class
5527
-     * @throws EE_Error
5528
-     */
5529
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5530
-    {
5531
-        $obj_in_map = $this->get_from_entity_map($id);
5532
-        if ($obj_in_map) {
5533
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5534
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
-                    $obj_in_map->set($field_name, $value);
5536
-                }
5537
-                // make the model object in the entity map's cache match the $replacing_model_obj
5538
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
-                    $obj_in_map->clear_cache($relation_name, null, true);
5540
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
-                    }
5543
-                }
5544
-            }
5545
-            return $obj_in_map;
5546
-        }
5547
-        $this->add_to_entity_map($replacing_model_obj);
5548
-        return $replacing_model_obj;
5549
-    }
5550
-
5551
-
5552
-
5553
-    /**
5554
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
-     * require_once($this->_getClassName().".class.php");
5557
-     *
5558
-     * @return string
5559
-     */
5560
-    private function _get_class_name()
5561
-    {
5562
-        return "EE_" . $this->get_this_model_name();
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5569
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
-     * it would be 'Events'.
5571
-     *
5572
-     * @param int $quantity
5573
-     * @return string
5574
-     */
5575
-    public function item_name($quantity = 1)
5576
-    {
5577
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
-    }
5579
-
5580
-
5581
-
5582
-    /**
5583
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
-     *        return $previousReturnValue.$returnString;
5595
-     * }
5596
-     * require('EEM_Answer.model.php');
5597
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5598
-     * // will output "you called my_callback! and passed args:monkeys,100"
5599
-     *
5600
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5601
-     * @param array  $args       array of original arguments passed to the function
5602
-     * @throws EE_Error
5603
-     * @return mixed whatever the plugin which calls add_filter decides
5604
-     */
5605
-    public function __call($methodName, $args)
5606
-    {
5607
-        $className = get_class($this);
5608
-        $tagName = "FHEE__{$className}__{$methodName}";
5609
-        if (! has_filter($tagName)) {
5610
-            throw new EE_Error(
5611
-                sprintf(
5612
-                    esc_html__(
5613
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5614
-                        'event_espresso'
5615
-                    ),
5616
-                    $methodName,
5617
-                    $className,
5618
-                    $tagName,
5619
-                    '<br />'
5620
-                )
5621
-            );
5622
-        }
5623
-        return apply_filters($tagName, null, $this, $args);
5624
-    }
5625
-
5626
-
5627
-
5628
-    /**
5629
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5630
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5631
-     *
5632
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5633
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5634
-     *                                                       the object's class name
5635
-     *                                                       or object's ID
5636
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5637
-     *                                                       exists in the database. If it does not, we add it
5638
-     * @throws EE_Error
5639
-     * @return EE_Base_Class
5640
-     */
5641
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5642
-    {
5643
-        $className = $this->_get_class_name();
5644
-        if ($base_class_obj_or_id instanceof $className) {
5645
-            $model_object = $base_class_obj_or_id;
5646
-        } else {
5647
-            $primary_key_field = $this->get_primary_key_field();
5648
-            if (
5649
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5650
-                && (
5651
-                    is_int($base_class_obj_or_id)
5652
-                    || is_string($base_class_obj_or_id)
5653
-                )
5654
-            ) {
5655
-                // assume it's an ID.
5656
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5657
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5658
-            } elseif (
5659
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5660
-                && is_string($base_class_obj_or_id)
5661
-            ) {
5662
-                // assume its a string representation of the object
5663
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5664
-            } else {
5665
-                throw new EE_Error(
5666
-                    sprintf(
5667
-                        esc_html__(
5668
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5669
-                            'event_espresso'
5670
-                        ),
5671
-                        $base_class_obj_or_id,
5672
-                        $this->_get_class_name(),
5673
-                        print_r($base_class_obj_or_id, true)
5674
-                    )
5675
-                );
5676
-            }
5677
-        }
5678
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5679
-            $model_object->save();
5680
-        }
5681
-        return $model_object;
5682
-    }
5683
-
5684
-
5685
-
5686
-    /**
5687
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5688
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5689
-     * returns it ID.
5690
-     *
5691
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5692
-     * @return int|string depending on the type of this model object's ID
5693
-     * @throws EE_Error
5694
-     */
5695
-    public function ensure_is_ID($base_class_obj_or_id)
5696
-    {
5697
-        $className = $this->_get_class_name();
5698
-        if ($base_class_obj_or_id instanceof $className) {
5699
-            /** @var $base_class_obj_or_id EE_Base_Class */
5700
-            $id = $base_class_obj_or_id->ID();
5701
-        } elseif (is_int($base_class_obj_or_id)) {
5702
-            // assume it's an ID
5703
-            $id = $base_class_obj_or_id;
5704
-        } elseif (is_string($base_class_obj_or_id)) {
5705
-            // assume its a string representation of the object
5706
-            $id = $base_class_obj_or_id;
5707
-        } else {
5708
-            throw new EE_Error(sprintf(
5709
-                esc_html__(
5710
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5711
-                    'event_espresso'
5712
-                ),
5713
-                $base_class_obj_or_id,
5714
-                $this->_get_class_name(),
5715
-                print_r($base_class_obj_or_id, true)
5716
-            ));
5717
-        }
5718
-        return $id;
5719
-    }
5720
-
5721
-
5722
-
5723
-    /**
5724
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5725
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5726
-     * been sanitized and converted into the appropriate domain.
5727
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5728
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5729
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5730
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5731
-     * $EVT = EEM_Event::instance(); $old_setting =
5732
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5733
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5734
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5735
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5736
-     *
5737
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5738
-     * @return void
5739
-     */
5740
-    public function assume_values_already_prepared_by_model_object(
5741
-        $values_already_prepared = self::not_prepared_by_model_object
5742
-    ) {
5743
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5744
-    }
5745
-
5746
-
5747
-
5748
-    /**
5749
-     * Read comments for assume_values_already_prepared_by_model_object()
5750
-     *
5751
-     * @return int
5752
-     */
5753
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5754
-    {
5755
-        return $this->_values_already_prepared_by_model_object;
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * Gets all the indexes on this model
5762
-     *
5763
-     * @return EE_Index[]
5764
-     */
5765
-    public function indexes()
5766
-    {
5767
-        return $this->_indexes;
5768
-    }
5769
-
5770
-
5771
-
5772
-    /**
5773
-     * Gets all the Unique Indexes on this model
5774
-     *
5775
-     * @return EE_Unique_Index[]
5776
-     */
5777
-    public function unique_indexes()
5778
-    {
5779
-        $unique_indexes = array();
5780
-        foreach ($this->_indexes as $name => $index) {
5781
-            if ($index instanceof EE_Unique_Index) {
5782
-                $unique_indexes [ $name ] = $index;
5783
-            }
5784
-        }
5785
-        return $unique_indexes;
5786
-    }
5787
-
5788
-
5789
-
5790
-    /**
5791
-     * Gets all the fields which, when combined, make the primary key.
5792
-     * This is usually just an array with 1 element (the primary key), but in cases
5793
-     * where there is no primary key, it's a combination of fields as defined
5794
-     * on a primary index
5795
-     *
5796
-     * @return EE_Model_Field_Base[] indexed by the field's name
5797
-     * @throws EE_Error
5798
-     */
5799
-    public function get_combined_primary_key_fields()
5800
-    {
5801
-        foreach ($this->indexes() as $index) {
5802
-            if ($index instanceof EE_Primary_Key_Index) {
5803
-                return $index->fields();
5804
-            }
5805
-        }
5806
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5807
-    }
5808
-
5809
-
5810
-
5811
-    /**
5812
-     * Used to build a primary key string (when the model has no primary key),
5813
-     * which can be used a unique string to identify this model object.
5814
-     *
5815
-     * @param array $fields_n_values keys are field names, values are their values.
5816
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5817
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5818
-     *                               before passing it to this function (that will convert it from columns-n-values
5819
-     *                               to field-names-n-values).
5820
-     * @return string
5821
-     * @throws EE_Error
5822
-     */
5823
-    public function get_index_primary_key_string($fields_n_values)
5824
-    {
5825
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5826
-            $fields_n_values,
5827
-            $this->get_combined_primary_key_fields()
5828
-        );
5829
-        return http_build_query($cols_n_values_for_primary_key_index);
5830
-    }
5831
-
5832
-
5833
-
5834
-    /**
5835
-     * Gets the field values from the primary key string
5836
-     *
5837
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5838
-     * @param string $index_primary_key_string
5839
-     * @return null|array
5840
-     * @throws EE_Error
5841
-     */
5842
-    public function parse_index_primary_key_string($index_primary_key_string)
5843
-    {
5844
-        $key_fields = $this->get_combined_primary_key_fields();
5845
-        // check all of them are in the $id
5846
-        $key_vals_in_combined_pk = array();
5847
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848
-        foreach ($key_fields as $key_field_name => $field_obj) {
5849
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5850
-                return null;
5851
-            }
5852
-        }
5853
-        return $key_vals_in_combined_pk;
5854
-    }
5855
-
5856
-
5857
-
5858
-    /**
5859
-     * verifies that an array of key-value pairs for model fields has a key
5860
-     * for each field comprising the primary key index
5861
-     *
5862
-     * @param array $key_vals
5863
-     * @return boolean
5864
-     * @throws EE_Error
5865
-     */
5866
-    public function has_all_combined_primary_key_fields($key_vals)
5867
-    {
5868
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869
-        foreach ($keys_it_should_have as $key) {
5870
-            if (! isset($key_vals[ $key ])) {
5871
-                return false;
5872
-            }
5873
-        }
5874
-        return true;
5875
-    }
5876
-
5877
-
5878
-
5879
-    /**
5880
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5881
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5882
-     *
5883
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5884
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5885
-     * @throws EE_Error
5886
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5887
-     *                                                              indexed)
5888
-     */
5889
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5890
-    {
5891
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5892
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5893
-        } elseif (is_array($model_object_or_attributes_array)) {
5894
-            $attributes_array = $model_object_or_attributes_array;
5895
-        } else {
5896
-            throw new EE_Error(sprintf(esc_html__(
5897
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5898
-                "event_espresso"
5899
-            ), $model_object_or_attributes_array));
5900
-        }
5901
-        // even copies obviously won't have the same ID, so remove the primary key
5902
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
-            unset($attributes_array[ $this->primary_key_name() ]);
5905
-        }
5906
-        if (isset($query_params[0])) {
5907
-            $query_params[0] = array_merge($attributes_array, $query_params);
5908
-        } else {
5909
-            $query_params[0] = $attributes_array;
5910
-        }
5911
-        return $this->get_all($query_params);
5912
-    }
5913
-
5914
-
5915
-
5916
-    /**
5917
-     * Gets the first copy we find. See get_all_copies for more details
5918
-     *
5919
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5920
-     * @param array $query_params
5921
-     * @return EE_Base_Class
5922
-     * @throws EE_Error
5923
-     */
5924
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925
-    {
5926
-        if (! is_array($query_params)) {
5927
-            EE_Error::doing_it_wrong(
5928
-                'EEM_Base::get_one_copy',
5929
-                sprintf(
5930
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5931
-                    gettype($query_params)
5932
-                ),
5933
-                '4.6.0'
5934
-            );
5935
-            $query_params = array();
5936
-        }
5937
-        $query_params['limit'] = 1;
5938
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5939
-        if (is_array($copies)) {
5940
-            return array_shift($copies);
5941
-        }
5942
-        return null;
5943
-    }
5944
-
5945
-
5946
-
5947
-    /**
5948
-     * Updates the item with the specified id. Ignores default query parameters because
5949
-     * we have specified the ID, and its assumed we KNOW what we're doing
5950
-     *
5951
-     * @param array      $fields_n_values keys are field names, values are their new values
5952
-     * @param int|string $id              the value of the primary key to update
5953
-     * @return int number of rows updated
5954
-     * @throws EE_Error
5955
-     */
5956
-    public function update_by_ID($fields_n_values, $id)
5957
-    {
5958
-        $query_params = array(
5959
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5960
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5961
-        );
5962
-        return $this->update($fields_n_values, $query_params);
5963
-    }
5964
-
5965
-
5966
-
5967
-    /**
5968
-     * Changes an operator which was supplied to the models into one usable in SQL
5969
-     *
5970
-     * @param string $operator_supplied
5971
-     * @return string an operator which can be used in SQL
5972
-     * @throws EE_Error
5973
-     */
5974
-    private function _prepare_operator_for_sql($operator_supplied)
5975
-    {
5976
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5977
-            : null;
5978
-        if ($sql_operator) {
5979
-            return $sql_operator;
5980
-        }
5981
-        throw new EE_Error(
5982
-            sprintf(
5983
-                esc_html__(
5984
-                    "The operator '%s' is not in the list of valid operators: %s",
5985
-                    "event_espresso"
5986
-                ),
5987
-                $operator_supplied,
5988
-                implode(",", array_keys($this->_valid_operators))
5989
-            )
5990
-        );
5991
-    }
5992
-
5993
-
5994
-
5995
-    /**
5996
-     * Gets the valid operators
5997
-     * @return array keys are accepted strings, values are the SQL they are converted to
5998
-     */
5999
-    public function valid_operators()
6000
-    {
6001
-        return $this->_valid_operators;
6002
-    }
6003
-
6004
-
6005
-
6006
-    /**
6007
-     * Gets the between-style operators (take 2 arguments).
6008
-     * @return array keys are accepted strings, values are the SQL they are converted to
6009
-     */
6010
-    public function valid_between_style_operators()
6011
-    {
6012
-        return array_intersect(
6013
-            $this->valid_operators(),
6014
-            $this->_between_style_operators
6015
-        );
6016
-    }
6017
-
6018
-    /**
6019
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6020
-     * @return array keys are accepted strings, values are the SQL they are converted to
6021
-     */
6022
-    public function valid_like_style_operators()
6023
-    {
6024
-        return array_intersect(
6025
-            $this->valid_operators(),
6026
-            $this->_like_style_operators
6027
-        );
6028
-    }
6029
-
6030
-    /**
6031
-     * Gets the "in"-style operators
6032
-     * @return array keys are accepted strings, values are the SQL they are converted to
6033
-     */
6034
-    public function valid_in_style_operators()
6035
-    {
6036
-        return array_intersect(
6037
-            $this->valid_operators(),
6038
-            $this->_in_style_operators
6039
-        );
6040
-    }
6041
-
6042
-    /**
6043
-     * Gets the "null"-style operators (accept no arguments)
6044
-     * @return array keys are accepted strings, values are the SQL they are converted to
6045
-     */
6046
-    public function valid_null_style_operators()
6047
-    {
6048
-        return array_intersect(
6049
-            $this->valid_operators(),
6050
-            $this->_null_style_operators
6051
-        );
6052
-    }
6053
-
6054
-    /**
6055
-     * Gets an array where keys are the primary keys and values are their 'names'
6056
-     * (as determined by the model object's name() function, which is often overridden)
6057
-     *
6058
-     * @param array $query_params like get_all's
6059
-     * @return string[]
6060
-     * @throws EE_Error
6061
-     */
6062
-    public function get_all_names($query_params = array())
6063
-    {
6064
-        $objs = $this->get_all($query_params);
6065
-        $names = array();
6066
-        foreach ($objs as $obj) {
6067
-            $names[ $obj->ID() ] = $obj->name();
6068
-        }
6069
-        return $names;
6070
-    }
6071
-
6072
-
6073
-
6074
-    /**
6075
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6076
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6077
-     * this is duplicated effort and reduces efficiency) you would be better to use
6078
-     * array_keys() on $model_objects.
6079
-     *
6080
-     * @param \EE_Base_Class[] $model_objects
6081
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6082
-     *                                               in the returned array
6083
-     * @return array
6084
-     * @throws EE_Error
6085
-     */
6086
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087
-    {
6088
-        if (! $this->has_primary_key_field()) {
6089
-            if (WP_DEBUG) {
6090
-                EE_Error::add_error(
6091
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6092
-                    __FILE__,
6093
-                    __FUNCTION__,
6094
-                    __LINE__
6095
-                );
6096
-            }
6097
-        }
6098
-        $IDs = array();
6099
-        foreach ($model_objects as $model_object) {
6100
-            $id = $model_object->ID();
6101
-            if (! $id) {
6102
-                if ($filter_out_empty_ids) {
6103
-                    continue;
6104
-                }
6105
-                if (WP_DEBUG) {
6106
-                    EE_Error::add_error(
6107
-                        esc_html__(
6108
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6109
-                            'event_espresso'
6110
-                        ),
6111
-                        __FILE__,
6112
-                        __FUNCTION__,
6113
-                        __LINE__
6114
-                    );
6115
-                }
6116
-            }
6117
-            $IDs[] = $id;
6118
-        }
6119
-        return $IDs;
6120
-    }
6121
-
6122
-
6123
-
6124
-    /**
6125
-     * Returns the string used in capabilities relating to this model. If there
6126
-     * are no capabilities that relate to this model returns false
6127
-     *
6128
-     * @return string|false
6129
-     */
6130
-    public function cap_slug()
6131
-    {
6132
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6133
-    }
6134
-
6135
-
6136
-
6137
-    /**
6138
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6139
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6140
-     * only returns the cap restrictions array in that context (ie, the array
6141
-     * at that key)
6142
-     *
6143
-     * @param string $context
6144
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6145
-     * @throws EE_Error
6146
-     */
6147
-    public function cap_restrictions($context = EEM_Base::caps_read)
6148
-    {
6149
-        EEM_Base::verify_is_valid_cap_context($context);
6150
-        // check if we ought to run the restriction generator first
6151
-        if (
6152
-            isset($this->_cap_restriction_generators[ $context ])
6153
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6155
-        ) {
6156
-            $this->_cap_restrictions[ $context ] = array_merge(
6157
-                $this->_cap_restrictions[ $context ],
6158
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6159
-            );
6160
-        }
6161
-        // and make sure we've finalized the construction of each restriction
6162
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6163
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164
-                $where_conditions_obj->_finalize_construct($this);
6165
-            }
6166
-        }
6167
-        return $this->_cap_restrictions[ $context ];
6168
-    }
6169
-
6170
-
6171
-
6172
-    /**
6173
-     * Indicating whether or not this model thinks its a wp core model
6174
-     *
6175
-     * @return boolean
6176
-     */
6177
-    public function is_wp_core_model()
6178
-    {
6179
-        return $this->_wp_core_model;
6180
-    }
6181
-
6182
-
6183
-
6184
-    /**
6185
-     * Gets all the caps that are missing which impose a restriction on
6186
-     * queries made in this context
6187
-     *
6188
-     * @param string $context one of EEM_Base::caps_ constants
6189
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6190
-     * @throws EE_Error
6191
-     */
6192
-    public function caps_missing($context = EEM_Base::caps_read)
6193
-    {
6194
-        $missing_caps = array();
6195
-        $cap_restrictions = $this->cap_restrictions($context);
6196
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197
-            if (
6198
-                ! EE_Capabilities::instance()
6199
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6200
-            ) {
6201
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6202
-            }
6203
-        }
6204
-        return $missing_caps;
6205
-    }
6206
-
6207
-
6208
-
6209
-    /**
6210
-     * Gets the mapping from capability contexts to action strings used in capability names
6211
-     *
6212
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6213
-     * one of 'read', 'edit', or 'delete'
6214
-     */
6215
-    public function cap_contexts_to_cap_action_map()
6216
-    {
6217
-        return apply_filters(
6218
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6219
-            $this->_cap_contexts_to_cap_action_map,
6220
-            $this
6221
-        );
6222
-    }
6223
-
6224
-
6225
-
6226
-    /**
6227
-     * Gets the action string for the specified capability context
6228
-     *
6229
-     * @param string $context
6230
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6231
-     * @throws EE_Error
6232
-     */
6233
-    public function cap_action_for_context($context)
6234
-    {
6235
-        $mapping = $this->cap_contexts_to_cap_action_map();
6236
-        if (isset($mapping[ $context ])) {
6237
-            return $mapping[ $context ];
6238
-        }
6239
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240
-            return $action;
6241
-        }
6242
-        throw new EE_Error(
6243
-            sprintf(
6244
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6245
-                $context,
6246
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6247
-            )
6248
-        );
6249
-    }
6250
-
6251
-
6252
-
6253
-    /**
6254
-     * Returns all the capability contexts which are valid when querying models
6255
-     *
6256
-     * @return array
6257
-     */
6258
-    public static function valid_cap_contexts()
6259
-    {
6260
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6261
-            self::caps_read,
6262
-            self::caps_read_admin,
6263
-            self::caps_edit,
6264
-            self::caps_delete,
6265
-        ));
6266
-    }
6267
-
6268
-
6269
-
6270
-    /**
6271
-     * Returns all valid options for 'default_where_conditions'
6272
-     *
6273
-     * @return array
6274
-     */
6275
-    public static function valid_default_where_conditions()
6276
-    {
6277
-        return array(
6278
-            EEM_Base::default_where_conditions_all,
6279
-            EEM_Base::default_where_conditions_this_only,
6280
-            EEM_Base::default_where_conditions_others_only,
6281
-            EEM_Base::default_where_conditions_minimum_all,
6282
-            EEM_Base::default_where_conditions_minimum_others,
6283
-            EEM_Base::default_where_conditions_none
6284
-        );
6285
-    }
6286
-
6287
-    // public static function default_where_conditions_full
6288
-    /**
6289
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6290
-     *
6291
-     * @param string $context
6292
-     * @return bool
6293
-     * @throws EE_Error
6294
-     */
6295
-    public static function verify_is_valid_cap_context($context)
6296
-    {
6297
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6298
-        if (in_array($context, $valid_cap_contexts)) {
6299
-            return true;
6300
-        }
6301
-        throw new EE_Error(
6302
-            sprintf(
6303
-                esc_html__(
6304
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6305
-                    'event_espresso'
6306
-                ),
6307
-                $context,
6308
-                'EEM_Base',
6309
-                implode(',', $valid_cap_contexts)
6310
-            )
6311
-        );
6312
-    }
6313
-
6314
-
6315
-
6316
-    /**
6317
-     * Clears all the models field caches. This is only useful when a sub-class
6318
-     * might have added a field or something and these caches might be invalidated
6319
-     */
6320
-    protected function _invalidate_field_caches()
6321
-    {
6322
-        $this->_cache_foreign_key_to_fields = array();
6323
-        $this->_cached_fields = null;
6324
-        $this->_cached_fields_non_db_only = null;
6325
-    }
6326
-
6327
-
6328
-
6329
-    /**
6330
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6331
-     * (eg "and", "or", "not").
6332
-     *
6333
-     * @return array
6334
-     */
6335
-    public function logic_query_param_keys()
6336
-    {
6337
-        return $this->_logic_query_param_keys;
6338
-    }
6339
-
6340
-
6341
-
6342
-    /**
6343
-     * Determines whether or not the where query param array key is for a logic query param.
6344
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6345
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6346
-     *
6347
-     * @param $query_param_key
6348
-     * @return bool
6349
-     */
6350
-    public function is_logic_query_param_key($query_param_key)
6351
-    {
6352
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353
-            if (
6354
-                $query_param_key === $logic_query_param_key
6355
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6356
-            ) {
6357
-                return true;
6358
-            }
6359
-        }
6360
-        return false;
6361
-    }
6362
-
6363
-    /**
6364
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6365
-     * @since 4.9.74.p
6366
-     * @return boolean
6367
-     */
6368
-    public function hasPassword()
6369
-    {
6370
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6371
-        if ($this->has_password_field === null) {
6372
-            $password_field = $this->getPasswordField();
6373
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6374
-        }
6375
-        return $this->has_password_field;
6376
-    }
6377
-
6378
-    /**
6379
-     * Returns the password field on this model, if there is one
6380
-     * @since 4.9.74.p
6381
-     * @return EE_Password_Field|null
6382
-     */
6383
-    public function getPasswordField()
6384
-    {
6385
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6386
-        // there's no need to search for it. If we don't know yet, then find out
6387
-        if ($this->has_password_field === null && $this->password_field === null) {
6388
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6389
-        }
6390
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6391
-        return $this->password_field;
6392
-    }
6393
-
6394
-
6395
-    /**
6396
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6397
-     * @since 4.9.74.p
6398
-     * @return EE_Model_Field_Base[]
6399
-     * @throws EE_Error
6400
-     */
6401
-    public function getPasswordProtectedFields()
6402
-    {
6403
-        $password_field = $this->getPasswordField();
6404
-        $fields = array();
6405
-        if ($password_field instanceof EE_Password_Field) {
6406
-            $field_names = $password_field->protectedFields();
6407
-            foreach ($field_names as $field_name) {
6408
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6409
-            }
6410
-        }
6411
-        return $fields;
6412
-    }
6413
-
6414
-
6415
-    /**
6416
-     * Checks if the current user can perform the requested action on this model
6417
-     * @since 4.9.74.p
6418
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6419
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6420
-     * @return bool
6421
-     * @throws EE_Error
6422
-     * @throws InvalidArgumentException
6423
-     * @throws InvalidDataTypeException
6424
-     * @throws InvalidInterfaceException
6425
-     * @throws ReflectionException
6426
-     * @throws UnexpectedEntityException
6427
-     */
6428
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6429
-    {
6430
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432
-        }
6433
-        if (!is_array($model_obj_or_fields_n_values)) {
6434
-            throw new UnexpectedEntityException(
6435
-                $model_obj_or_fields_n_values,
6436
-                'EE_Base_Class',
6437
-                sprintf(
6438
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6439
-                    __FUNCTION__
6440
-                )
6441
-            );
6442
-        }
6443
-        return $this->exists(
6444
-            $this->alter_query_params_to_restrict_by_ID(
6445
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6446
-                array(
6447
-                    'default_where_conditions' => 'none',
6448
-                    'caps'                     => $cap_to_check,
6449
-                )
6450
-            )
6451
-        );
6452
-    }
6453
-
6454
-    /**
6455
-     * Returns the query param where conditions key to the password affecting this model.
6456
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6457
-     * @since 4.9.74.p
6458
-     * @return null|string
6459
-     * @throws EE_Error
6460
-     * @throws InvalidArgumentException
6461
-     * @throws InvalidDataTypeException
6462
-     * @throws InvalidInterfaceException
6463
-     * @throws ModelConfigurationException
6464
-     * @throws ReflectionException
6465
-     */
6466
-    public function modelChainAndPassword()
6467
-    {
6468
-        if ($this->model_chain_to_password === null) {
6469
-            throw new ModelConfigurationException(
6470
-                $this,
6471
-                esc_html_x(
6472
-                // @codingStandardsIgnoreStart
6473
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6474
-                    // @codingStandardsIgnoreEnd
6475
-                    '1: model name',
6476
-                    'event_espresso'
6477
-                )
6478
-            );
6479
-        }
6480
-        if ($this->model_chain_to_password === '') {
6481
-            $model_with_password = $this;
6482
-        } else {
6483
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6484
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6485
-            } else {
6486
-                $last_model_in_chain = $this->model_chain_to_password;
6487
-            }
6488
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6489
-        }
6490
-
6491
-        $password_field = $model_with_password->getPasswordField();
6492
-        if ($password_field instanceof EE_Password_Field) {
6493
-            $password_field_name = $password_field->get_name();
6494
-        } else {
6495
-            throw new ModelConfigurationException(
6496
-                $this,
6497
-                sprintf(
6498
-                    esc_html_x(
6499
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6500
-                        '1: model name, 2: special string',
6501
-                        'event_espresso'
6502
-                    ),
6503
-                    $model_with_password->get_this_model_name(),
6504
-                    $this->model_chain_to_password
6505
-                )
6506
-            );
6507
-        }
6508
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6509
-    }
6510
-
6511
-    /**
6512
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6513
-     * or if this model itself has a password affecting access to some of its other fields.
6514
-     * @since 4.9.74.p
6515
-     * @return boolean
6516
-     */
6517
-    public function restrictedByRelatedModelPassword()
6518
-    {
6519
-        return $this->model_chain_to_password !== null;
6520
-    }
3817
+		}
3818
+		return $null_friendly_where_conditions;
3819
+	}
3820
+
3821
+
3822
+
3823
+	/**
3824
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3825
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3826
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3827
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3828
+	 *
3829
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3830
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3831
+	 */
3832
+	private function _get_default_where_conditions($model_relation_path = null)
3833
+	{
3834
+		if ($this->_ignore_where_strategy) {
3835
+			return array();
3836
+		}
3837
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3838
+	}
3839
+
3840
+
3841
+
3842
+	/**
3843
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3844
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3845
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3846
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3847
+	 * Similar to _get_default_where_conditions
3848
+	 *
3849
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3850
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3851
+	 */
3852
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3853
+	{
3854
+		if ($this->_ignore_where_strategy) {
3855
+			return array();
3856
+		}
3857
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3858
+	}
3859
+
3860
+
3861
+
3862
+	/**
3863
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3864
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3865
+	 *
3866
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3867
+	 * @return string
3868
+	 * @throws EE_Error
3869
+	 */
3870
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3871
+	{
3872
+		$selects = $this->_get_columns_to_select_for_this_model();
3873
+		foreach (
3874
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3875
+		) {
3876
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3877
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3878
+			foreach ($other_model_selects as $key => $value) {
3879
+				$selects[] = $value;
3880
+			}
3881
+		}
3882
+		return implode(", ", $selects);
3883
+	}
3884
+
3885
+
3886
+
3887
+	/**
3888
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3889
+	 * So that's going to be the columns for all the fields on the model
3890
+	 *
3891
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3892
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3893
+	 */
3894
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3895
+	{
3896
+		$fields = $this->field_settings();
3897
+		$selects = array();
3898
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3899
+			$model_relation_chain,
3900
+			$this->get_this_model_name()
3901
+		);
3902
+		foreach ($fields as $field_obj) {
3903
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3904
+						 . $field_obj->get_table_alias()
3905
+						 . "."
3906
+						 . $field_obj->get_table_column()
3907
+						 . " AS '"
3908
+						 . $table_alias_with_model_relation_chain_prefix
3909
+						 . $field_obj->get_table_alias()
3910
+						 . "."
3911
+						 . $field_obj->get_table_column()
3912
+						 . "'";
3913
+		}
3914
+		// make sure we are also getting the PKs of each table
3915
+		$tables = $this->get_tables();
3916
+		if (count($tables) > 1) {
3917
+			foreach ($tables as $table_obj) {
3918
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919
+									   . $table_obj->get_fully_qualified_pk_column();
3920
+				if (! in_array($qualified_pk_column, $selects)) {
3921
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922
+				}
3923
+			}
3924
+		}
3925
+		return $selects;
3926
+	}
3927
+
3928
+
3929
+
3930
+	/**
3931
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3932
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3933
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3934
+	 * SQL for joining, and the data types
3935
+	 *
3936
+	 * @param null|string                 $original_query_param
3937
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3938
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3939
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3940
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3941
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3942
+	 *                                                          or 'Registration's
3943
+	 * @param string                      $original_query_param what it originally was (eg
3944
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3945
+	 *                                                          matches $query_param
3946
+	 * @throws EE_Error
3947
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3948
+	 */
3949
+	private function _extract_related_model_info_from_query_param(
3950
+		$query_param,
3951
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3952
+		$query_param_type,
3953
+		$original_query_param = null
3954
+	) {
3955
+		if ($original_query_param === null) {
3956
+			$original_query_param = $query_param;
3957
+		}
3958
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3959
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3960
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3961
+		$allow_fields = in_array(
3962
+			$query_param_type,
3963
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3964
+			true
3965
+		);
3966
+		// check to see if we have a field on this model
3967
+		$this_model_fields = $this->field_settings(true);
3968
+		if (array_key_exists($query_param, $this_model_fields)) {
3969
+			if ($allow_fields) {
3970
+				return;
3971
+			}
3972
+			throw new EE_Error(
3973
+				sprintf(
3974
+					esc_html__(
3975
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3976
+						"event_espresso"
3977
+					),
3978
+					$query_param,
3979
+					get_class($this),
3980
+					$query_param_type,
3981
+					$original_query_param
3982
+				)
3983
+			);
3984
+		}
3985
+		// check if this is a special logic query param
3986
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3987
+			if ($allow_logic_query_params) {
3988
+				return;
3989
+			}
3990
+			throw new EE_Error(
3991
+				sprintf(
3992
+					esc_html__(
3993
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3994
+						'event_espresso'
3995
+					),
3996
+					implode('", "', $this->_logic_query_param_keys),
3997
+					$query_param,
3998
+					get_class($this),
3999
+					'<br />',
4000
+					"\t"
4001
+					. ' $passed_in_query_info = <pre>'
4002
+					. print_r($passed_in_query_info, true)
4003
+					. '</pre>'
4004
+					. "\n\t"
4005
+					. ' $query_param_type = '
4006
+					. $query_param_type
4007
+					. "\n\t"
4008
+					. ' $original_query_param = '
4009
+					. $original_query_param
4010
+				)
4011
+			);
4012
+		}
4013
+		// check if it's a custom selection
4014
+		if (
4015
+			$this->_custom_selections instanceof CustomSelects
4016
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4017
+		) {
4018
+			return;
4019
+		}
4020
+		// check if has a model name at the beginning
4021
+		// and
4022
+		// check if it's a field on a related model
4023
+		if (
4024
+			$this->extractJoinModelFromQueryParams(
4025
+				$passed_in_query_info,
4026
+				$query_param,
4027
+				$original_query_param,
4028
+				$query_param_type
4029
+			)
4030
+		) {
4031
+			return;
4032
+		}
4033
+
4034
+		// ok so $query_param didn't start with a model name
4035
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4036
+		// it's wack, that's what it is
4037
+		throw new EE_Error(
4038
+			sprintf(
4039
+				esc_html__(
4040
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4041
+					"event_espresso"
4042
+				),
4043
+				$query_param,
4044
+				get_class($this),
4045
+				$query_param_type,
4046
+				$original_query_param
4047
+			)
4048
+		);
4049
+	}
4050
+
4051
+
4052
+	/**
4053
+	 * Extracts any possible join model information from the provided possible_join_string.
4054
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4055
+	 * parts that should be added to the query.
4056
+	 *
4057
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4058
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4059
+	 * @param null|string                 $original_query_param
4060
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4061
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4062
+	 * @return bool  returns true if a join was added and false if not.
4063
+	 * @throws EE_Error
4064
+	 */
4065
+	private function extractJoinModelFromQueryParams(
4066
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4067
+		$possible_join_string,
4068
+		$original_query_param,
4069
+		$query_parameter_type
4070
+	) {
4071
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4073
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4075
+				if ($possible_join_string === '') {
4076
+					// nothing left to $query_param
4077
+					// we should actually end in a field name, not a model like this!
4078
+					throw new EE_Error(
4079
+						sprintf(
4080
+							esc_html__(
4081
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4082
+								"event_espresso"
4083
+							),
4084
+							$possible_join_string,
4085
+							$query_parameter_type,
4086
+							get_class($this),
4087
+							$valid_related_model_name
4088
+						)
4089
+					);
4090
+				}
4091
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4092
+				$related_model_obj->_extract_related_model_info_from_query_param(
4093
+					$possible_join_string,
4094
+					$query_info_carrier,
4095
+					$query_parameter_type,
4096
+					$original_query_param
4097
+				);
4098
+				return true;
4099
+			}
4100
+			if ($possible_join_string === $valid_related_model_name) {
4101
+				$this->_add_join_to_model(
4102
+					$valid_related_model_name,
4103
+					$query_info_carrier,
4104
+					$original_query_param
4105
+				);
4106
+				return true;
4107
+			}
4108
+		}
4109
+		return false;
4110
+	}
4111
+
4112
+
4113
+	/**
4114
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4115
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4116
+	 * @throws EE_Error
4117
+	 */
4118
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4119
+	{
4120
+		if (
4121
+			$this->_custom_selections instanceof CustomSelects
4122
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4123
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4124
+			)
4125
+		) {
4126
+			$original_selects = $this->_custom_selections->originalSelects();
4127
+			foreach ($original_selects as $alias => $select_configuration) {
4128
+				$this->extractJoinModelFromQueryParams(
4129
+					$query_info_carrier,
4130
+					$select_configuration[0],
4131
+					$select_configuration[0],
4132
+					'custom_selects'
4133
+				);
4134
+			}
4135
+		}
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4142
+	 * and store it on $passed_in_query_info
4143
+	 *
4144
+	 * @param string                      $model_name
4145
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4146
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4147
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4148
+	 *                                                          and are adding a join to 'Payment' with the original
4149
+	 *                                                          query param key
4150
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4151
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4152
+	 *                                                          Payment wants to add default query params so that it
4153
+	 *                                                          will know what models to prepend onto its default query
4154
+	 *                                                          params or in case it wants to rename tables (in case
4155
+	 *                                                          there are multiple joins to the same table)
4156
+	 * @return void
4157
+	 * @throws EE_Error
4158
+	 */
4159
+	private function _add_join_to_model(
4160
+		$model_name,
4161
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4162
+		$original_query_param
4163
+	) {
4164
+		$relation_obj = $this->related_settings_for($model_name);
4165
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4166
+		// check if the relation is HABTM, because then we're essentially doing two joins
4167
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4168
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4169
+			$join_model_obj = $relation_obj->get_join_model();
4170
+			// replace the model specified with the join model for this relation chain, whi
4171
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4172
+				$model_name,
4173
+				$join_model_obj->get_this_model_name(),
4174
+				$model_relation_chain
4175
+			);
4176
+			$passed_in_query_info->merge(
4177
+				new EE_Model_Query_Info_Carrier(
4178
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4179
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4180
+				)
4181
+			);
4182
+		}
4183
+		// now just join to the other table pointed to by the relation object, and add its data types
4184
+		$passed_in_query_info->merge(
4185
+			new EE_Model_Query_Info_Carrier(
4186
+				array($model_relation_chain => $model_name),
4187
+				$relation_obj->get_join_statement($model_relation_chain)
4188
+			)
4189
+		);
4190
+	}
4191
+
4192
+
4193
+
4194
+	/**
4195
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4196
+	 *
4197
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4198
+	 * @return string of SQL
4199
+	 * @throws EE_Error
4200
+	 */
4201
+	private function _construct_where_clause($where_params)
4202
+	{
4203
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204
+		if ($SQL) {
4205
+			return " WHERE " . $SQL;
4206
+		}
4207
+		return '';
4208
+	}
4209
+
4210
+
4211
+
4212
+	/**
4213
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4214
+	 * and should be passed HAVING parameters, not WHERE parameters
4215
+	 *
4216
+	 * @param array $having_params
4217
+	 * @return string
4218
+	 * @throws EE_Error
4219
+	 */
4220
+	private function _construct_having_clause($having_params)
4221
+	{
4222
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223
+		if ($SQL) {
4224
+			return " HAVING " . $SQL;
4225
+		}
4226
+		return '';
4227
+	}
4228
+
4229
+
4230
+	/**
4231
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4232
+	 * Event_Meta.meta_value = 'foo'))"
4233
+	 *
4234
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4235
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4236
+	 * @throws EE_Error
4237
+	 * @return string of SQL
4238
+	 */
4239
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4240
+	{
4241
+		$where_clauses = array();
4242
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4244
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4245
+				switch ($query_param) {
4246
+					case 'not':
4247
+					case 'NOT':
4248
+						$where_clauses[] = "! ("
4249
+										   . $this->_construct_condition_clause_recursive(
4250
+											   $op_and_value_or_sub_condition,
4251
+											   $glue
4252
+										   )
4253
+										   . ")";
4254
+						break;
4255
+					case 'and':
4256
+					case 'AND':
4257
+						$where_clauses[] = " ("
4258
+										   . $this->_construct_condition_clause_recursive(
4259
+											   $op_and_value_or_sub_condition,
4260
+											   ' AND '
4261
+										   )
4262
+										   . ")";
4263
+						break;
4264
+					case 'or':
4265
+					case 'OR':
4266
+						$where_clauses[] = " ("
4267
+										   . $this->_construct_condition_clause_recursive(
4268
+											   $op_and_value_or_sub_condition,
4269
+											   ' OR '
4270
+										   )
4271
+										   . ")";
4272
+						break;
4273
+				}
4274
+			} else {
4275
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4276
+				// if it's not a normal field, maybe it's a custom selection?
4277
+				if (! $field_obj) {
4278
+					if ($this->_custom_selections instanceof CustomSelects) {
4279
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280
+					} else {
4281
+						throw new EE_Error(sprintf(esc_html__(
4282
+							"%s is neither a valid model field name, nor a custom selection",
4283
+							"event_espresso"
4284
+						), $query_param));
4285
+					}
4286
+				}
4287
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4289
+			}
4290
+		}
4291
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4292
+	}
4293
+
4294
+
4295
+
4296
+	/**
4297
+	 * Takes the input parameter and extract the table name (alias) and column name
4298
+	 *
4299
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4300
+	 * @throws EE_Error
4301
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4302
+	 */
4303
+	private function _deduce_column_name_from_query_param($query_param)
4304
+	{
4305
+		$field = $this->_deduce_field_from_query_param($query_param);
4306
+		if ($field) {
4307
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4308
+				$field->get_model_name(),
4309
+				$query_param
4310
+			);
4311
+			return $table_alias_prefix . $field->get_qualified_column();
4312
+		}
4313
+		if (
4314
+			$this->_custom_selections instanceof CustomSelects
4315
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4316
+		) {
4317
+			// maybe it's custom selection item?
4318
+			// if so, just use it as the "column name"
4319
+			return $query_param;
4320
+		}
4321
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4322
+			? implode(',', $this->_custom_selections->columnAliases())
4323
+			: '';
4324
+		throw new EE_Error(
4325
+			sprintf(
4326
+				esc_html__(
4327
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4328
+					"event_espresso"
4329
+				),
4330
+				$query_param,
4331
+				$custom_select_aliases
4332
+			)
4333
+		);
4334
+	}
4335
+
4336
+
4337
+
4338
+	/**
4339
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4340
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4341
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4342
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4343
+	 *
4344
+	 * @param string $condition_query_param_key
4345
+	 * @return string
4346
+	 */
4347
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4348
+	{
4349
+		$pos_of_star = strpos($condition_query_param_key, '*');
4350
+		if ($pos_of_star === false) {
4351
+			return $condition_query_param_key;
4352
+		}
4353
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4354
+		return $condition_query_param_sans_star;
4355
+	}
4356
+
4357
+
4358
+
4359
+	/**
4360
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4361
+	 *
4362
+	 * @param                            mixed      array | string    $op_and_value
4363
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4364
+	 * @throws EE_Error
4365
+	 * @return string
4366
+	 */
4367
+	private function _construct_op_and_value($op_and_value, $field_obj)
4368
+	{
4369
+		if (is_array($op_and_value)) {
4370
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
+			if (! $operator) {
4372
+				$php_array_like_string = array();
4373
+				foreach ($op_and_value as $key => $value) {
4374
+					$php_array_like_string[] = "$key=>$value";
4375
+				}
4376
+				throw new EE_Error(
4377
+					sprintf(
4378
+						esc_html__(
4379
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4380
+							"event_espresso"
4381
+						),
4382
+						implode(",", $php_array_like_string)
4383
+					)
4384
+				);
4385
+			}
4386
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4387
+		} else {
4388
+			$operator = '=';
4389
+			$value = $op_and_value;
4390
+		}
4391
+		// check to see if the value is actually another field
4392
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4394
+		}
4395
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396
+			// in this case, the value should be an array, or at least a comma-separated list
4397
+			// it will need to handle a little differently
4398
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4399
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4400
+			return $operator . SP . $cleaned_value;
4401
+		}
4402
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403
+			// the value should be an array with count of two.
4404
+			if (count($value) !== 2) {
4405
+				throw new EE_Error(
4406
+					sprintf(
4407
+						esc_html__(
4408
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4409
+							'event_espresso'
4410
+						),
4411
+						"BETWEEN"
4412
+					)
4413
+				);
4414
+			}
4415
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
+			return $operator . SP . $cleaned_value;
4417
+		}
4418
+		if (in_array($operator, $this->valid_null_style_operators())) {
4419
+			if ($value !== null) {
4420
+				throw new EE_Error(
4421
+					sprintf(
4422
+						esc_html__(
4423
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4424
+							"event_espresso"
4425
+						),
4426
+						$value,
4427
+						$operator
4428
+					)
4429
+				);
4430
+			}
4431
+			return $operator;
4432
+		}
4433
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4435
+			// remove other junk. So just treat it as a string.
4436
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4437
+		}
4438
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4440
+		}
4441
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442
+			throw new EE_Error(
4443
+				sprintf(
4444
+					esc_html__(
4445
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4446
+						'event_espresso'
4447
+					),
4448
+					$operator,
4449
+					$operator
4450
+				)
4451
+			);
4452
+		}
4453
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454
+			throw new EE_Error(
4455
+				sprintf(
4456
+					esc_html__(
4457
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4458
+						'event_espresso'
4459
+					),
4460
+					$operator,
4461
+					$operator
4462
+				)
4463
+			);
4464
+		}
4465
+		throw new EE_Error(
4466
+			sprintf(
4467
+				esc_html__(
4468
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4469
+					"event_espresso"
4470
+				),
4471
+				http_build_query($op_and_value)
4472
+			)
4473
+		);
4474
+	}
4475
+
4476
+
4477
+
4478
+	/**
4479
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4480
+	 *
4481
+	 * @param array                      $values
4482
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4483
+	 *                                              '%s'
4484
+	 * @return string
4485
+	 * @throws EE_Error
4486
+	 */
4487
+	public function _construct_between_value($values, $field_obj)
4488
+	{
4489
+		$cleaned_values = array();
4490
+		foreach ($values as $value) {
4491
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492
+		}
4493
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4494
+	}
4495
+
4496
+
4497
+	/**
4498
+	 * Takes an array or a comma-separated list of $values and cleans them
4499
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4500
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4501
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4502
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4503
+	 *
4504
+	 * @param mixed                      $values    array or comma-separated string
4505
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4506
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4507
+	 * @throws EE_Error
4508
+	 */
4509
+	public function _construct_in_value($values, $field_obj)
4510
+	{
4511
+		$prepped = [];
4512
+		// check if the value is a CSV list
4513
+		if (is_string($values)) {
4514
+			// in which case, turn it into an array
4515
+			$values = explode(',', $values);
4516
+		}
4517
+		// make sure we only have one of each value in the list
4518
+		$values = array_unique($values);
4519
+		foreach ($values as $value) {
4520
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4521
+		}
4522
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4523
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4524
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525
+		if (empty($prepped)) {
4526
+			$all_fields = $this->field_settings();
4527
+			$first_field    = reset($all_fields);
4528
+			$main_table = $this->_get_main_table();
4529
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530
+		}
4531
+		return '(' . implode(',', $prepped) . ')';
4532
+	}
4533
+
4534
+
4535
+
4536
+	/**
4537
+	 * @param mixed                      $value
4538
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4539
+	 * @throws EE_Error
4540
+	 * @return false|null|string
4541
+	 */
4542
+	private function _wpdb_prepare_using_field($value, $field_obj)
4543
+	{
4544
+		/** @type WPDB $wpdb */
4545
+		global $wpdb;
4546
+		if ($field_obj instanceof EE_Model_Field_Base) {
4547
+			return $wpdb->prepare(
4548
+				$field_obj->get_wpdb_data_type(),
4549
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4550
+			);
4551
+		} //$field_obj should really just be a data type
4552
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553
+			throw new EE_Error(
4554
+				sprintf(
4555
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4556
+					$field_obj,
4557
+					implode(",", $this->_valid_wpdb_data_types)
4558
+				)
4559
+			);
4560
+		}
4561
+		return $wpdb->prepare($field_obj, $value);
4562
+	}
4563
+
4564
+
4565
+
4566
+	/**
4567
+	 * Takes the input parameter and finds the model field that it indicates.
4568
+	 *
4569
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4570
+	 * @throws EE_Error
4571
+	 * @return EE_Model_Field_Base
4572
+	 */
4573
+	protected function _deduce_field_from_query_param($query_param_name)
4574
+	{
4575
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4576
+		// which will help us find the database table and column
4577
+		$query_param_parts = explode(".", $query_param_name);
4578
+		if (empty($query_param_parts)) {
4579
+			throw new EE_Error(sprintf(esc_html__(
4580
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4581
+				'event_espresso'
4582
+			), $query_param_name));
4583
+		}
4584
+		$number_of_parts = count($query_param_parts);
4585
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4586
+		if ($number_of_parts === 1) {
4587
+			$field_name = $last_query_param_part;
4588
+			$model_obj = $this;
4589
+		} else {// $number_of_parts >= 2
4590
+			// the last part is the column name, and there are only 2parts. therefore...
4591
+			$field_name = $last_query_param_part;
4592
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4593
+		}
4594
+		try {
4595
+			return $model_obj->field_settings_for($field_name);
4596
+		} catch (EE_Error $e) {
4597
+			return null;
4598
+		}
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4605
+	 * alias and column which corresponds to it
4606
+	 *
4607
+	 * @param string $field_name
4608
+	 * @throws EE_Error
4609
+	 * @return string
4610
+	 */
4611
+	public function _get_qualified_column_for_field($field_name)
4612
+	{
4613
+		$all_fields = $this->field_settings();
4614
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4615
+		if ($field) {
4616
+			return $field->get_qualified_column();
4617
+		}
4618
+		throw new EE_Error(
4619
+			sprintf(
4620
+				esc_html__(
4621
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4622
+					'event_espresso'
4623
+				),
4624
+				$field_name,
4625
+				get_class($this)
4626
+			)
4627
+		);
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4634
+	 * Example usage:
4635
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4636
+	 *      array(),
4637
+	 *      ARRAY_A,
4638
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4639
+	 *  );
4640
+	 * is equivalent to
4641
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4642
+	 * and
4643
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4644
+	 *      array(
4645
+	 *          array(
4646
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4647
+	 *          ),
4648
+	 *          ARRAY_A,
4649
+	 *          implode(
4650
+	 *              ', ',
4651
+	 *              array_merge(
4652
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4653
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4654
+	 *              )
4655
+	 *          )
4656
+	 *      )
4657
+	 *  );
4658
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4659
+	 *
4660
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4661
+	 *                                            and the one whose fields you are selecting for example: when querying
4662
+	 *                                            tickets model and selecting fields from the tickets model you would
4663
+	 *                                            leave this parameter empty, because no models are needed to join
4664
+	 *                                            between the queried model and the selected one. Likewise when
4665
+	 *                                            querying the datetime model and selecting fields from the tickets
4666
+	 *                                            model, it would also be left empty, because there is a direct
4667
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4668
+	 *                                            them together. However, when querying from the event model and
4669
+	 *                                            selecting fields from the ticket model, you should provide the string
4670
+	 *                                            'Datetime', indicating that the event model must first join to the
4671
+	 *                                            datetime model in order to find its relation to ticket model.
4672
+	 *                                            Also, when querying from the venue model and selecting fields from
4673
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4674
+	 *                                            indicating you need to join the venue model to the event model,
4675
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4676
+	 *                                            This string is used to deduce the prefix that gets added onto the
4677
+	 *                                            models' tables qualified columns
4678
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4679
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4680
+	 *                                            qualified column names
4681
+	 * @return array|string
4682
+	 */
4683
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684
+	{
4685
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4686
+		$qualified_columns = array();
4687
+		foreach ($this->field_settings() as $field_name => $field) {
4688
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4689
+		}
4690
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691
+	}
4692
+
4693
+
4694
+
4695
+	/**
4696
+	 * constructs the select use on special limit joins
4697
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4698
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4699
+	 * (as that is typically where the limits would be set).
4700
+	 *
4701
+	 * @param  string       $table_alias The table the select is being built for
4702
+	 * @param  mixed|string $limit       The limit for this select
4703
+	 * @return string                The final select join element for the query.
4704
+	 */
4705
+	public function _construct_limit_join_select($table_alias, $limit)
4706
+	{
4707
+		$SQL = '';
4708
+		foreach ($this->_tables as $table_obj) {
4709
+			if ($table_obj instanceof EE_Primary_Table) {
4710
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4711
+					? $table_obj->get_select_join_limit($limit)
4712
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4713
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4714
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4715
+					? $table_obj->get_select_join_limit_join($limit)
4716
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4717
+			}
4718
+		}
4719
+		return $SQL;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4726
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4727
+	 *
4728
+	 * @return string SQL
4729
+	 * @throws EE_Error
4730
+	 */
4731
+	public function _construct_internal_join()
4732
+	{
4733
+		$SQL = $this->_get_main_table()->get_table_sql();
4734
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4735
+		return $SQL;
4736
+	}
4737
+
4738
+
4739
+
4740
+	/**
4741
+	 * Constructs the SQL for joining all the tables on this model.
4742
+	 * Normally $alias should be the primary table's alias, but in cases where
4743
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4744
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4745
+	 * alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4748
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4749
+	 *
4750
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4751
+	 * @return string
4752
+	 */
4753
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4754
+	{
4755
+		$SQL = '';
4756
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4757
+		foreach ($this->_tables as $table_obj) {
4758
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4759
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4760
+					// so we're joining to this table, meaning the table is already in
4761
+					// the FROM statement, BUT the primary table isn't. So we want
4762
+					// to add the inverse join sql
4763
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4764
+				} else {
4765
+					// just add a regular JOIN to this table from the primary table
4766
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4767
+				}
4768
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4769
+		}
4770
+		return $SQL;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4777
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4778
+	 * their data type (eg, '%s', '%d', etc)
4779
+	 *
4780
+	 * @return array
4781
+	 */
4782
+	public function _get_data_types()
4783
+	{
4784
+		$data_types = array();
4785
+		foreach ($this->field_settings() as $field_obj) {
4786
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787
+			/** @var $field_obj EE_Model_Field_Base */
4788
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4789
+		}
4790
+		return $data_types;
4791
+	}
4792
+
4793
+
4794
+
4795
+	/**
4796
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4797
+	 *
4798
+	 * @param string $model_name
4799
+	 * @throws EE_Error
4800
+	 * @return EEM_Base
4801
+	 */
4802
+	public function get_related_model_obj($model_name)
4803
+	{
4804
+		$model_classname = "EEM_" . $model_name;
4805
+		if (! class_exists($model_classname)) {
4806
+			throw new EE_Error(sprintf(esc_html__(
4807
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808
+				'event_espresso'
4809
+			), $model_name, $model_classname));
4810
+		}
4811
+		return call_user_func($model_classname . "::instance");
4812
+	}
4813
+
4814
+
4815
+
4816
+	/**
4817
+	 * Returns the array of EE_ModelRelations for this model.
4818
+	 *
4819
+	 * @return EE_Model_Relation_Base[]
4820
+	 */
4821
+	public function relation_settings()
4822
+	{
4823
+		return $this->_model_relations;
4824
+	}
4825
+
4826
+
4827
+
4828
+	/**
4829
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4830
+	 * because without THOSE models, this model probably doesn't have much purpose.
4831
+	 * (Eg, without an event, datetimes have little purpose.)
4832
+	 *
4833
+	 * @return EE_Belongs_To_Relation[]
4834
+	 */
4835
+	public function belongs_to_relations()
4836
+	{
4837
+		$belongs_to_relations = array();
4838
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4841
+			}
4842
+		}
4843
+		return $belongs_to_relations;
4844
+	}
4845
+
4846
+
4847
+
4848
+	/**
4849
+	 * Returns the specified EE_Model_Relation, or throws an exception
4850
+	 *
4851
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4852
+	 * @throws EE_Error
4853
+	 * @return EE_Model_Relation_Base
4854
+	 */
4855
+	public function related_settings_for($relation_name)
4856
+	{
4857
+		$relatedModels = $this->relation_settings();
4858
+		if (! array_key_exists($relation_name, $relatedModels)) {
4859
+			throw new EE_Error(
4860
+				sprintf(
4861
+					esc_html__(
4862
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4863
+						'event_espresso'
4864
+					),
4865
+					$relation_name,
4866
+					$this->_get_class_name(),
4867
+					implode(', ', array_keys($relatedModels))
4868
+				)
4869
+			);
4870
+		}
4871
+		return $relatedModels[ $relation_name ];
4872
+	}
4873
+
4874
+
4875
+
4876
+	/**
4877
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4878
+	 * fields
4879
+	 *
4880
+	 * @param string $fieldName
4881
+	 * @param boolean $include_db_only_fields
4882
+	 * @throws EE_Error
4883
+	 * @return EE_Model_Field_Base
4884
+	 */
4885
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4886
+	{
4887
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4888
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4889
+			throw new EE_Error(sprintf(
4890
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891
+				$fieldName,
4892
+				get_class($this)
4893
+			));
4894
+		}
4895
+		return $fieldSettings[ $fieldName ];
4896
+	}
4897
+
4898
+
4899
+
4900
+	/**
4901
+	 * Checks if this field exists on this model
4902
+	 *
4903
+	 * @param string $fieldName a key in the model's _field_settings array
4904
+	 * @return boolean
4905
+	 */
4906
+	public function has_field($fieldName)
4907
+	{
4908
+		$fieldSettings = $this->field_settings(true);
4909
+		if (isset($fieldSettings[ $fieldName ])) {
4910
+			return true;
4911
+		}
4912
+		return false;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Returns whether or not this model has a relation to the specified model
4919
+	 *
4920
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4921
+	 * @return boolean
4922
+	 */
4923
+	public function has_relation($relation_name)
4924
+	{
4925
+		$relations = $this->relation_settings();
4926
+		if (isset($relations[ $relation_name ])) {
4927
+			return true;
4928
+		}
4929
+		return false;
4930
+	}
4931
+
4932
+
4933
+
4934
+	/**
4935
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4936
+	 * Eg, on EE_Answer that would be ANS_ID field object
4937
+	 *
4938
+	 * @param $field_obj
4939
+	 * @return boolean
4940
+	 */
4941
+	public function is_primary_key_field($field_obj)
4942
+	{
4943
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4944
+	}
4945
+
4946
+
4947
+
4948
+	/**
4949
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4950
+	 * Eg, on EE_Answer that would be ANS_ID field object
4951
+	 *
4952
+	 * @return EE_Model_Field_Base
4953
+	 * @throws EE_Error
4954
+	 */
4955
+	public function get_primary_key_field()
4956
+	{
4957
+		if ($this->_primary_key_field === null) {
4958
+			foreach ($this->field_settings(true) as $field_obj) {
4959
+				if ($this->is_primary_key_field($field_obj)) {
4960
+					$this->_primary_key_field = $field_obj;
4961
+					break;
4962
+				}
4963
+			}
4964
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965
+				throw new EE_Error(sprintf(
4966
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967
+					get_class($this)
4968
+				));
4969
+			}
4970
+		}
4971
+		return $this->_primary_key_field;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * Returns whether or not not there is a primary key on this model.
4978
+	 * Internally does some caching.
4979
+	 *
4980
+	 * @return boolean
4981
+	 */
4982
+	public function has_primary_key_field()
4983
+	{
4984
+		if ($this->_has_primary_key_field === null) {
4985
+			try {
4986
+				$this->get_primary_key_field();
4987
+				$this->_has_primary_key_field = true;
4988
+			} catch (EE_Error $e) {
4989
+				$this->_has_primary_key_field = false;
4990
+			}
4991
+		}
4992
+		return $this->_has_primary_key_field;
4993
+	}
4994
+
4995
+
4996
+
4997
+	/**
4998
+	 * Finds the first field of type $field_class_name.
4999
+	 *
5000
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5001
+	 *                                 EE_Foreign_Key_Field, etc
5002
+	 * @return EE_Model_Field_Base or null if none is found
5003
+	 */
5004
+	public function get_a_field_of_type($field_class_name)
5005
+	{
5006
+		foreach ($this->field_settings() as $field) {
5007
+			if ($field instanceof $field_class_name) {
5008
+				return $field;
5009
+			}
5010
+		}
5011
+		return null;
5012
+	}
5013
+
5014
+
5015
+
5016
+	/**
5017
+	 * Gets a foreign key field pointing to model.
5018
+	 *
5019
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5020
+	 * @return EE_Foreign_Key_Field_Base
5021
+	 * @throws EE_Error
5022
+	 */
5023
+	public function get_foreign_key_to($model_name)
5024
+	{
5025
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5026
+			foreach ($this->field_settings() as $field) {
5027
+				if (
5028
+					$field instanceof EE_Foreign_Key_Field_Base
5029
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5030
+				) {
5031
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5032
+					break;
5033
+				}
5034
+			}
5035
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5036
+				throw new EE_Error(sprintf(esc_html__(
5037
+					"There is no foreign key field pointing to model %s on model %s",
5038
+					'event_espresso'
5039
+				), $model_name, get_class($this)));
5040
+			}
5041
+		}
5042
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5043
+	}
5044
+
5045
+
5046
+
5047
+	/**
5048
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5049
+	 *
5050
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5051
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5052
+	 *                            Either one works
5053
+	 * @return string
5054
+	 */
5055
+	public function get_table_for_alias($table_alias)
5056
+	{
5057
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5059
+	}
5060
+
5061
+
5062
+
5063
+	/**
5064
+	 * Returns a flat array of all field son this model, instead of organizing them
5065
+	 * by table_alias as they are in the constructor.
5066
+	 *
5067
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5068
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5069
+	 */
5070
+	public function field_settings($include_db_only_fields = false)
5071
+	{
5072
+		if ($include_db_only_fields) {
5073
+			if ($this->_cached_fields === null) {
5074
+				$this->_cached_fields = array();
5075
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5076
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
+						$this->_cached_fields[ $field_name ] = $field_obj;
5078
+					}
5079
+				}
5080
+			}
5081
+			return $this->_cached_fields;
5082
+		}
5083
+		if ($this->_cached_fields_non_db_only === null) {
5084
+			$this->_cached_fields_non_db_only = array();
5085
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5086
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087
+					/** @var $field_obj EE_Model_Field_Base */
5088
+					if (! $field_obj->is_db_only_field()) {
5089
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5090
+					}
5091
+				}
5092
+			}
5093
+		}
5094
+		return $this->_cached_fields_non_db_only;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 *        cycle though array of attendees and create objects out of each item
5101
+	 *
5102
+	 * @access        private
5103
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5104
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5105
+	 *                           numerically indexed)
5106
+	 * @throws EE_Error
5107
+	 */
5108
+	protected function _create_objects($rows = array())
5109
+	{
5110
+		$array_of_objects = array();
5111
+		if (empty($rows)) {
5112
+			return array();
5113
+		}
5114
+		$count_if_model_has_no_primary_key = 0;
5115
+		$has_primary_key = $this->has_primary_key_field();
5116
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5117
+		foreach ((array) $rows as $row) {
5118
+			if (empty($row)) {
5119
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5120
+				return array();
5121
+			}
5122
+			// check if we've already set this object in the results array,
5123
+			// in which case there's no need to process it further (again)
5124
+			if ($has_primary_key) {
5125
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5126
+					$row,
5127
+					$primary_key_field->get_qualified_column(),
5128
+					$primary_key_field->get_table_column()
5129
+				);
5130
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5131
+					continue;
5132
+				}
5133
+			}
5134
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5135
+			if (! $classInstance) {
5136
+				throw new EE_Error(
5137
+					sprintf(
5138
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5139
+						$this->get_this_model_name(),
5140
+						http_build_query($row)
5141
+					)
5142
+				);
5143
+			}
5144
+			// set the timezone on the instantiated objects
5145
+			$classInstance->set_timezone($this->_timezone);
5146
+			// make sure if there is any timezone setting present that we set the timezone for the object
5147
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
+			$array_of_objects[ $key ] = $classInstance;
5149
+			// also, for all the relations of type BelongsTo, see if we can cache
5150
+			// those related models
5151
+			// (we could do this for other relations too, but if there are conditions
5152
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5153
+			// so it requires a little more thought than just caching them immediately...)
5154
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5155
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5156
+					// check if this model's INFO is present. If so, cache it on the model
5157
+					$other_model = $relation_obj->get_other_model();
5158
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5159
+					// if we managed to make a model object from the results, cache it on the main model object
5160
+					if ($other_model_obj_maybe) {
5161
+						// set timezone on these other model objects if they are present
5162
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5163
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5164
+					}
5165
+				}
5166
+			}
5167
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5168
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5169
+			// the field in the CustomSelects object
5170
+			if ($this->_custom_selections instanceof CustomSelects) {
5171
+				$classInstance->setCustomSelectsValues(
5172
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5173
+				);
5174
+			}
5175
+		}
5176
+		return $array_of_objects;
5177
+	}
5178
+
5179
+
5180
+	/**
5181
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5182
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5183
+	 *
5184
+	 * @param array $db_results_row
5185
+	 * @return array
5186
+	 */
5187
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5188
+	{
5189
+		$results = array();
5190
+		if ($this->_custom_selections instanceof CustomSelects) {
5191
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
+				if (isset($db_results_row[ $alias ])) {
5193
+					$results[ $alias ] = $this->convertValueToDataType(
5194
+						$db_results_row[ $alias ],
5195
+						$this->_custom_selections->getDataTypeForAlias($alias)
5196
+					);
5197
+				}
5198
+			}
5199
+		}
5200
+		return $results;
5201
+	}
5202
+
5203
+
5204
+	/**
5205
+	 * This will set the value for the given alias
5206
+	 * @param string $value
5207
+	 * @param string $datatype (one of %d, %s, %f)
5208
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5209
+	 */
5210
+	protected function convertValueToDataType($value, $datatype)
5211
+	{
5212
+		switch ($datatype) {
5213
+			case '%f':
5214
+				return (float) $value;
5215
+			case '%d':
5216
+				return (int) $value;
5217
+			default:
5218
+				return (string) $value;
5219
+		}
5220
+	}
5221
+
5222
+
5223
+	/**
5224
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5225
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5226
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5227
+	 * object (as set in the model_field!).
5228
+	 *
5229
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5230
+	 */
5231
+	public function create_default_object()
5232
+	{
5233
+		$this_model_fields_and_values = array();
5234
+		// setup the row using default values;
5235
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5236
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5237
+		}
5238
+		$className = $this->_get_class_name();
5239
+		$classInstance = EE_Registry::instance()
5240
+									->load_class($className, array($this_model_fields_and_values), false, false);
5241
+		return $classInstance;
5242
+	}
5243
+
5244
+
5245
+
5246
+	/**
5247
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5248
+	 *                             or an stdClass where each property is the name of a column,
5249
+	 * @return EE_Base_Class
5250
+	 * @throws EE_Error
5251
+	 */
5252
+	public function instantiate_class_from_array_or_object($cols_n_values)
5253
+	{
5254
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5255
+			$cols_n_values = get_object_vars($cols_n_values);
5256
+		}
5257
+		$primary_key = null;
5258
+		// make sure the array only has keys that are fields/columns on this model
5259
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5262
+		}
5263
+		$className = $this->_get_class_name();
5264
+		// check we actually found results that we can use to build our model object
5265
+		// if not, return null
5266
+		if ($this->has_primary_key_field()) {
5267
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5268
+				return null;
5269
+			}
5270
+		} elseif ($this->unique_indexes()) {
5271
+			$first_column = reset($this_model_fields_n_values);
5272
+			if (empty($first_column)) {
5273
+				return null;
5274
+			}
5275
+		}
5276
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277
+		if ($primary_key) {
5278
+			$classInstance = $this->get_from_entity_map($primary_key);
5279
+			if (! $classInstance) {
5280
+				$classInstance = EE_Registry::instance()
5281
+											->load_class(
5282
+												$className,
5283
+												array($this_model_fields_n_values, $this->_timezone),
5284
+												true,
5285
+												false
5286
+											);
5287
+				// add this new object to the entity map
5288
+				$classInstance = $this->add_to_entity_map($classInstance);
5289
+			}
5290
+		} else {
5291
+			$classInstance = EE_Registry::instance()
5292
+										->load_class(
5293
+											$className,
5294
+											array($this_model_fields_n_values, $this->_timezone),
5295
+											true,
5296
+											false
5297
+										);
5298
+		}
5299
+		return $classInstance;
5300
+	}
5301
+
5302
+
5303
+
5304
+	/**
5305
+	 * Gets the model object from the  entity map if it exists
5306
+	 *
5307
+	 * @param int|string $id the ID of the model object
5308
+	 * @return EE_Base_Class
5309
+	 */
5310
+	public function get_from_entity_map($id)
5311
+	{
5312
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5314
+	}
5315
+
5316
+
5317
+
5318
+	/**
5319
+	 * add_to_entity_map
5320
+	 * Adds the object to the model's entity mappings
5321
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5322
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5323
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5324
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5325
+	 *        then this method should be called immediately after the update query
5326
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5327
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5328
+	 *
5329
+	 * @param    EE_Base_Class $object
5330
+	 * @throws EE_Error
5331
+	 * @return \EE_Base_Class
5332
+	 */
5333
+	public function add_to_entity_map(EE_Base_Class $object)
5334
+	{
5335
+		$className = $this->_get_class_name();
5336
+		if (! $object instanceof $className) {
5337
+			throw new EE_Error(sprintf(
5338
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339
+				is_object($object) ? get_class($object) : $object,
5340
+				$className
5341
+			));
5342
+		}
5343
+		/** @var $object EE_Base_Class */
5344
+		if (! $object->ID()) {
5345
+			throw new EE_Error(sprintf(esc_html__(
5346
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5347
+				"event_espresso"
5348
+			), get_class($this)));
5349
+		}
5350
+		// double check it's not already there
5351
+		$classInstance = $this->get_from_entity_map($object->ID());
5352
+		if ($classInstance) {
5353
+			return $classInstance;
5354
+		}
5355
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5356
+		return $object;
5357
+	}
5358
+
5359
+
5360
+
5361
+	/**
5362
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5363
+	 * if no identifier is provided, then the entire entity map is emptied
5364
+	 *
5365
+	 * @param int|string $id the ID of the model object
5366
+	 * @return boolean
5367
+	 */
5368
+	public function clear_entity_map($id = null)
5369
+	{
5370
+		if (empty($id)) {
5371
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5372
+			return true;
5373
+		}
5374
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5376
+			return true;
5377
+		}
5378
+		return false;
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5385
+	 * Given an array where keys are column (or column alias) names and values,
5386
+	 * returns an array of their corresponding field names and database values
5387
+	 *
5388
+	 * @param array $cols_n_values
5389
+	 * @return array
5390
+	 */
5391
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5392
+	{
5393
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * _deduce_fields_n_values_from_cols_n_values
5400
+	 * Given an array where keys are column (or column alias) names and values,
5401
+	 * returns an array of their corresponding field names and database values
5402
+	 *
5403
+	 * @param string $cols_n_values
5404
+	 * @return array
5405
+	 */
5406
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5407
+	{
5408
+		$this_model_fields_n_values = array();
5409
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5410
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5411
+				$cols_n_values,
5412
+				$table_obj->get_fully_qualified_pk_column(),
5413
+				$table_obj->get_pk_column()
5414
+			);
5415
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5416
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
+					if (! $field_obj->is_db_only_field()) {
5419
+						// prepare field as if its coming from db
5420
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5422
+					}
5423
+				}
5424
+			} else {
5425
+				// the table's rows existed. Use their values
5426
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
+					if (! $field_obj->is_db_only_field()) {
5428
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5429
+							$cols_n_values,
5430
+							$field_obj->get_qualified_column(),
5431
+							$field_obj->get_table_column()
5432
+						);
5433
+					}
5434
+				}
5435
+			}
5436
+		}
5437
+		return $this_model_fields_n_values;
5438
+	}
5439
+
5440
+
5441
+	/**
5442
+	 * @param $cols_n_values
5443
+	 * @param $qualified_column
5444
+	 * @param $regular_column
5445
+	 * @return null
5446
+	 * @throws EE_Error
5447
+	 * @throws ReflectionException
5448
+	 */
5449
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5450
+	{
5451
+		$value = null;
5452
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453
+		// does the field on the model relate to this column retrieved from the db?
5454
+		// or is it a db-only field? (not relating to the model)
5455
+		if (isset($cols_n_values[ $qualified_column ])) {
5456
+			$value = $cols_n_values[ $qualified_column ];
5457
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5458
+			$value = $cols_n_values[ $regular_column ];
5459
+		} elseif (! empty($this->foreign_key_aliases)) {
5460
+			// no PK?  ok check if there is a foreign key alias set for this table
5461
+			// then check if that alias exists in the incoming data
5462
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
+					$value = $cols_n_values[ $FK_alias ];
5466
+					[$pk_class] = explode('.', $PK_column);
5467
+					$pk_model_name = "EEM_{$pk_class}";
5468
+					/** @var EEM_Base $pk_model */
5469
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5470
+					if ($pk_model instanceof EEM_Base) {
5471
+						// make sure object is pulled from db and added to entity map
5472
+						$pk_model->get_one_by_ID($value);
5473
+					}
5474
+					break;
5475
+				}
5476
+			}
5477
+		}
5478
+		return $value;
5479
+	}
5480
+
5481
+
5482
+
5483
+	/**
5484
+	 * refresh_entity_map_from_db
5485
+	 * Makes sure the model object in the entity map at $id assumes the values
5486
+	 * of the database (opposite of EE_base_Class::save())
5487
+	 *
5488
+	 * @param int|string $id
5489
+	 * @return EE_Base_Class
5490
+	 * @throws EE_Error
5491
+	 */
5492
+	public function refresh_entity_map_from_db($id)
5493
+	{
5494
+		$obj_in_map = $this->get_from_entity_map($id);
5495
+		if ($obj_in_map) {
5496
+			$wpdb_results = $this->_get_all_wpdb_results(
5497
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5498
+			);
5499
+			if ($wpdb_results && is_array($wpdb_results)) {
5500
+				$one_row = reset($wpdb_results);
5501
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5502
+					$obj_in_map->set_from_db($field_name, $db_value);
5503
+				}
5504
+				// clear the cache of related model objects
5505
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5506
+					$obj_in_map->clear_cache($relation_name, null, true);
5507
+				}
5508
+			}
5509
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5510
+			return $obj_in_map;
5511
+		}
5512
+		return $this->get_one_by_ID($id);
5513
+	}
5514
+
5515
+
5516
+
5517
+	/**
5518
+	 * refresh_entity_map_with
5519
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5520
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5521
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5522
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5523
+	 *
5524
+	 * @param int|string    $id
5525
+	 * @param EE_Base_Class $replacing_model_obj
5526
+	 * @return \EE_Base_Class
5527
+	 * @throws EE_Error
5528
+	 */
5529
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5530
+	{
5531
+		$obj_in_map = $this->get_from_entity_map($id);
5532
+		if ($obj_in_map) {
5533
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5534
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5535
+					$obj_in_map->set($field_name, $value);
5536
+				}
5537
+				// make the model object in the entity map's cache match the $replacing_model_obj
5538
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5539
+					$obj_in_map->clear_cache($relation_name, null, true);
5540
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5541
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5542
+					}
5543
+				}
5544
+			}
5545
+			return $obj_in_map;
5546
+		}
5547
+		$this->add_to_entity_map($replacing_model_obj);
5548
+		return $replacing_model_obj;
5549
+	}
5550
+
5551
+
5552
+
5553
+	/**
5554
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5555
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5556
+	 * require_once($this->_getClassName().".class.php");
5557
+	 *
5558
+	 * @return string
5559
+	 */
5560
+	private function _get_class_name()
5561
+	{
5562
+		return "EE_" . $this->get_this_model_name();
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5569
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5570
+	 * it would be 'Events'.
5571
+	 *
5572
+	 * @param int $quantity
5573
+	 * @return string
5574
+	 */
5575
+	public function item_name($quantity = 1)
5576
+	{
5577
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5578
+	}
5579
+
5580
+
5581
+
5582
+	/**
5583
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5584
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5585
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5586
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5587
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5588
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5589
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5590
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5591
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5592
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5593
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5594
+	 *        return $previousReturnValue.$returnString;
5595
+	 * }
5596
+	 * require('EEM_Answer.model.php');
5597
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5598
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5599
+	 *
5600
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5601
+	 * @param array  $args       array of original arguments passed to the function
5602
+	 * @throws EE_Error
5603
+	 * @return mixed whatever the plugin which calls add_filter decides
5604
+	 */
5605
+	public function __call($methodName, $args)
5606
+	{
5607
+		$className = get_class($this);
5608
+		$tagName = "FHEE__{$className}__{$methodName}";
5609
+		if (! has_filter($tagName)) {
5610
+			throw new EE_Error(
5611
+				sprintf(
5612
+					esc_html__(
5613
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5614
+						'event_espresso'
5615
+					),
5616
+					$methodName,
5617
+					$className,
5618
+					$tagName,
5619
+					'<br />'
5620
+				)
5621
+			);
5622
+		}
5623
+		return apply_filters($tagName, null, $this, $args);
5624
+	}
5625
+
5626
+
5627
+
5628
+	/**
5629
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5630
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5631
+	 *
5632
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5633
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5634
+	 *                                                       the object's class name
5635
+	 *                                                       or object's ID
5636
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5637
+	 *                                                       exists in the database. If it does not, we add it
5638
+	 * @throws EE_Error
5639
+	 * @return EE_Base_Class
5640
+	 */
5641
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5642
+	{
5643
+		$className = $this->_get_class_name();
5644
+		if ($base_class_obj_or_id instanceof $className) {
5645
+			$model_object = $base_class_obj_or_id;
5646
+		} else {
5647
+			$primary_key_field = $this->get_primary_key_field();
5648
+			if (
5649
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5650
+				&& (
5651
+					is_int($base_class_obj_or_id)
5652
+					|| is_string($base_class_obj_or_id)
5653
+				)
5654
+			) {
5655
+				// assume it's an ID.
5656
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5657
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5658
+			} elseif (
5659
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5660
+				&& is_string($base_class_obj_or_id)
5661
+			) {
5662
+				// assume its a string representation of the object
5663
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5664
+			} else {
5665
+				throw new EE_Error(
5666
+					sprintf(
5667
+						esc_html__(
5668
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5669
+							'event_espresso'
5670
+						),
5671
+						$base_class_obj_or_id,
5672
+						$this->_get_class_name(),
5673
+						print_r($base_class_obj_or_id, true)
5674
+					)
5675
+				);
5676
+			}
5677
+		}
5678
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5679
+			$model_object->save();
5680
+		}
5681
+		return $model_object;
5682
+	}
5683
+
5684
+
5685
+
5686
+	/**
5687
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5688
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5689
+	 * returns it ID.
5690
+	 *
5691
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5692
+	 * @return int|string depending on the type of this model object's ID
5693
+	 * @throws EE_Error
5694
+	 */
5695
+	public function ensure_is_ID($base_class_obj_or_id)
5696
+	{
5697
+		$className = $this->_get_class_name();
5698
+		if ($base_class_obj_or_id instanceof $className) {
5699
+			/** @var $base_class_obj_or_id EE_Base_Class */
5700
+			$id = $base_class_obj_or_id->ID();
5701
+		} elseif (is_int($base_class_obj_or_id)) {
5702
+			// assume it's an ID
5703
+			$id = $base_class_obj_or_id;
5704
+		} elseif (is_string($base_class_obj_or_id)) {
5705
+			// assume its a string representation of the object
5706
+			$id = $base_class_obj_or_id;
5707
+		} else {
5708
+			throw new EE_Error(sprintf(
5709
+				esc_html__(
5710
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5711
+					'event_espresso'
5712
+				),
5713
+				$base_class_obj_or_id,
5714
+				$this->_get_class_name(),
5715
+				print_r($base_class_obj_or_id, true)
5716
+			));
5717
+		}
5718
+		return $id;
5719
+	}
5720
+
5721
+
5722
+
5723
+	/**
5724
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5725
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5726
+	 * been sanitized and converted into the appropriate domain.
5727
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5728
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5729
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5730
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5731
+	 * $EVT = EEM_Event::instance(); $old_setting =
5732
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5733
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5734
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5735
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5736
+	 *
5737
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5738
+	 * @return void
5739
+	 */
5740
+	public function assume_values_already_prepared_by_model_object(
5741
+		$values_already_prepared = self::not_prepared_by_model_object
5742
+	) {
5743
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5744
+	}
5745
+
5746
+
5747
+
5748
+	/**
5749
+	 * Read comments for assume_values_already_prepared_by_model_object()
5750
+	 *
5751
+	 * @return int
5752
+	 */
5753
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5754
+	{
5755
+		return $this->_values_already_prepared_by_model_object;
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * Gets all the indexes on this model
5762
+	 *
5763
+	 * @return EE_Index[]
5764
+	 */
5765
+	public function indexes()
5766
+	{
5767
+		return $this->_indexes;
5768
+	}
5769
+
5770
+
5771
+
5772
+	/**
5773
+	 * Gets all the Unique Indexes on this model
5774
+	 *
5775
+	 * @return EE_Unique_Index[]
5776
+	 */
5777
+	public function unique_indexes()
5778
+	{
5779
+		$unique_indexes = array();
5780
+		foreach ($this->_indexes as $name => $index) {
5781
+			if ($index instanceof EE_Unique_Index) {
5782
+				$unique_indexes [ $name ] = $index;
5783
+			}
5784
+		}
5785
+		return $unique_indexes;
5786
+	}
5787
+
5788
+
5789
+
5790
+	/**
5791
+	 * Gets all the fields which, when combined, make the primary key.
5792
+	 * This is usually just an array with 1 element (the primary key), but in cases
5793
+	 * where there is no primary key, it's a combination of fields as defined
5794
+	 * on a primary index
5795
+	 *
5796
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5797
+	 * @throws EE_Error
5798
+	 */
5799
+	public function get_combined_primary_key_fields()
5800
+	{
5801
+		foreach ($this->indexes() as $index) {
5802
+			if ($index instanceof EE_Primary_Key_Index) {
5803
+				return $index->fields();
5804
+			}
5805
+		}
5806
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5807
+	}
5808
+
5809
+
5810
+
5811
+	/**
5812
+	 * Used to build a primary key string (when the model has no primary key),
5813
+	 * which can be used a unique string to identify this model object.
5814
+	 *
5815
+	 * @param array $fields_n_values keys are field names, values are their values.
5816
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5817
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5818
+	 *                               before passing it to this function (that will convert it from columns-n-values
5819
+	 *                               to field-names-n-values).
5820
+	 * @return string
5821
+	 * @throws EE_Error
5822
+	 */
5823
+	public function get_index_primary_key_string($fields_n_values)
5824
+	{
5825
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5826
+			$fields_n_values,
5827
+			$this->get_combined_primary_key_fields()
5828
+		);
5829
+		return http_build_query($cols_n_values_for_primary_key_index);
5830
+	}
5831
+
5832
+
5833
+
5834
+	/**
5835
+	 * Gets the field values from the primary key string
5836
+	 *
5837
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5838
+	 * @param string $index_primary_key_string
5839
+	 * @return null|array
5840
+	 * @throws EE_Error
5841
+	 */
5842
+	public function parse_index_primary_key_string($index_primary_key_string)
5843
+	{
5844
+		$key_fields = $this->get_combined_primary_key_fields();
5845
+		// check all of them are in the $id
5846
+		$key_vals_in_combined_pk = array();
5847
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848
+		foreach ($key_fields as $key_field_name => $field_obj) {
5849
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5850
+				return null;
5851
+			}
5852
+		}
5853
+		return $key_vals_in_combined_pk;
5854
+	}
5855
+
5856
+
5857
+
5858
+	/**
5859
+	 * verifies that an array of key-value pairs for model fields has a key
5860
+	 * for each field comprising the primary key index
5861
+	 *
5862
+	 * @param array $key_vals
5863
+	 * @return boolean
5864
+	 * @throws EE_Error
5865
+	 */
5866
+	public function has_all_combined_primary_key_fields($key_vals)
5867
+	{
5868
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869
+		foreach ($keys_it_should_have as $key) {
5870
+			if (! isset($key_vals[ $key ])) {
5871
+				return false;
5872
+			}
5873
+		}
5874
+		return true;
5875
+	}
5876
+
5877
+
5878
+
5879
+	/**
5880
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5881
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5882
+	 *
5883
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5884
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5885
+	 * @throws EE_Error
5886
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5887
+	 *                                                              indexed)
5888
+	 */
5889
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5890
+	{
5891
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5892
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5893
+		} elseif (is_array($model_object_or_attributes_array)) {
5894
+			$attributes_array = $model_object_or_attributes_array;
5895
+		} else {
5896
+			throw new EE_Error(sprintf(esc_html__(
5897
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5898
+				"event_espresso"
5899
+			), $model_object_or_attributes_array));
5900
+		}
5901
+		// even copies obviously won't have the same ID, so remove the primary key
5902
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
+			unset($attributes_array[ $this->primary_key_name() ]);
5905
+		}
5906
+		if (isset($query_params[0])) {
5907
+			$query_params[0] = array_merge($attributes_array, $query_params);
5908
+		} else {
5909
+			$query_params[0] = $attributes_array;
5910
+		}
5911
+		return $this->get_all($query_params);
5912
+	}
5913
+
5914
+
5915
+
5916
+	/**
5917
+	 * Gets the first copy we find. See get_all_copies for more details
5918
+	 *
5919
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5920
+	 * @param array $query_params
5921
+	 * @return EE_Base_Class
5922
+	 * @throws EE_Error
5923
+	 */
5924
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925
+	{
5926
+		if (! is_array($query_params)) {
5927
+			EE_Error::doing_it_wrong(
5928
+				'EEM_Base::get_one_copy',
5929
+				sprintf(
5930
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5931
+					gettype($query_params)
5932
+				),
5933
+				'4.6.0'
5934
+			);
5935
+			$query_params = array();
5936
+		}
5937
+		$query_params['limit'] = 1;
5938
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5939
+		if (is_array($copies)) {
5940
+			return array_shift($copies);
5941
+		}
5942
+		return null;
5943
+	}
5944
+
5945
+
5946
+
5947
+	/**
5948
+	 * Updates the item with the specified id. Ignores default query parameters because
5949
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5950
+	 *
5951
+	 * @param array      $fields_n_values keys are field names, values are their new values
5952
+	 * @param int|string $id              the value of the primary key to update
5953
+	 * @return int number of rows updated
5954
+	 * @throws EE_Error
5955
+	 */
5956
+	public function update_by_ID($fields_n_values, $id)
5957
+	{
5958
+		$query_params = array(
5959
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5960
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5961
+		);
5962
+		return $this->update($fields_n_values, $query_params);
5963
+	}
5964
+
5965
+
5966
+
5967
+	/**
5968
+	 * Changes an operator which was supplied to the models into one usable in SQL
5969
+	 *
5970
+	 * @param string $operator_supplied
5971
+	 * @return string an operator which can be used in SQL
5972
+	 * @throws EE_Error
5973
+	 */
5974
+	private function _prepare_operator_for_sql($operator_supplied)
5975
+	{
5976
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5977
+			: null;
5978
+		if ($sql_operator) {
5979
+			return $sql_operator;
5980
+		}
5981
+		throw new EE_Error(
5982
+			sprintf(
5983
+				esc_html__(
5984
+					"The operator '%s' is not in the list of valid operators: %s",
5985
+					"event_espresso"
5986
+				),
5987
+				$operator_supplied,
5988
+				implode(",", array_keys($this->_valid_operators))
5989
+			)
5990
+		);
5991
+	}
5992
+
5993
+
5994
+
5995
+	/**
5996
+	 * Gets the valid operators
5997
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5998
+	 */
5999
+	public function valid_operators()
6000
+	{
6001
+		return $this->_valid_operators;
6002
+	}
6003
+
6004
+
6005
+
6006
+	/**
6007
+	 * Gets the between-style operators (take 2 arguments).
6008
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6009
+	 */
6010
+	public function valid_between_style_operators()
6011
+	{
6012
+		return array_intersect(
6013
+			$this->valid_operators(),
6014
+			$this->_between_style_operators
6015
+		);
6016
+	}
6017
+
6018
+	/**
6019
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6020
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6021
+	 */
6022
+	public function valid_like_style_operators()
6023
+	{
6024
+		return array_intersect(
6025
+			$this->valid_operators(),
6026
+			$this->_like_style_operators
6027
+		);
6028
+	}
6029
+
6030
+	/**
6031
+	 * Gets the "in"-style operators
6032
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6033
+	 */
6034
+	public function valid_in_style_operators()
6035
+	{
6036
+		return array_intersect(
6037
+			$this->valid_operators(),
6038
+			$this->_in_style_operators
6039
+		);
6040
+	}
6041
+
6042
+	/**
6043
+	 * Gets the "null"-style operators (accept no arguments)
6044
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6045
+	 */
6046
+	public function valid_null_style_operators()
6047
+	{
6048
+		return array_intersect(
6049
+			$this->valid_operators(),
6050
+			$this->_null_style_operators
6051
+		);
6052
+	}
6053
+
6054
+	/**
6055
+	 * Gets an array where keys are the primary keys and values are their 'names'
6056
+	 * (as determined by the model object's name() function, which is often overridden)
6057
+	 *
6058
+	 * @param array $query_params like get_all's
6059
+	 * @return string[]
6060
+	 * @throws EE_Error
6061
+	 */
6062
+	public function get_all_names($query_params = array())
6063
+	{
6064
+		$objs = $this->get_all($query_params);
6065
+		$names = array();
6066
+		foreach ($objs as $obj) {
6067
+			$names[ $obj->ID() ] = $obj->name();
6068
+		}
6069
+		return $names;
6070
+	}
6071
+
6072
+
6073
+
6074
+	/**
6075
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6076
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6077
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6078
+	 * array_keys() on $model_objects.
6079
+	 *
6080
+	 * @param \EE_Base_Class[] $model_objects
6081
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6082
+	 *                                               in the returned array
6083
+	 * @return array
6084
+	 * @throws EE_Error
6085
+	 */
6086
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087
+	{
6088
+		if (! $this->has_primary_key_field()) {
6089
+			if (WP_DEBUG) {
6090
+				EE_Error::add_error(
6091
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6092
+					__FILE__,
6093
+					__FUNCTION__,
6094
+					__LINE__
6095
+				);
6096
+			}
6097
+		}
6098
+		$IDs = array();
6099
+		foreach ($model_objects as $model_object) {
6100
+			$id = $model_object->ID();
6101
+			if (! $id) {
6102
+				if ($filter_out_empty_ids) {
6103
+					continue;
6104
+				}
6105
+				if (WP_DEBUG) {
6106
+					EE_Error::add_error(
6107
+						esc_html__(
6108
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6109
+							'event_espresso'
6110
+						),
6111
+						__FILE__,
6112
+						__FUNCTION__,
6113
+						__LINE__
6114
+					);
6115
+				}
6116
+			}
6117
+			$IDs[] = $id;
6118
+		}
6119
+		return $IDs;
6120
+	}
6121
+
6122
+
6123
+
6124
+	/**
6125
+	 * Returns the string used in capabilities relating to this model. If there
6126
+	 * are no capabilities that relate to this model returns false
6127
+	 *
6128
+	 * @return string|false
6129
+	 */
6130
+	public function cap_slug()
6131
+	{
6132
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6133
+	}
6134
+
6135
+
6136
+
6137
+	/**
6138
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6139
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6140
+	 * only returns the cap restrictions array in that context (ie, the array
6141
+	 * at that key)
6142
+	 *
6143
+	 * @param string $context
6144
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6145
+	 * @throws EE_Error
6146
+	 */
6147
+	public function cap_restrictions($context = EEM_Base::caps_read)
6148
+	{
6149
+		EEM_Base::verify_is_valid_cap_context($context);
6150
+		// check if we ought to run the restriction generator first
6151
+		if (
6152
+			isset($this->_cap_restriction_generators[ $context ])
6153
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6155
+		) {
6156
+			$this->_cap_restrictions[ $context ] = array_merge(
6157
+				$this->_cap_restrictions[ $context ],
6158
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6159
+			);
6160
+		}
6161
+		// and make sure we've finalized the construction of each restriction
6162
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6163
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164
+				$where_conditions_obj->_finalize_construct($this);
6165
+			}
6166
+		}
6167
+		return $this->_cap_restrictions[ $context ];
6168
+	}
6169
+
6170
+
6171
+
6172
+	/**
6173
+	 * Indicating whether or not this model thinks its a wp core model
6174
+	 *
6175
+	 * @return boolean
6176
+	 */
6177
+	public function is_wp_core_model()
6178
+	{
6179
+		return $this->_wp_core_model;
6180
+	}
6181
+
6182
+
6183
+
6184
+	/**
6185
+	 * Gets all the caps that are missing which impose a restriction on
6186
+	 * queries made in this context
6187
+	 *
6188
+	 * @param string $context one of EEM_Base::caps_ constants
6189
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6190
+	 * @throws EE_Error
6191
+	 */
6192
+	public function caps_missing($context = EEM_Base::caps_read)
6193
+	{
6194
+		$missing_caps = array();
6195
+		$cap_restrictions = $this->cap_restrictions($context);
6196
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197
+			if (
6198
+				! EE_Capabilities::instance()
6199
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6200
+			) {
6201
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6202
+			}
6203
+		}
6204
+		return $missing_caps;
6205
+	}
6206
+
6207
+
6208
+
6209
+	/**
6210
+	 * Gets the mapping from capability contexts to action strings used in capability names
6211
+	 *
6212
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6213
+	 * one of 'read', 'edit', or 'delete'
6214
+	 */
6215
+	public function cap_contexts_to_cap_action_map()
6216
+	{
6217
+		return apply_filters(
6218
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6219
+			$this->_cap_contexts_to_cap_action_map,
6220
+			$this
6221
+		);
6222
+	}
6223
+
6224
+
6225
+
6226
+	/**
6227
+	 * Gets the action string for the specified capability context
6228
+	 *
6229
+	 * @param string $context
6230
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6231
+	 * @throws EE_Error
6232
+	 */
6233
+	public function cap_action_for_context($context)
6234
+	{
6235
+		$mapping = $this->cap_contexts_to_cap_action_map();
6236
+		if (isset($mapping[ $context ])) {
6237
+			return $mapping[ $context ];
6238
+		}
6239
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240
+			return $action;
6241
+		}
6242
+		throw new EE_Error(
6243
+			sprintf(
6244
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6245
+				$context,
6246
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6247
+			)
6248
+		);
6249
+	}
6250
+
6251
+
6252
+
6253
+	/**
6254
+	 * Returns all the capability contexts which are valid when querying models
6255
+	 *
6256
+	 * @return array
6257
+	 */
6258
+	public static function valid_cap_contexts()
6259
+	{
6260
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6261
+			self::caps_read,
6262
+			self::caps_read_admin,
6263
+			self::caps_edit,
6264
+			self::caps_delete,
6265
+		));
6266
+	}
6267
+
6268
+
6269
+
6270
+	/**
6271
+	 * Returns all valid options for 'default_where_conditions'
6272
+	 *
6273
+	 * @return array
6274
+	 */
6275
+	public static function valid_default_where_conditions()
6276
+	{
6277
+		return array(
6278
+			EEM_Base::default_where_conditions_all,
6279
+			EEM_Base::default_where_conditions_this_only,
6280
+			EEM_Base::default_where_conditions_others_only,
6281
+			EEM_Base::default_where_conditions_minimum_all,
6282
+			EEM_Base::default_where_conditions_minimum_others,
6283
+			EEM_Base::default_where_conditions_none
6284
+		);
6285
+	}
6286
+
6287
+	// public static function default_where_conditions_full
6288
+	/**
6289
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6290
+	 *
6291
+	 * @param string $context
6292
+	 * @return bool
6293
+	 * @throws EE_Error
6294
+	 */
6295
+	public static function verify_is_valid_cap_context($context)
6296
+	{
6297
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6298
+		if (in_array($context, $valid_cap_contexts)) {
6299
+			return true;
6300
+		}
6301
+		throw new EE_Error(
6302
+			sprintf(
6303
+				esc_html__(
6304
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6305
+					'event_espresso'
6306
+				),
6307
+				$context,
6308
+				'EEM_Base',
6309
+				implode(',', $valid_cap_contexts)
6310
+			)
6311
+		);
6312
+	}
6313
+
6314
+
6315
+
6316
+	/**
6317
+	 * Clears all the models field caches. This is only useful when a sub-class
6318
+	 * might have added a field or something and these caches might be invalidated
6319
+	 */
6320
+	protected function _invalidate_field_caches()
6321
+	{
6322
+		$this->_cache_foreign_key_to_fields = array();
6323
+		$this->_cached_fields = null;
6324
+		$this->_cached_fields_non_db_only = null;
6325
+	}
6326
+
6327
+
6328
+
6329
+	/**
6330
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6331
+	 * (eg "and", "or", "not").
6332
+	 *
6333
+	 * @return array
6334
+	 */
6335
+	public function logic_query_param_keys()
6336
+	{
6337
+		return $this->_logic_query_param_keys;
6338
+	}
6339
+
6340
+
6341
+
6342
+	/**
6343
+	 * Determines whether or not the where query param array key is for a logic query param.
6344
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6345
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6346
+	 *
6347
+	 * @param $query_param_key
6348
+	 * @return bool
6349
+	 */
6350
+	public function is_logic_query_param_key($query_param_key)
6351
+	{
6352
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353
+			if (
6354
+				$query_param_key === $logic_query_param_key
6355
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6356
+			) {
6357
+				return true;
6358
+			}
6359
+		}
6360
+		return false;
6361
+	}
6362
+
6363
+	/**
6364
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6365
+	 * @since 4.9.74.p
6366
+	 * @return boolean
6367
+	 */
6368
+	public function hasPassword()
6369
+	{
6370
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6371
+		if ($this->has_password_field === null) {
6372
+			$password_field = $this->getPasswordField();
6373
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6374
+		}
6375
+		return $this->has_password_field;
6376
+	}
6377
+
6378
+	/**
6379
+	 * Returns the password field on this model, if there is one
6380
+	 * @since 4.9.74.p
6381
+	 * @return EE_Password_Field|null
6382
+	 */
6383
+	public function getPasswordField()
6384
+	{
6385
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6386
+		// there's no need to search for it. If we don't know yet, then find out
6387
+		if ($this->has_password_field === null && $this->password_field === null) {
6388
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6389
+		}
6390
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6391
+		return $this->password_field;
6392
+	}
6393
+
6394
+
6395
+	/**
6396
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6397
+	 * @since 4.9.74.p
6398
+	 * @return EE_Model_Field_Base[]
6399
+	 * @throws EE_Error
6400
+	 */
6401
+	public function getPasswordProtectedFields()
6402
+	{
6403
+		$password_field = $this->getPasswordField();
6404
+		$fields = array();
6405
+		if ($password_field instanceof EE_Password_Field) {
6406
+			$field_names = $password_field->protectedFields();
6407
+			foreach ($field_names as $field_name) {
6408
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6409
+			}
6410
+		}
6411
+		return $fields;
6412
+	}
6413
+
6414
+
6415
+	/**
6416
+	 * Checks if the current user can perform the requested action on this model
6417
+	 * @since 4.9.74.p
6418
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6419
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6420
+	 * @return bool
6421
+	 * @throws EE_Error
6422
+	 * @throws InvalidArgumentException
6423
+	 * @throws InvalidDataTypeException
6424
+	 * @throws InvalidInterfaceException
6425
+	 * @throws ReflectionException
6426
+	 * @throws UnexpectedEntityException
6427
+	 */
6428
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6429
+	{
6430
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432
+		}
6433
+		if (!is_array($model_obj_or_fields_n_values)) {
6434
+			throw new UnexpectedEntityException(
6435
+				$model_obj_or_fields_n_values,
6436
+				'EE_Base_Class',
6437
+				sprintf(
6438
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6439
+					__FUNCTION__
6440
+				)
6441
+			);
6442
+		}
6443
+		return $this->exists(
6444
+			$this->alter_query_params_to_restrict_by_ID(
6445
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6446
+				array(
6447
+					'default_where_conditions' => 'none',
6448
+					'caps'                     => $cap_to_check,
6449
+				)
6450
+			)
6451
+		);
6452
+	}
6453
+
6454
+	/**
6455
+	 * Returns the query param where conditions key to the password affecting this model.
6456
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6457
+	 * @since 4.9.74.p
6458
+	 * @return null|string
6459
+	 * @throws EE_Error
6460
+	 * @throws InvalidArgumentException
6461
+	 * @throws InvalidDataTypeException
6462
+	 * @throws InvalidInterfaceException
6463
+	 * @throws ModelConfigurationException
6464
+	 * @throws ReflectionException
6465
+	 */
6466
+	public function modelChainAndPassword()
6467
+	{
6468
+		if ($this->model_chain_to_password === null) {
6469
+			throw new ModelConfigurationException(
6470
+				$this,
6471
+				esc_html_x(
6472
+				// @codingStandardsIgnoreStart
6473
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6474
+					// @codingStandardsIgnoreEnd
6475
+					'1: model name',
6476
+					'event_espresso'
6477
+				)
6478
+			);
6479
+		}
6480
+		if ($this->model_chain_to_password === '') {
6481
+			$model_with_password = $this;
6482
+		} else {
6483
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6484
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6485
+			} else {
6486
+				$last_model_in_chain = $this->model_chain_to_password;
6487
+			}
6488
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6489
+		}
6490
+
6491
+		$password_field = $model_with_password->getPasswordField();
6492
+		if ($password_field instanceof EE_Password_Field) {
6493
+			$password_field_name = $password_field->get_name();
6494
+		} else {
6495
+			throw new ModelConfigurationException(
6496
+				$this,
6497
+				sprintf(
6498
+					esc_html_x(
6499
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6500
+						'1: model name, 2: special string',
6501
+						'event_espresso'
6502
+					),
6503
+					$model_with_password->get_this_model_name(),
6504
+					$this->model_chain_to_password
6505
+				)
6506
+			);
6507
+		}
6508
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6509
+	}
6510
+
6511
+	/**
6512
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6513
+	 * or if this model itself has a password affecting access to some of its other fields.
6514
+	 * @since 4.9.74.p
6515
+	 * @return boolean
6516
+	 */
6517
+	public function restrictedByRelatedModelPassword()
6518
+	{
6519
+		return $this->model_chain_to_password !== null;
6520
+	}
6521 6521
 }
Please login to merge, or discard this patch.
Spacing   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     esc_html__(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(esc_html__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             esc_html__(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
     {
892 892
         $wp_user_field_name = $this->wp_user_field_name();
893 893
         if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
895 895
         }
896 896
         return $query_params;
897 897
     }
@@ -909,17 +909,17 @@  discard block
 block discarded – undo
909 909
     public function wp_user_field_name()
910 910
     {
911 911
         try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
912
+            if ( ! empty($this->_model_chain_to_wp_user)) {
913 913
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914 914
                 $last_model_name = end($models_to_follow_to_wp_users);
915 915
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
917 917
             } else {
918 918
                 $model_with_fk_to_wp_users = $this;
919 919
                 $model_chain_to_wp_user = '';
920 920
             }
921 921
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
923 923
         } catch (EE_Error $e) {
924 924
             return false;
925 925
         }
@@ -996,11 +996,11 @@  discard block
 block discarded – undo
996 996
         if ($this->_custom_selections instanceof CustomSelects) {
997 997
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998 998
             $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
999
+                ? ', '.$custom_expressions
1000 1000
                 : $custom_expressions;
1001 1001
         }
1002 1002
 
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1004 1004
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005 1005
     }
1006 1006
 
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
      */
1018 1018
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019 1019
     {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021 1021
             return null;
1022 1022
         }
1023 1023
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             esc_html__(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159 1159
     {
1160
-        if (! isset($query_params[0])) {
1160
+        if ( ! isset($query_params[0])) {
1161 1161
             $query_params[0] = array();
1162 1162
         }
1163 1163
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1164 1164
         if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
+            $query_params[0][$this->primary_key_name()] = $id;
1166 1166
         } else {
1167 1167
             // no primary key, so the $id must be from the get_index_primary_key_string()
1168 1168
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function get_one($query_params = array())
1184 1184
     {
1185
-        if (! is_array($query_params)) {
1185
+        if ( ! is_array($query_params)) {
1186 1186
             EE_Error::doing_it_wrong(
1187 1187
                 'EEM_Base::get_one',
1188 1188
                 sprintf(
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
                 return array();
1381 1381
             }
1382 1382
         }
1383
-        if (! is_array($query_params)) {
1383
+        if ( ! is_array($query_params)) {
1384 1384
             EE_Error::doing_it_wrong(
1385 1385
                 'EEM_Base::_get_consecutive',
1386 1386
                 sprintf(
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
             $query_params = array();
1393 1393
         }
1394 1394
         // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1396 1396
         $query_params['limit'] = $limit;
1397 1397
         // set direction
1398 1398
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
     {
1474 1474
         $field_settings = $this->field_settings_for($field_name);
1475 1475
         // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1477 1477
             throw new EE_Error(sprintf(esc_html__(
1478 1478
                 'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1479 1479
                 'event_espresso'
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
      */
1623 1623
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624 1624
     {
1625
-        if (! is_array($query_params)) {
1625
+        if ( ! is_array($query_params)) {
1626 1626
             EE_Error::doing_it_wrong(
1627 1627
                 'EEM_Base::update',
1628 1628
                 sprintf(
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
             $wpdb_result = (array) $wpdb_result;
1671 1671
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672 1672
             if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1674 1674
             } else {
1675 1675
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1676 1676
                 $main_table_pk_value = null;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
                     // in this table, right? so insert a row in the current table, using any fields available
1687 1687
                     if (
1688 1688
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1689
+                           && $wpdb_result[$this_table_pk_column])
1690 1690
                     ) {
1691 1691
                         $success = $this->_insert_into_specific_table(
1692 1692
                             $table_obj,
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                             $main_table_pk_value
1695 1695
                         );
1696 1696
                         // if we died here, report the error
1697
-                        if (! $success) {
1697
+                        if ( ! $success) {
1698 1698
                             return false;
1699 1699
                         }
1700 1700
                     }
@@ -1722,10 +1722,10 @@  discard block
 block discarded – undo
1722 1722
                 $model_objs_affected_ids = array();
1723 1723
                 foreach ($models_affected_key_columns as $row) {
1724 1724
                     $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1726 1726
                 }
1727 1727
             }
1728
-            if (! $model_objs_affected_ids) {
1728
+            if ( ! $model_objs_affected_ids) {
1729 1729
                 // wait wait wait- if nothing was affected let's stop here
1730 1730
                 return 0;
1731 1731
             }
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
                . $model_query_info->get_full_join_sql()
1753 1753
                . " SET "
1754 1754
                . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756 1756
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757 1757
         /**
1758 1758
          * Action called after a model update call has been made.
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
          * @param int      $rows_affected
1764 1764
          */
1765 1765
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1766
+        return $rows_affected; // how many supposedly got updated
1767 1767
     }
1768 1768
 
1769 1769
 
@@ -1794,7 +1794,7 @@  discard block
 block discarded – undo
1794 1794
         }
1795 1795
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1796 1796
         $select_expressions = $field->get_qualified_column();
1797
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1797
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1798 1798
         return $this->_do_wpdb_query('get_col', array($SQL));
1799 1799
     }
1800 1800
 
@@ -1812,7 +1812,7 @@  discard block
 block discarded – undo
1812 1812
     {
1813 1813
         $query_params['limit'] = 1;
1814 1814
         $col = $this->get_col($query_params, $field_to_select);
1815
-        if (! empty($col)) {
1815
+        if ( ! empty($col)) {
1816 1816
             return reset($col);
1817 1817
         }
1818 1818
         return null;
@@ -1843,7 +1843,7 @@  discard block
 block discarded – undo
1843 1843
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1844 1844
             $value_sql = $prepared_value === null ? 'NULL'
1845 1845
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1846
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1846
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1847 1847
         }
1848 1848
         return implode(",", $cols_n_values);
1849 1849
     }
@@ -1987,12 +1987,12 @@  discard block
 block discarded – undo
1987 1987
         if (
1988 1988
             $this->has_primary_key_field()
1989 1989
             && $rows_deleted !== false
1990
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1990
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1991 1991
         ) {
1992
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1992
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1993 1993
             foreach ($ids_for_removal as $id) {
1994
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1995
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1994
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1995
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1996 1996
                 }
1997 1997
             }
1998 1998
 
@@ -2028,7 +2028,7 @@  discard block
 block discarded – undo
2028 2028
          * @param int      $rows_deleted
2029 2029
          */
2030 2030
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2031
-        return $rows_deleted;// how many supposedly got deleted
2031
+        return $rows_deleted; // how many supposedly got deleted
2032 2032
     }
2033 2033
 
2034 2034
 
@@ -2122,15 +2122,15 @@  discard block
 block discarded – undo
2122 2122
                 if (
2123 2123
                     $allow_blocking
2124 2124
                     && $this->delete_is_blocked_by_related_models(
2125
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2125
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2126 2126
                     )
2127 2127
                 ) {
2128 2128
                     continue;
2129 2129
                 }
2130 2130
                 // primary table deletes
2131
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2132
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2133
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2131
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2132
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2133
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2134 2134
                 }
2135 2135
             }
2136 2136
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2139,8 +2139,8 @@  discard block
 block discarded – undo
2139 2139
                 $ids_to_delete_indexed_by_column_for_row = array();
2140 2140
                 foreach ($fields as $cpk_field) {
2141 2141
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2142
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2143
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2143
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2144 2144
                     }
2145 2145
                 }
2146 2146
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
         } elseif ($this->has_primary_key_field()) {
2179 2179
             $query = array();
2180 2180
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2181
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2181
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2182 2182
             }
2183 2183
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2184 2184
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2186,7 +2186,7 @@  discard block
 block discarded – undo
2186 2186
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2187 2187
                 $values_for_each_combined_primary_key_for_a_row = array();
2188 2188
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2189
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2189
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2190 2190
                 }
2191 2191
                 $ways_to_identify_a_row[] = '('
2192 2192
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2258,8 +2258,8 @@  discard block
 block discarded – undo
2258 2258
                 $column_to_count = '*';
2259 2259
             }
2260 2260
         }
2261
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2262
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2262
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2263 2263
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2264 2264
     }
2265 2265
 
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             $field_obj = $this->get_primary_key_field();
2283 2283
         }
2284 2284
         $column_to_count = $field_obj->get_qualified_column();
2285
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2285
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2286 2286
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2287 2287
         $data_type = $field_obj->get_wpdb_data_type();
2288 2288
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2309,7 +2309,7 @@  discard block
 block discarded – undo
2309 2309
         // if we're in maintenance mode level 2, DON'T run any queries
2310 2310
         // because level 2 indicates the database needs updating and
2311 2311
         // is probably out of sync with the code
2312
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2312
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2313 2313
             throw new EE_Error(sprintf(esc_html__(
2314 2314
                 "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2315 2315
                 "event_espresso"
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
         }
2318 2318
         /** @type WPDB $wpdb */
2319 2319
         global $wpdb;
2320
-        if (! method_exists($wpdb, $wpdb_method)) {
2320
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2321 2321
             throw new EE_Error(sprintf(esc_html__(
2322 2322
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2323 2323
                 'event_espresso'
@@ -2331,7 +2331,7 @@  discard block
 block discarded – undo
2331 2331
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2332 2332
         if (WP_DEBUG) {
2333 2333
             $wpdb->show_errors($old_show_errors_value);
2334
-            if (! empty($wpdb->last_error)) {
2334
+            if ( ! empty($wpdb->last_error)) {
2335 2335
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2336 2336
             }
2337 2337
             if ($result === false) {
@@ -2397,7 +2397,7 @@  discard block
 block discarded – undo
2397 2397
                     return $result;
2398 2398
                     break;
2399 2399
             }
2400
-            if (! empty($error_message)) {
2400
+            if ( ! empty($error_message)) {
2401 2401
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2402 2402
                 trigger_error($error_message);
2403 2403
             }
@@ -2477,11 +2477,11 @@  discard block
 block discarded – undo
2477 2477
      */
2478 2478
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2479 2479
     {
2480
-        return " FROM " . $model_query_info->get_full_join_sql() .
2481
-               $model_query_info->get_where_sql() .
2482
-               $model_query_info->get_group_by_sql() .
2483
-               $model_query_info->get_having_sql() .
2484
-               $model_query_info->get_order_by_sql() .
2480
+        return " FROM ".$model_query_info->get_full_join_sql().
2481
+               $model_query_info->get_where_sql().
2482
+               $model_query_info->get_group_by_sql().
2483
+               $model_query_info->get_having_sql().
2484
+               $model_query_info->get_order_by_sql().
2485 2485
                $model_query_info->get_limit_sql();
2486 2486
     }
2487 2487
 
@@ -2677,12 +2677,12 @@  discard block
 block discarded – undo
2677 2677
         $related_model = $this->get_related_model_obj($model_name);
2678 2678
         // we're just going to use the query params on the related model's normal get_all query,
2679 2679
         // except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2680
+        if ( ! isset($query_params['default_where_conditions'])) {
2681 2681
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682 2682
         }
2683 2683
         $this_model_name = $this->get_this_model_name();
2684 2684
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2685
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2686 2686
         return $related_model->count($query_params, $field_to_count, $distinct);
2687 2687
     }
2688 2688
 
@@ -2702,7 +2702,7 @@  discard block
 block discarded – undo
2702 2702
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2703 2703
     {
2704 2704
         $related_model = $this->get_related_model_obj($model_name);
2705
-        if (! is_array($query_params)) {
2705
+        if ( ! is_array($query_params)) {
2706 2706
             EE_Error::doing_it_wrong(
2707 2707
                 'EEM_Base::sum_related',
2708 2708
                 sprintf(
@@ -2715,12 +2715,12 @@  discard block
 block discarded – undo
2715 2715
         }
2716 2716
         // we're just going to use the query params on the related model's normal get_all query,
2717 2717
         // except add a condition to say to match the current mod
2718
-        if (! isset($query_params['default_where_conditions'])) {
2718
+        if ( ! isset($query_params['default_where_conditions'])) {
2719 2719
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2720 2720
         }
2721 2721
         $this_model_name = $this->get_this_model_name();
2722 2722
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2723
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2723
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2724 2724
         return $related_model->sum($query_params, $field_to_sum);
2725 2725
     }
2726 2726
 
@@ -2773,7 +2773,7 @@  discard block
 block discarded – undo
2773 2773
                 $field_with_model_name = $field;
2774 2774
             }
2775 2775
         }
2776
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2776
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2777 2777
             throw new EE_Error(sprintf(
2778 2778
                 esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2779 2779
                 $this->get_this_model_name()
@@ -2910,13 +2910,13 @@  discard block
 block discarded – undo
2910 2910
                 || $this->get_primary_key_field()
2911 2911
                    instanceof
2912 2912
                    EE_Primary_Key_String_Field)
2913
-            && isset($fields_n_values[ $this->primary_key_name() ])
2913
+            && isset($fields_n_values[$this->primary_key_name()])
2914 2914
         ) {
2915
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2915
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2916 2916
         }
2917 2917
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2918 2918
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2919
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2919
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2920 2920
         }
2921 2921
         // if there is nothing to base this search on, then we shouldn't find anything
2922 2922
         if (empty($query_params)) {
@@ -2994,15 +2994,15 @@  discard block
 block discarded – undo
2994 2994
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2995 2995
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2996 2996
             if ($prepared_value !== null) {
2997
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2997
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2998 2998
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2999 2999
             }
3000 3000
         }
3001 3001
         if ($table instanceof EE_Secondary_Table && $new_id) {
3002 3002
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3003 3003
             // so add the fk to the main table as a column
3004
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3005
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3005
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3006 3006
         }
3007 3007
         // insert the new entry
3008 3008
         $result = $this->_do_wpdb_query(
@@ -3019,7 +3019,7 @@  discard block
 block discarded – undo
3019 3019
             }
3020 3020
             // it's not an auto-increment primary key, so
3021 3021
             // it must have been supplied
3022
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3022
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3023 3023
         }
3024 3024
         // we can't return a  primary key because there is none. instead return
3025 3025
         // a unique string indicating this model
@@ -3044,14 +3044,14 @@  discard block
 block discarded – undo
3044 3044
         if (
3045 3045
             ! $field_obj->is_nullable()
3046 3046
             && (
3047
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3048
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
+                ! isset($fields_n_values[$field_obj->get_name()])
3048
+                || $fields_n_values[$field_obj->get_name()] === null
3049 3049
             )
3050 3050
         ) {
3051
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3051
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3052 3052
         }
3053
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3054
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3054
+            ? $fields_n_values[$field_obj->get_name()]
3055 3055
             : null;
3056 3056
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3057 3057
     }
@@ -3152,7 +3152,7 @@  discard block
 block discarded – undo
3152 3152
      */
3153 3153
     public function get_table_obj_by_alias($table_alias = '')
3154 3154
     {
3155
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3155
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156 3156
     }
3157 3157
 
3158 3158
 
@@ -3167,7 +3167,7 @@  discard block
 block discarded – undo
3167 3167
         $other_tables = array();
3168 3168
         foreach ($this->_tables as $table_alias => $table) {
3169 3169
             if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[ $table_alias ] = $table;
3170
+                $other_tables[$table_alias] = $table;
3171 3171
             }
3172 3172
         }
3173 3173
         return $other_tables;
@@ -3183,7 +3183,7 @@  discard block
 block discarded – undo
3183 3183
      */
3184 3184
     public function _get_fields_for_table($table_alias)
3185 3185
     {
3186
-        return $this->_fields[ $table_alias ];
3186
+        return $this->_fields[$table_alias];
3187 3187
     }
3188 3188
 
3189 3189
 
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
                     $query_info_carrier,
3213 3213
                     'group_by'
3214 3214
                 );
3215
-            } elseif (! empty($query_params['group_by'])) {
3215
+            } elseif ( ! empty($query_params['group_by'])) {
3216 3216
                 $this->_extract_related_model_info_from_query_param(
3217 3217
                     $query_params['group_by'],
3218 3218
                     $query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                     $query_info_carrier,
3235 3235
                     'order_by'
3236 3236
                 );
3237
-            } elseif (! empty($query_params['order_by'])) {
3237
+            } elseif ( ! empty($query_params['order_by'])) {
3238 3238
                 $this->_extract_related_model_info_from_query_param(
3239 3239
                     $query_params['order_by'],
3240 3240
                     $query_info_carrier,
@@ -3269,7 +3269,7 @@  discard block
 block discarded – undo
3269 3269
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270 3270
         $query_param_type
3271 3271
     ) {
3272
-        if (! empty($sub_query_params)) {
3272
+        if ( ! empty($sub_query_params)) {
3273 3273
             $sub_query_params = (array) $sub_query_params;
3274 3274
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275 3275
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                 // of array('Registration.TXN_ID'=>23)
3285 3285
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3286 3286
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3287
-                    if (! is_array($possibly_array_of_params)) {
3287
+                    if ( ! is_array($possibly_array_of_params)) {
3288 3288
                         throw new EE_Error(sprintf(
3289 3289
                             esc_html__(
3290 3290
                                 "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
@@ -3308,7 +3308,7 @@  discard block
 block discarded – undo
3308 3308
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3309 3309
                     // indicating that $possible_array_of_params[1] is actually a field name,
3310 3310
                     // from which we should extract query parameters!
3311
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3311
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3312 3312
                         throw new EE_Error(sprintf(esc_html__(
3313 3313
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3314 3314
                             "event_espresso"
@@ -3342,8 +3342,8 @@  discard block
 block discarded – undo
3342 3342
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3343 3343
         $query_param_type
3344 3344
     ) {
3345
-        if (! empty($sub_query_params)) {
3346
-            if (! is_array($sub_query_params)) {
3345
+        if ( ! empty($sub_query_params)) {
3346
+            if ( ! is_array($sub_query_params)) {
3347 3347
                 throw new EE_Error(sprintf(
3348 3348
                     esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3349 3349
                     $sub_query_params
@@ -3377,7 +3377,7 @@  discard block
 block discarded – undo
3377 3377
      */
3378 3378
     public function _create_model_query_info_carrier($query_params)
3379 3379
     {
3380
-        if (! is_array($query_params)) {
3380
+        if ( ! is_array($query_params)) {
3381 3381
             EE_Error::doing_it_wrong(
3382 3382
                 'EEM_Base::_create_model_query_info_carrier',
3383 3383
                 sprintf(
@@ -3410,7 +3410,7 @@  discard block
 block discarded – undo
3410 3410
             // only include if related to a cpt where no password has been set
3411 3411
             $query_params[0]['OR*nopassword'] = array(
3412 3412
                 $where_param_key_for_password => '',
3413
-                $where_param_key_for_password . '*' => array('IS_NULL')
3413
+                $where_param_key_for_password.'*' => array('IS_NULL')
3414 3414
             );
3415 3415
         }
3416 3416
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3464,7 +3464,7 @@  discard block
 block discarded – undo
3464 3464
         // set limit
3465 3465
         if (array_key_exists('limit', $query_params)) {
3466 3466
             if (is_array($query_params['limit'])) {
3467
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3467
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3468 3468
                     $e = sprintf(
3469 3469
                         esc_html__(
3470 3470
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3472,12 +3472,12 @@  discard block
 block discarded – undo
3472 3472
                         ),
3473 3473
                         http_build_query($query_params['limit'])
3474 3474
                     );
3475
-                    throw new EE_Error($e . "|" . $e);
3475
+                    throw new EE_Error($e."|".$e);
3476 3476
                 }
3477 3477
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3479
-            } elseif (! empty($query_params['limit'])) {
3480
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3478
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3479
+            } elseif ( ! empty($query_params['limit'])) {
3480
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3481 3481
             }
3482 3482
         }
3483 3483
         // set order by
@@ -3509,10 +3509,10 @@  discard block
 block discarded – undo
3509 3509
                 $order_array = array();
3510 3510
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3511 3511
                     $order = $this->_extract_order($order);
3512
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3512
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3513 3513
                 }
3514
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3515
-            } elseif (! empty($query_params['order_by'])) {
3514
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3515
+            } elseif ( ! empty($query_params['order_by'])) {
3516 3516
                 $this->_extract_related_model_info_from_query_param(
3517 3517
                     $query_params['order_by'],
3518 3518
                     $query_object,
@@ -3523,7 +3523,7 @@  discard block
 block discarded – undo
3523 3523
                     ? $this->_extract_order($query_params['order'])
3524 3524
                     : 'DESC';
3525 3525
                 $query_object->set_order_by_sql(
3526
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3526
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3527 3527
                 );
3528 3528
             }
3529 3529
         }
@@ -3535,7 +3535,7 @@  discard block
 block discarded – undo
3535 3535
         ) {
3536 3536
             $pk_field = $this->get_primary_key_field();
3537 3537
             $order = $this->_extract_order($query_params['order']);
3538
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3538
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3539 3539
         }
3540 3540
         // set group by
3541 3541
         if (array_key_exists('group_by', $query_params)) {
@@ -3545,10 +3545,10 @@  discard block
 block discarded – undo
3545 3545
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3546 3546
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3547 3547
                 }
3548
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3549
-            } elseif (! empty($query_params['group_by'])) {
3548
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3549
+            } elseif ( ! empty($query_params['group_by'])) {
3550 3550
                 $query_object->set_group_by_sql(
3551
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3551
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3552 3552
                 );
3553 3553
             }
3554 3554
         }
@@ -3558,7 +3558,7 @@  discard block
 block discarded – undo
3558 3558
         }
3559 3559
         // now, just verify they didn't pass anything wack
3560 3560
         foreach ($query_params as $query_key => $query_value) {
3561
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3561
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3562 3562
                 throw new EE_Error(
3563 3563
                     sprintf(
3564 3564
                         esc_html__(
@@ -3666,7 +3666,7 @@  discard block
 block discarded – undo
3666 3666
         $where_query_params = array()
3667 3667
     ) {
3668 3668
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3669
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3669
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3670 3670
             throw new EE_Error(sprintf(
3671 3671
                 esc_html__(
3672 3672
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3798,19 +3798,19 @@  discard block
 block discarded – undo
3798 3798
     ) {
3799 3799
         $null_friendly_where_conditions = array();
3800 3800
         $none_overridden = true;
3801
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3801
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3802 3802
         foreach ($default_where_conditions as $key => $val) {
3803
-            if (isset($provided_where_conditions[ $key ])) {
3803
+            if (isset($provided_where_conditions[$key])) {
3804 3804
                 $none_overridden = false;
3805 3805
             } else {
3806
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3806
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3807 3807
             }
3808 3808
         }
3809 3809
         if ($none_overridden && $default_where_conditions) {
3810 3810
             if ($model->has_primary_key_field()) {
3811
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3811
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3812 3812
                                                                                 . "."
3813
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3813
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3814 3814
             }/*else{
3815 3815
                 //@todo NO PK, use other defaults
3816 3816
             }*/
@@ -3917,7 +3917,7 @@  discard block
 block discarded – undo
3917 3917
             foreach ($tables as $table_obj) {
3918 3918
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3919 3919
                                        . $table_obj->get_fully_qualified_pk_column();
3920
-                if (! in_array($qualified_pk_column, $selects)) {
3920
+                if ( ! in_array($qualified_pk_column, $selects)) {
3921 3921
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3922 3922
                 }
3923 3923
             }
@@ -4069,9 +4069,9 @@  discard block
 block discarded – undo
4069 4069
         $query_parameter_type
4070 4070
     ) {
4071 4071
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4072
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4072
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4073 4073
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4074
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4074
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4075 4075
                 if ($possible_join_string === '') {
4076 4076
                     // nothing left to $query_param
4077 4077
                     // we should actually end in a field name, not a model like this!
@@ -4202,7 +4202,7 @@  discard block
 block discarded – undo
4202 4202
     {
4203 4203
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4204 4204
         if ($SQL) {
4205
-            return " WHERE " . $SQL;
4205
+            return " WHERE ".$SQL;
4206 4206
         }
4207 4207
         return '';
4208 4208
     }
@@ -4221,7 +4221,7 @@  discard block
 block discarded – undo
4221 4221
     {
4222 4222
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4223 4223
         if ($SQL) {
4224
-            return " HAVING " . $SQL;
4224
+            return " HAVING ".$SQL;
4225 4225
         }
4226 4226
         return '';
4227 4227
     }
@@ -4240,7 +4240,7 @@  discard block
 block discarded – undo
4240 4240
     {
4241 4241
         $where_clauses = array();
4242 4242
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4243
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4243
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4244 4244
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4245 4245
                 switch ($query_param) {
4246 4246
                     case 'not':
@@ -4274,7 +4274,7 @@  discard block
 block discarded – undo
4274 4274
             } else {
4275 4275
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4276 4276
                 // if it's not a normal field, maybe it's a custom selection?
4277
-                if (! $field_obj) {
4277
+                if ( ! $field_obj) {
4278 4278
                     if ($this->_custom_selections instanceof CustomSelects) {
4279 4279
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4280 4280
                     } else {
@@ -4285,7 +4285,7 @@  discard block
 block discarded – undo
4285 4285
                     }
4286 4286
                 }
4287 4287
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4288
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4288
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4289 4289
             }
4290 4290
         }
4291 4291
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4308,7 +4308,7 @@  discard block
 block discarded – undo
4308 4308
                 $field->get_model_name(),
4309 4309
                 $query_param
4310 4310
             );
4311
-            return $table_alias_prefix . $field->get_qualified_column();
4311
+            return $table_alias_prefix.$field->get_qualified_column();
4312 4312
         }
4313 4313
         if (
4314 4314
             $this->_custom_selections instanceof CustomSelects
@@ -4368,7 +4368,7 @@  discard block
 block discarded – undo
4368 4368
     {
4369 4369
         if (is_array($op_and_value)) {
4370 4370
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4371
-            if (! $operator) {
4371
+            if ( ! $operator) {
4372 4372
                 $php_array_like_string = array();
4373 4373
                 foreach ($op_and_value as $key => $value) {
4374 4374
                     $php_array_like_string[] = "$key=>$value";
@@ -4390,14 +4390,14 @@  discard block
 block discarded – undo
4390 4390
         }
4391 4391
         // check to see if the value is actually another field
4392 4392
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4393
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4393
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4394 4394
         }
4395 4395
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4396 4396
             // in this case, the value should be an array, or at least a comma-separated list
4397 4397
             // it will need to handle a little differently
4398 4398
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4399 4399
             // note: $cleaned_value has already been run through $wpdb->prepare()
4400
-            return $operator . SP . $cleaned_value;
4400
+            return $operator.SP.$cleaned_value;
4401 4401
         }
4402 4402
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4403 4403
             // the value should be an array with count of two.
@@ -4413,7 +4413,7 @@  discard block
 block discarded – undo
4413 4413
                 );
4414 4414
             }
4415 4415
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4416
-            return $operator . SP . $cleaned_value;
4416
+            return $operator.SP.$cleaned_value;
4417 4417
         }
4418 4418
         if (in_array($operator, $this->valid_null_style_operators())) {
4419 4419
             if ($value !== null) {
@@ -4433,10 +4433,10 @@  discard block
 block discarded – undo
4433 4433
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4434 4434
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4435 4435
             // remove other junk. So just treat it as a string.
4436
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4436
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4437 4437
         }
4438
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4439
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4440 4440
         }
4441 4441
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4442 4442
             throw new EE_Error(
@@ -4450,7 +4450,7 @@  discard block
 block discarded – undo
4450 4450
                 )
4451 4451
             );
4452 4452
         }
4453
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4453
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4454 4454
             throw new EE_Error(
4455 4455
                 sprintf(
4456 4456
                     esc_html__(
@@ -4490,7 +4490,7 @@  discard block
 block discarded – undo
4490 4490
         foreach ($values as $value) {
4491 4491
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4492 4492
         }
4493
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4493
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4494 4494
     }
4495 4495
 
4496 4496
 
@@ -4524,11 +4524,11 @@  discard block
 block discarded – undo
4524 4524
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4525 4525
         if (empty($prepped)) {
4526 4526
             $all_fields = $this->field_settings();
4527
-            $first_field    = reset($all_fields);
4527
+            $first_field = reset($all_fields);
4528 4528
             $main_table = $this->_get_main_table();
4529 4529
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4530 4530
         }
4531
-        return '(' . implode(',', $prepped) . ')';
4531
+        return '('.implode(',', $prepped).')';
4532 4532
     }
4533 4533
 
4534 4534
 
@@ -4549,7 +4549,7 @@  discard block
 block discarded – undo
4549 4549
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4550 4550
             );
4551 4551
         } //$field_obj should really just be a data type
4552
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4552
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4553 4553
             throw new EE_Error(
4554 4554
                 sprintf(
4555 4555
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4582,14 +4582,14 @@  discard block
 block discarded – undo
4582 4582
             ), $query_param_name));
4583 4583
         }
4584 4584
         $number_of_parts = count($query_param_parts);
4585
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4585
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4586 4586
         if ($number_of_parts === 1) {
4587 4587
             $field_name = $last_query_param_part;
4588 4588
             $model_obj = $this;
4589 4589
         } else {// $number_of_parts >= 2
4590 4590
             // the last part is the column name, and there are only 2parts. therefore...
4591 4591
             $field_name = $last_query_param_part;
4592
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4592
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4593 4593
         }
4594 4594
         try {
4595 4595
             return $model_obj->field_settings_for($field_name);
@@ -4611,7 +4611,7 @@  discard block
 block discarded – undo
4611 4611
     public function _get_qualified_column_for_field($field_name)
4612 4612
     {
4613 4613
         $all_fields = $this->field_settings();
4614
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4614
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4615 4615
         if ($field) {
4616 4616
             return $field->get_qualified_column();
4617 4617
         }
@@ -4682,10 +4682,10 @@  discard block
 block discarded – undo
4682 4682
      */
4683 4683
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4684 4684
     {
4685
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4685
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4686 4686
         $qualified_columns = array();
4687 4687
         foreach ($this->field_settings() as $field_name => $field) {
4688
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4688
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4689 4689
         }
4690 4690
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4691 4691
     }
@@ -4709,11 +4709,11 @@  discard block
 block discarded – undo
4709 4709
             if ($table_obj instanceof EE_Primary_Table) {
4710 4710
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4711 4711
                     ? $table_obj->get_select_join_limit($limit)
4712
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4712
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4713 4713
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4714 4714
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4715 4715
                     ? $table_obj->get_select_join_limit_join($limit)
4716
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4716
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4717 4717
             }
4718 4718
         }
4719 4719
         return $SQL;
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
         foreach ($this->field_settings() as $field_obj) {
4786 4786
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4787 4787
             /** @var $field_obj EE_Model_Field_Base */
4788
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4788
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4789 4789
         }
4790 4790
         return $data_types;
4791 4791
     }
@@ -4801,14 +4801,14 @@  discard block
 block discarded – undo
4801 4801
      */
4802 4802
     public function get_related_model_obj($model_name)
4803 4803
     {
4804
-        $model_classname = "EEM_" . $model_name;
4805
-        if (! class_exists($model_classname)) {
4804
+        $model_classname = "EEM_".$model_name;
4805
+        if ( ! class_exists($model_classname)) {
4806 4806
             throw new EE_Error(sprintf(esc_html__(
4807 4807
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4808 4808
                 'event_espresso'
4809 4809
             ), $model_name, $model_classname));
4810 4810
         }
4811
-        return call_user_func($model_classname . "::instance");
4811
+        return call_user_func($model_classname."::instance");
4812 4812
     }
4813 4813
 
4814 4814
 
@@ -4837,7 +4837,7 @@  discard block
 block discarded – undo
4837 4837
         $belongs_to_relations = array();
4838 4838
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4839 4839
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4840
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4840
+                $belongs_to_relations[$model_name] = $relation_obj;
4841 4841
             }
4842 4842
         }
4843 4843
         return $belongs_to_relations;
@@ -4855,7 +4855,7 @@  discard block
 block discarded – undo
4855 4855
     public function related_settings_for($relation_name)
4856 4856
     {
4857 4857
         $relatedModels = $this->relation_settings();
4858
-        if (! array_key_exists($relation_name, $relatedModels)) {
4858
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4859 4859
             throw new EE_Error(
4860 4860
                 sprintf(
4861 4861
                     esc_html__(
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
                 )
4869 4869
             );
4870 4870
         }
4871
-        return $relatedModels[ $relation_name ];
4871
+        return $relatedModels[$relation_name];
4872 4872
     }
4873 4873
 
4874 4874
 
@@ -4885,14 +4885,14 @@  discard block
 block discarded – undo
4885 4885
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4886 4886
     {
4887 4887
         $fieldSettings = $this->field_settings($include_db_only_fields);
4888
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4888
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4889 4889
             throw new EE_Error(sprintf(
4890 4890
                 esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4891 4891
                 $fieldName,
4892 4892
                 get_class($this)
4893 4893
             ));
4894 4894
         }
4895
-        return $fieldSettings[ $fieldName ];
4895
+        return $fieldSettings[$fieldName];
4896 4896
     }
4897 4897
 
4898 4898
 
@@ -4906,7 +4906,7 @@  discard block
 block discarded – undo
4906 4906
     public function has_field($fieldName)
4907 4907
     {
4908 4908
         $fieldSettings = $this->field_settings(true);
4909
-        if (isset($fieldSettings[ $fieldName ])) {
4909
+        if (isset($fieldSettings[$fieldName])) {
4910 4910
             return true;
4911 4911
         }
4912 4912
         return false;
@@ -4923,7 +4923,7 @@  discard block
 block discarded – undo
4923 4923
     public function has_relation($relation_name)
4924 4924
     {
4925 4925
         $relations = $this->relation_settings();
4926
-        if (isset($relations[ $relation_name ])) {
4926
+        if (isset($relations[$relation_name])) {
4927 4927
             return true;
4928 4928
         }
4929 4929
         return false;
@@ -4961,7 +4961,7 @@  discard block
 block discarded – undo
4961 4961
                     break;
4962 4962
                 }
4963 4963
             }
4964
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4964
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4965 4965
                 throw new EE_Error(sprintf(
4966 4966
                     esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4967 4967
                     get_class($this)
@@ -5022,24 +5022,24 @@  discard block
 block discarded – undo
5022 5022
      */
5023 5023
     public function get_foreign_key_to($model_name)
5024 5024
     {
5025
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5025
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5026 5026
             foreach ($this->field_settings() as $field) {
5027 5027
                 if (
5028 5028
                     $field instanceof EE_Foreign_Key_Field_Base
5029 5029
                     && in_array($model_name, $field->get_model_names_pointed_to())
5030 5030
                 ) {
5031
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5031
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5032 5032
                     break;
5033 5033
                 }
5034 5034
             }
5035
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5035
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5036 5036
                 throw new EE_Error(sprintf(esc_html__(
5037 5037
                     "There is no foreign key field pointing to model %s on model %s",
5038 5038
                     'event_espresso'
5039 5039
                 ), $model_name, get_class($this)));
5040 5040
             }
5041 5041
         }
5042
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5042
+        return $this->_cache_foreign_key_to_fields[$model_name];
5043 5043
     }
5044 5044
 
5045 5045
 
@@ -5055,7 +5055,7 @@  discard block
 block discarded – undo
5055 5055
     public function get_table_for_alias($table_alias)
5056 5056
     {
5057 5057
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5058
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5058
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5059 5059
     }
5060 5060
 
5061 5061
 
@@ -5074,7 +5074,7 @@  discard block
 block discarded – undo
5074 5074
                 $this->_cached_fields = array();
5075 5075
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5076 5076
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5077
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5077
+                        $this->_cached_fields[$field_name] = $field_obj;
5078 5078
                     }
5079 5079
                 }
5080 5080
             }
@@ -5085,8 +5085,8 @@  discard block
 block discarded – undo
5085 5085
             foreach ($this->_fields as $fields_corresponding_to_table) {
5086 5086
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5087 5087
                     /** @var $field_obj EE_Model_Field_Base */
5088
-                    if (! $field_obj->is_db_only_field()) {
5089
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+                    if ( ! $field_obj->is_db_only_field()) {
5089
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5090 5090
                     }
5091 5091
                 }
5092 5092
             }
@@ -5127,12 +5127,12 @@  discard block
 block discarded – undo
5127 5127
                     $primary_key_field->get_qualified_column(),
5128 5128
                     $primary_key_field->get_table_column()
5129 5129
                 );
5130
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5130
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5131 5131
                     continue;
5132 5132
                 }
5133 5133
             }
5134 5134
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5135
-            if (! $classInstance) {
5135
+            if ( ! $classInstance) {
5136 5136
                 throw new EE_Error(
5137 5137
                     sprintf(
5138 5138
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5145,7 +5145,7 @@  discard block
 block discarded – undo
5145 5145
             $classInstance->set_timezone($this->_timezone);
5146 5146
             // make sure if there is any timezone setting present that we set the timezone for the object
5147 5147
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5148
-            $array_of_objects[ $key ] = $classInstance;
5148
+            $array_of_objects[$key] = $classInstance;
5149 5149
             // also, for all the relations of type BelongsTo, see if we can cache
5150 5150
             // those related models
5151 5151
             // (we could do this for other relations too, but if there are conditions
@@ -5189,9 +5189,9 @@  discard block
 block discarded – undo
5189 5189
         $results = array();
5190 5190
         if ($this->_custom_selections instanceof CustomSelects) {
5191 5191
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5192
-                if (isset($db_results_row[ $alias ])) {
5193
-                    $results[ $alias ] = $this->convertValueToDataType(
5194
-                        $db_results_row[ $alias ],
5192
+                if (isset($db_results_row[$alias])) {
5193
+                    $results[$alias] = $this->convertValueToDataType(
5194
+                        $db_results_row[$alias],
5195 5195
                         $this->_custom_selections->getDataTypeForAlias($alias)
5196 5196
                     );
5197 5197
                 }
@@ -5233,7 +5233,7 @@  discard block
 block discarded – undo
5233 5233
         $this_model_fields_and_values = array();
5234 5234
         // setup the row using default values;
5235 5235
         foreach ($this->field_settings() as $field_name => $field_obj) {
5236
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5236
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5237 5237
         }
5238 5238
         $className = $this->_get_class_name();
5239 5239
         $classInstance = EE_Registry::instance()
@@ -5251,20 +5251,20 @@  discard block
 block discarded – undo
5251 5251
      */
5252 5252
     public function instantiate_class_from_array_or_object($cols_n_values)
5253 5253
     {
5254
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5254
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5255 5255
             $cols_n_values = get_object_vars($cols_n_values);
5256 5256
         }
5257 5257
         $primary_key = null;
5258 5258
         // make sure the array only has keys that are fields/columns on this model
5259 5259
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5260
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5261
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5261
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5262 5262
         }
5263 5263
         $className = $this->_get_class_name();
5264 5264
         // check we actually found results that we can use to build our model object
5265 5265
         // if not, return null
5266 5266
         if ($this->has_primary_key_field()) {
5267
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5267
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5268 5268
                 return null;
5269 5269
             }
5270 5270
         } elseif ($this->unique_indexes()) {
@@ -5276,7 +5276,7 @@  discard block
 block discarded – undo
5276 5276
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5277 5277
         if ($primary_key) {
5278 5278
             $classInstance = $this->get_from_entity_map($primary_key);
5279
-            if (! $classInstance) {
5279
+            if ( ! $classInstance) {
5280 5280
                 $classInstance = EE_Registry::instance()
5281 5281
                                             ->load_class(
5282 5282
                                                 $className,
@@ -5309,8 +5309,8 @@  discard block
 block discarded – undo
5309 5309
      */
5310 5310
     public function get_from_entity_map($id)
5311 5311
     {
5312
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5313
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5313
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5314 5314
     }
5315 5315
 
5316 5316
 
@@ -5333,7 +5333,7 @@  discard block
 block discarded – undo
5333 5333
     public function add_to_entity_map(EE_Base_Class $object)
5334 5334
     {
5335 5335
         $className = $this->_get_class_name();
5336
-        if (! $object instanceof $className) {
5336
+        if ( ! $object instanceof $className) {
5337 5337
             throw new EE_Error(sprintf(
5338 5338
                 esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5339 5339
                 is_object($object) ? get_class($object) : $object,
@@ -5341,7 +5341,7 @@  discard block
 block discarded – undo
5341 5341
             ));
5342 5342
         }
5343 5343
         /** @var $object EE_Base_Class */
5344
-        if (! $object->ID()) {
5344
+        if ( ! $object->ID()) {
5345 5345
             throw new EE_Error(sprintf(esc_html__(
5346 5346
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5347 5347
                 "event_espresso"
@@ -5352,7 +5352,7 @@  discard block
 block discarded – undo
5352 5352
         if ($classInstance) {
5353 5353
             return $classInstance;
5354 5354
         }
5355
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5355
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5356 5356
         return $object;
5357 5357
     }
5358 5358
 
@@ -5368,11 +5368,11 @@  discard block
 block discarded – undo
5368 5368
     public function clear_entity_map($id = null)
5369 5369
     {
5370 5370
         if (empty($id)) {
5371
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5371
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5372 5372
             return true;
5373 5373
         }
5374
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5375
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5375
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5376 5376
             return true;
5377 5377
         }
5378 5378
         return false;
@@ -5415,17 +5415,17 @@  discard block
 block discarded – undo
5415 5415
             // there is a primary key on this table and its not set. Use defaults for all its columns
5416 5416
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5417 5417
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5418
-                    if (! $field_obj->is_db_only_field()) {
5418
+                    if ( ! $field_obj->is_db_only_field()) {
5419 5419
                         // prepare field as if its coming from db
5420 5420
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5421
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5421
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5422 5422
                     }
5423 5423
                 }
5424 5424
             } else {
5425 5425
                 // the table's rows existed. Use their values
5426 5426
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5427
-                    if (! $field_obj->is_db_only_field()) {
5428
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+                    if ( ! $field_obj->is_db_only_field()) {
5428
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5429 5429
                             $cols_n_values,
5430 5430
                             $field_obj->get_qualified_column(),
5431 5431
                             $field_obj->get_table_column()
@@ -5452,17 +5452,17 @@  discard block
 block discarded – undo
5452 5452
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5453 5453
         // does the field on the model relate to this column retrieved from the db?
5454 5454
         // or is it a db-only field? (not relating to the model)
5455
-        if (isset($cols_n_values[ $qualified_column ])) {
5456
-            $value = $cols_n_values[ $qualified_column ];
5457
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5458
-            $value = $cols_n_values[ $regular_column ];
5459
-        } elseif (! empty($this->foreign_key_aliases)) {
5455
+        if (isset($cols_n_values[$qualified_column])) {
5456
+            $value = $cols_n_values[$qualified_column];
5457
+        } elseif (isset($cols_n_values[$regular_column])) {
5458
+            $value = $cols_n_values[$regular_column];
5459
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5460 5460
             // no PK?  ok check if there is a foreign key alias set for this table
5461 5461
             // then check if that alias exists in the incoming data
5462 5462
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5463 5463
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5464
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5465
-                    $value = $cols_n_values[ $FK_alias ];
5464
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5465
+                    $value = $cols_n_values[$FK_alias];
5466 5466
                     [$pk_class] = explode('.', $PK_column);
5467 5467
                     $pk_model_name = "EEM_{$pk_class}";
5468 5468
                     /** @var EEM_Base $pk_model */
@@ -5506,7 +5506,7 @@  discard block
 block discarded – undo
5506 5506
                     $obj_in_map->clear_cache($relation_name, null, true);
5507 5507
                 }
5508 5508
             }
5509
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5509
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5510 5510
             return $obj_in_map;
5511 5511
         }
5512 5512
         return $this->get_one_by_ID($id);
@@ -5559,7 +5559,7 @@  discard block
 block discarded – undo
5559 5559
      */
5560 5560
     private function _get_class_name()
5561 5561
     {
5562
-        return "EE_" . $this->get_this_model_name();
5562
+        return "EE_".$this->get_this_model_name();
5563 5563
     }
5564 5564
 
5565 5565
 
@@ -5606,7 +5606,7 @@  discard block
 block discarded – undo
5606 5606
     {
5607 5607
         $className = get_class($this);
5608 5608
         $tagName = "FHEE__{$className}__{$methodName}";
5609
-        if (! has_filter($tagName)) {
5609
+        if ( ! has_filter($tagName)) {
5610 5610
             throw new EE_Error(
5611 5611
                 sprintf(
5612 5612
                     esc_html__(
@@ -5779,7 +5779,7 @@  discard block
 block discarded – undo
5779 5779
         $unique_indexes = array();
5780 5780
         foreach ($this->_indexes as $name => $index) {
5781 5781
             if ($index instanceof EE_Unique_Index) {
5782
-                $unique_indexes [ $name ] = $index;
5782
+                $unique_indexes [$name] = $index;
5783 5783
             }
5784 5784
         }
5785 5785
         return $unique_indexes;
@@ -5846,7 +5846,7 @@  discard block
 block discarded – undo
5846 5846
         $key_vals_in_combined_pk = array();
5847 5847
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5848 5848
         foreach ($key_fields as $key_field_name => $field_obj) {
5849
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5849
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5850 5850
                 return null;
5851 5851
             }
5852 5852
         }
@@ -5867,7 +5867,7 @@  discard block
 block discarded – undo
5867 5867
     {
5868 5868
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5869 5869
         foreach ($keys_it_should_have as $key) {
5870
-            if (! isset($key_vals[ $key ])) {
5870
+            if ( ! isset($key_vals[$key])) {
5871 5871
                 return false;
5872 5872
             }
5873 5873
         }
@@ -5900,8 +5900,8 @@  discard block
 block discarded – undo
5900 5900
         }
5901 5901
         // even copies obviously won't have the same ID, so remove the primary key
5902 5902
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5903
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5904
-            unset($attributes_array[ $this->primary_key_name() ]);
5903
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5904
+            unset($attributes_array[$this->primary_key_name()]);
5905 5905
         }
5906 5906
         if (isset($query_params[0])) {
5907 5907
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5923,7 +5923,7 @@  discard block
 block discarded – undo
5923 5923
      */
5924 5924
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5925 5925
     {
5926
-        if (! is_array($query_params)) {
5926
+        if ( ! is_array($query_params)) {
5927 5927
             EE_Error::doing_it_wrong(
5928 5928
                 'EEM_Base::get_one_copy',
5929 5929
                 sprintf(
@@ -5973,7 +5973,7 @@  discard block
 block discarded – undo
5973 5973
      */
5974 5974
     private function _prepare_operator_for_sql($operator_supplied)
5975 5975
     {
5976
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5976
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5977 5977
             : null;
5978 5978
         if ($sql_operator) {
5979 5979
             return $sql_operator;
@@ -6064,7 +6064,7 @@  discard block
 block discarded – undo
6064 6064
         $objs = $this->get_all($query_params);
6065 6065
         $names = array();
6066 6066
         foreach ($objs as $obj) {
6067
-            $names[ $obj->ID() ] = $obj->name();
6067
+            $names[$obj->ID()] = $obj->name();
6068 6068
         }
6069 6069
         return $names;
6070 6070
     }
@@ -6085,7 +6085,7 @@  discard block
 block discarded – undo
6085 6085
      */
6086 6086
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6087 6087
     {
6088
-        if (! $this->has_primary_key_field()) {
6088
+        if ( ! $this->has_primary_key_field()) {
6089 6089
             if (WP_DEBUG) {
6090 6090
                 EE_Error::add_error(
6091 6091
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6098,7 +6098,7 @@  discard block
 block discarded – undo
6098 6098
         $IDs = array();
6099 6099
         foreach ($model_objects as $model_object) {
6100 6100
             $id = $model_object->ID();
6101
-            if (! $id) {
6101
+            if ( ! $id) {
6102 6102
                 if ($filter_out_empty_ids) {
6103 6103
                     continue;
6104 6104
                 }
@@ -6149,22 +6149,22 @@  discard block
 block discarded – undo
6149 6149
         EEM_Base::verify_is_valid_cap_context($context);
6150 6150
         // check if we ought to run the restriction generator first
6151 6151
         if (
6152
-            isset($this->_cap_restriction_generators[ $context ])
6153
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6154
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6152
+            isset($this->_cap_restriction_generators[$context])
6153
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6154
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6155 6155
         ) {
6156
-            $this->_cap_restrictions[ $context ] = array_merge(
6157
-                $this->_cap_restrictions[ $context ],
6158
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6156
+            $this->_cap_restrictions[$context] = array_merge(
6157
+                $this->_cap_restrictions[$context],
6158
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6159 6159
             );
6160 6160
         }
6161 6161
         // and make sure we've finalized the construction of each restriction
6162
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6162
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6163 6163
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6164 6164
                 $where_conditions_obj->_finalize_construct($this);
6165 6165
             }
6166 6166
         }
6167
-        return $this->_cap_restrictions[ $context ];
6167
+        return $this->_cap_restrictions[$context];
6168 6168
     }
6169 6169
 
6170 6170
 
@@ -6196,9 +6196,9 @@  discard block
 block discarded – undo
6196 6196
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6197 6197
             if (
6198 6198
                 ! EE_Capabilities::instance()
6199
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6199
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6200 6200
             ) {
6201
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6201
+                $missing_caps[$cap] = $restriction_if_no_cap;
6202 6202
             }
6203 6203
         }
6204 6204
         return $missing_caps;
@@ -6233,8 +6233,8 @@  discard block
 block discarded – undo
6233 6233
     public function cap_action_for_context($context)
6234 6234
     {
6235 6235
         $mapping = $this->cap_contexts_to_cap_action_map();
6236
-        if (isset($mapping[ $context ])) {
6237
-            return $mapping[ $context ];
6236
+        if (isset($mapping[$context])) {
6237
+            return $mapping[$context];
6238 6238
         }
6239 6239
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6240 6240
             return $action;
@@ -6352,7 +6352,7 @@  discard block
 block discarded – undo
6352 6352
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6353 6353
             if (
6354 6354
                 $query_param_key === $logic_query_param_key
6355
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6355
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6356 6356
             ) {
6357 6357
                 return true;
6358 6358
             }
@@ -6405,7 +6405,7 @@  discard block
 block discarded – undo
6405 6405
         if ($password_field instanceof EE_Password_Field) {
6406 6406
             $field_names = $password_field->protectedFields();
6407 6407
             foreach ($field_names as $field_name) {
6408
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6408
+                $fields[$field_name] = $this->field_settings_for($field_name);
6409 6409
             }
6410 6410
         }
6411 6411
         return $fields;
@@ -6430,7 +6430,7 @@  discard block
 block discarded – undo
6430 6430
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6431 6431
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6432 6432
         }
6433
-        if (!is_array($model_obj_or_fields_n_values)) {
6433
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6434 6434
             throw new UnexpectedEntityException(
6435 6435
                 $model_obj_or_fields_n_values,
6436 6436
                 'EE_Base_Class',
@@ -6505,7 +6505,7 @@  discard block
 block discarded – undo
6505 6505
                 )
6506 6506
             );
6507 6507
         }
6508
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6508
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6509 6509
     }
6510 6510
 
6511 6511
     /**
Please login to merge, or discard this patch.
core/db_models/EEM_Soft_Delete_Base.model.php 2 patches
Indentation   +367 added lines, -367 removed lines patch added patch discarded remove patch
@@ -28,371 +28,371 @@
 block discarded – undo
28 28
  */
29 29
 abstract class EEM_Soft_Delete_Base extends EEM_Base
30 30
 {
31
-    /**
32
-     * @param null $timezone
33
-     * @throws EE_Error
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
-            $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
-        }
40
-        parent::__construct($timezone);
41
-    }
42
-
43
-
44
-    /**
45
-     * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
-     *
47
-     * @return string
48
-     * @throws EE_Error
49
-     */
50
-    public function deleted_field_name()
51
-    {
52
-        $field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
-        if ($field) {
54
-            return $field->get_name();
55
-        } else {
56
-            throw new EE_Error(
57
-                sprintf(
58
-                    esc_html__(
59
-                        'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
60
-                        'event_espresso'
61
-                    ),
62
-                    get_class($this),
63
-                    get_class($this)
64
-                )
65
-            );
66
-        }
67
-    }
68
-
69
-
70
-    /**
71
-     * Gets one item that's been deleted, according to $query_params
72
-     *
73
-     * @param array $query_params
74
-     * @return EE_Soft_Delete_Base_Class
75
-     * @throws EE_Error
76
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
77
-     */
78
-    public function get_one_deleted($query_params = [])
79
-    {
80
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
81
-        return $this->get_one($query_params);
82
-    }
83
-
84
-
85
-    /**
86
-     * Gets one item from the DB, regardless of whether it's been soft-deleted or not
87
-     *
88
-     * @param array $query_params like EEM_base::get_all's $query_params
89
-     * @return EE_Soft_Delete_Base_Class
90
-     * @throws EE_Error
91
-     */
92
-    public function get_one_deleted_or_undeleted($query_params = [])
93
-    {
94
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
95
-        return $this->get_one($query_params);
96
-    }
97
-
98
-
99
-    /**
100
-     * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
101
-     *
102
-     * @param int|string $id
103
-     * @return EE_Soft_Delete_Base_Class
104
-     * @throws EE_Error
105
-     */
106
-    public function get_one_by_ID_but_ignore_deleted($id)
107
-    {
108
-        return $this->get_one(
109
-            $this->alter_query_params_to_restrict_by_ID(
110
-                $id,
111
-                ['default_where_conditions' => 'default']
112
-            )
113
-        );
114
-    }
115
-
116
-
117
-    /**
118
-     * Counts all the deleted/trashed items
119
-     *
120
-     * @param array  $query_params
121
-     * @param string $field_to_count
122
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
123
-     *                             that by the setting $distinct to TRUE;
124
-     * @return int
125
-     * @throws EE_Error
126
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
127
-     */
128
-    public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
129
-    {
130
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
131
-        return $this->count($query_params, $field_to_count, $distinct);
132
-    }
133
-
134
-
135
-    /**
136
-     * Alters the query params so that only trashed/soft-deleted items are considered
137
-     *
138
-     * @param array $query_params
139
-     * @return array
140
-     * @throws EE_Error
141
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
-     */
143
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
144
-    {
145
-        $deletedFlagFieldName                     = $this->deleted_field_name();
146
-        $query_params[0][ $deletedFlagFieldName ] = true;
147
-        return $query_params;
148
-    }
149
-
150
-
151
-    /**
152
-     * Alters the query params so that only trashed/soft-deleted items are considered
153
-     *
154
-     * @param array $query_params
155
-     * @return array
156
-     * @throws EE_Error
157
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
-     */
159
-    public function alter_query_params_so_only_trashed_items_included($query_params)
160
-    {
161
-        return $this->_alter_query_params_so_only_trashed_items_included($query_params);
162
-    }
163
-
164
-
165
-    /**
166
-     * Alters the query params so each item's deleted status is ignored.
167
-     *
168
-     * @param array $query_params
169
-     * @return array
170
-     */
171
-    public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = [])
172
-    {
173
-        return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
174
-    }
175
-
176
-
177
-    /**
178
-     * Alters the query params so each item's deleted status is ignored.
179
-     *
180
-     * @param array $query_params
181
-     * @return array
182
-     */
183
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184
-    {
185
-        if (! isset($query_params['default_where_conditions'])) {
186
-            $query_params['default_where_conditions'] = 'minimum';
187
-        }
188
-        return $query_params;
189
-    }
190
-
191
-
192
-    /**
193
-     * Counts all deleted and undeleted items
194
-     *
195
-     * @param array  $query_params
196
-     * @param string $field_to_count
197
-     * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
198
-     *                             that by the setting $distinct to TRUE;
199
-     * @return int
200
-     * @throws EE_Error
201
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
202
-     */
203
-    public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
204
-    {
205
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
206
-        return $this->count($query_params, $field_to_count, $distinct);
207
-    }
208
-
209
-
210
-    /**
211
-     * Sum all the deleted items.
212
-     *
213
-     * @param array  $query_params
214
-     * @param string $field_to_sum
215
-     * @return float
216
-     * @throws EE_Error
217
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
-     */
219
-    public function sum_deleted($query_params = null, $field_to_sum = null)
220
-    {
221
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
222
-        return $this->sum($query_params, $field_to_sum);
223
-    }
224
-
225
-
226
-    /**
227
-     * Sums all the deleted and undeleted items.
228
-     *
229
-     * @param array  $query_params
230
-     * @param string $field_to_sum
231
-     * @return float
232
-     * @throws EE_Error
233
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
-     */
235
-    public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
236
-    {
237
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
238
-        return $this->sum($query_params, $field_to_sum);
239
-    }
240
-
241
-
242
-    /**
243
-     * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
244
-     * whether they've been soft-deleted or not
245
-     *
246
-     * @param array $query_params
247
-     * @return EE_Soft_Delete_Base_Class[]
248
-     * @throws EE_Error
249
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
250
-     */
251
-    public function get_all_deleted_and_undeleted($query_params = [])
252
-    {
253
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
254
-        return $this->get_all($query_params);
255
-    }
256
-
257
-
258
-    /**
259
-     * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
260
-     *
261
-     * @param array $query_params
262
-     * @return EE_Soft_Delete_Base_Class[]
263
-     * @throws EE_Error
264
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
265
-     */
266
-    public function get_all_deleted($query_params = [])
267
-    {
268
-        $query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
269
-        return $this->get_all($query_params);
270
-    }
271
-
272
-
273
-    /**
274
-     * Permanently deletes the selected rows. When selecting rows for deletion, ignores
275
-     * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
276
-     * before you can permanently delete them).
277
-     * Because this will cause a real deletion, related models may block this deletion (ie, add an error
278
-     * and abort the delete)
279
-     *
280
-     * @param array   $query_params
281
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
282
-     *                                that blocks it (ie, there' sno other data that depends on this data);
283
-     *                                if false, deletes regardless of other objects which may depend on it.
284
-     *                                Its generally advisable to always leave this as TRUE,
285
-     *                                otherwise you could easily corrupt your DB
286
-     * @return int                    number of rows deleted
287
-     * @throws EE_Error
288
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
289
-     */
290
-    public function delete_permanently($query_params, $allow_blocking = true)
291
-    {
292
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
293
-        return parent::delete_permanently($query_params, $allow_blocking);
294
-    }
295
-
296
-
297
-    /**
298
-     * Restores a particular item by its ID (primary key). Ignores the fact whether the item
299
-     * has been soft-deleted or not.
300
-     *
301
-     * @param mixed $ID int if primary key is an int, string otherwise
302
-     * @return boolean success
303
-     * @throws EE_Error
304
-     */
305
-    public function restore_by_ID($ID = false)
306
-    {
307
-        return $this->delete_or_restore_by_ID(false, $ID);
308
-    }
309
-
310
-
311
-    /**
312
-     * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
313
-     * this function will ignore whether the items have been soft-deleted or not.
314
-     *
315
-     * @param boolean $delete true for delete, false for restore
316
-     * @param mixed   $ID     int if primary key is an int, string otherwise
317
-     * @return bool
318
-     * @throws EE_Error
319
-     */
320
-    public function delete_or_restore_by_ID($delete = true, $ID = false)
321
-    {
322
-        // returns false if entity doesn't have an ID or if delete/restore action failed
323
-        return $ID && $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID));
324
-    }
325
-
326
-
327
-    /**
328
-     * Overrides parent's 'delete' method to instead do a soft delete on all rows that
329
-     * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
330
-     * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
331
-     * dependencies
332
-     *
333
-     * @param array $query_params
334
-     * @param bool  $block_deletes
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
338
-     */
339
-    public function delete($query_params = [], $block_deletes = false)
340
-    {
341
-        // no matter what, we WON'T block soft deletes.
342
-        return $this->delete_or_restore(true, $query_params);
343
-    }
344
-
345
-
346
-    /**
347
-     * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
348
-     * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
349
-     * have been soft-deleted or not.
350
-     *
351
-     * @param array $query_params
352
-     * @return bool
353
-     * @throws EE_Error
354
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
355
-     */
356
-    public function restore($query_params = [])
357
-    {
358
-        return $this->delete_or_restore(false, $query_params);
359
-    }
360
-
361
-
362
-    /**
363
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
364
-     *
365
-     * @param boolean $delete true to indicate deletion, false to indicate restoration
366
-     * @param array   $query_params
367
-     * @return boolean
368
-     * @throws EE_Error
369
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
370
-     */
371
-    public function delete_or_restore($delete = true, $query_params = [])
372
-    {
373
-        $deletedFlagFieldName = $this->deleted_field_name();
374
-        $query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
375
-        return (bool) $this->update([$deletedFlagFieldName => $delete], $query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Updates all the items of this model which match the $query params, regardless of whether
381
-     * they've been soft-deleted or not
382
-     *
383
-     * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
384
-     * @param array   $query_params            like EEM_base::get_all's $query_params
385
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
386
-     *                                         in this model's entity map according to $fields_n_values that match
387
-     *                                         $query_params. This obviously has some overhead, so you can disable it
388
-     *                                         by setting this to FALSE, but be aware that model objects being used
389
-     *                                         could get out-of-sync with the database
390
-     * @return int number of items updated
391
-     * @throws EE_Error
392
-     */
393
-    public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
394
-    {
395
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
396
-        return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
397
-    }
31
+	/**
32
+	 * @param null $timezone
33
+	 * @throws EE_Error
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38
+			$this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39
+		}
40
+		parent::__construct($timezone);
41
+	}
42
+
43
+
44
+	/**
45
+	 * Searches for field on this model of type 'deleted_flag'. if it is found, returns it's name.
46
+	 *
47
+	 * @return string
48
+	 * @throws EE_Error
49
+	 */
50
+	public function deleted_field_name()
51
+	{
52
+		$field = $this->get_a_field_of_type('EE_Trashed_Flag_Field');
53
+		if ($field) {
54
+			return $field->get_name();
55
+		} else {
56
+			throw new EE_Error(
57
+				sprintf(
58
+					esc_html__(
59
+						'We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
60
+						'event_espresso'
61
+					),
62
+					get_class($this),
63
+					get_class($this)
64
+				)
65
+			);
66
+		}
67
+	}
68
+
69
+
70
+	/**
71
+	 * Gets one item that's been deleted, according to $query_params
72
+	 *
73
+	 * @param array $query_params
74
+	 * @return EE_Soft_Delete_Base_Class
75
+	 * @throws EE_Error
76
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
77
+	 */
78
+	public function get_one_deleted($query_params = [])
79
+	{
80
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
81
+		return $this->get_one($query_params);
82
+	}
83
+
84
+
85
+	/**
86
+	 * Gets one item from the DB, regardless of whether it's been soft-deleted or not
87
+	 *
88
+	 * @param array $query_params like EEM_base::get_all's $query_params
89
+	 * @return EE_Soft_Delete_Base_Class
90
+	 * @throws EE_Error
91
+	 */
92
+	public function get_one_deleted_or_undeleted($query_params = [])
93
+	{
94
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
95
+		return $this->get_one($query_params);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Gets the item indicated by its ID. But if it's soft-deleted, pretends it doesn't exist.
101
+	 *
102
+	 * @param int|string $id
103
+	 * @return EE_Soft_Delete_Base_Class
104
+	 * @throws EE_Error
105
+	 */
106
+	public function get_one_by_ID_but_ignore_deleted($id)
107
+	{
108
+		return $this->get_one(
109
+			$this->alter_query_params_to_restrict_by_ID(
110
+				$id,
111
+				['default_where_conditions' => 'default']
112
+			)
113
+		);
114
+	}
115
+
116
+
117
+	/**
118
+	 * Counts all the deleted/trashed items
119
+	 *
120
+	 * @param array  $query_params
121
+	 * @param string $field_to_count
122
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
123
+	 *                             that by the setting $distinct to TRUE;
124
+	 * @return int
125
+	 * @throws EE_Error
126
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
127
+	 */
128
+	public function count_deleted($query_params = null, $field_to_count = null, $distinct = false)
129
+	{
130
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
131
+		return $this->count($query_params, $field_to_count, $distinct);
132
+	}
133
+
134
+
135
+	/**
136
+	 * Alters the query params so that only trashed/soft-deleted items are considered
137
+	 *
138
+	 * @param array $query_params
139
+	 * @return array
140
+	 * @throws EE_Error
141
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
+	 */
143
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
144
+	{
145
+		$deletedFlagFieldName                     = $this->deleted_field_name();
146
+		$query_params[0][ $deletedFlagFieldName ] = true;
147
+		return $query_params;
148
+	}
149
+
150
+
151
+	/**
152
+	 * Alters the query params so that only trashed/soft-deleted items are considered
153
+	 *
154
+	 * @param array $query_params
155
+	 * @return array
156
+	 * @throws EE_Error
157
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
158
+	 */
159
+	public function alter_query_params_so_only_trashed_items_included($query_params)
160
+	{
161
+		return $this->_alter_query_params_so_only_trashed_items_included($query_params);
162
+	}
163
+
164
+
165
+	/**
166
+	 * Alters the query params so each item's deleted status is ignored.
167
+	 *
168
+	 * @param array $query_params
169
+	 * @return array
170
+	 */
171
+	public function alter_query_params_so_deleted_and_undeleted_items_included($query_params = [])
172
+	{
173
+		return $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
174
+	}
175
+
176
+
177
+	/**
178
+	 * Alters the query params so each item's deleted status is ignored.
179
+	 *
180
+	 * @param array $query_params
181
+	 * @return array
182
+	 */
183
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184
+	{
185
+		if (! isset($query_params['default_where_conditions'])) {
186
+			$query_params['default_where_conditions'] = 'minimum';
187
+		}
188
+		return $query_params;
189
+	}
190
+
191
+
192
+	/**
193
+	 * Counts all deleted and undeleted items
194
+	 *
195
+	 * @param array  $query_params
196
+	 * @param string $field_to_count
197
+	 * @param bool   $distinct     if we want to only count the distinct values for the column then you can trigger
198
+	 *                             that by the setting $distinct to TRUE;
199
+	 * @return int
200
+	 * @throws EE_Error
201
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
202
+	 */
203
+	public function count_deleted_and_undeleted($query_params = null, $field_to_count = null, $distinct = false)
204
+	{
205
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
206
+		return $this->count($query_params, $field_to_count, $distinct);
207
+	}
208
+
209
+
210
+	/**
211
+	 * Sum all the deleted items.
212
+	 *
213
+	 * @param array  $query_params
214
+	 * @param string $field_to_sum
215
+	 * @return float
216
+	 * @throws EE_Error
217
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
218
+	 */
219
+	public function sum_deleted($query_params = null, $field_to_sum = null)
220
+	{
221
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
222
+		return $this->sum($query_params, $field_to_sum);
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sums all the deleted and undeleted items.
228
+	 *
229
+	 * @param array  $query_params
230
+	 * @param string $field_to_sum
231
+	 * @return float
232
+	 * @throws EE_Error
233
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
234
+	 */
235
+	public function sum_deleted_and_undeleted($query_params = null, $field_to_sum = null)
236
+	{
237
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
238
+		return $this->sum($query_params, $field_to_sum);
239
+	}
240
+
241
+
242
+	/**
243
+	 * Gets all deleted and undeleted mode objects from the db that meet the criteria, regardless of
244
+	 * whether they've been soft-deleted or not
245
+	 *
246
+	 * @param array $query_params
247
+	 * @return EE_Soft_Delete_Base_Class[]
248
+	 * @throws EE_Error
249
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
250
+	 */
251
+	public function get_all_deleted_and_undeleted($query_params = [])
252
+	{
253
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
254
+		return $this->get_all($query_params);
255
+	}
256
+
257
+
258
+	/**
259
+	 * For 'soft deletable' models, gets all which ARE deleted, according to conditions specified in $query_params.
260
+	 *
261
+	 * @param array $query_params
262
+	 * @return EE_Soft_Delete_Base_Class[]
263
+	 * @throws EE_Error
264
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
265
+	 */
266
+	public function get_all_deleted($query_params = [])
267
+	{
268
+		$query_params = $this->_alter_query_params_so_only_trashed_items_included($query_params);
269
+		return $this->get_all($query_params);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Permanently deletes the selected rows. When selecting rows for deletion, ignores
275
+	 * whether they've been soft-deleted or not. (ie, you don't have to soft-delete objects
276
+	 * before you can permanently delete them).
277
+	 * Because this will cause a real deletion, related models may block this deletion (ie, add an error
278
+	 * and abort the delete)
279
+	 *
280
+	 * @param array   $query_params
281
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
282
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
283
+	 *                                if false, deletes regardless of other objects which may depend on it.
284
+	 *                                Its generally advisable to always leave this as TRUE,
285
+	 *                                otherwise you could easily corrupt your DB
286
+	 * @return int                    number of rows deleted
287
+	 * @throws EE_Error
288
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
289
+	 */
290
+	public function delete_permanently($query_params, $allow_blocking = true)
291
+	{
292
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
293
+		return parent::delete_permanently($query_params, $allow_blocking);
294
+	}
295
+
296
+
297
+	/**
298
+	 * Restores a particular item by its ID (primary key). Ignores the fact whether the item
299
+	 * has been soft-deleted or not.
300
+	 *
301
+	 * @param mixed $ID int if primary key is an int, string otherwise
302
+	 * @return boolean success
303
+	 * @throws EE_Error
304
+	 */
305
+	public function restore_by_ID($ID = false)
306
+	{
307
+		return $this->delete_or_restore_by_ID(false, $ID);
308
+	}
309
+
310
+
311
+	/**
312
+	 * For deleting or restoring a particular item. Note that this model is a SOFT-DELETABLE model! However,
313
+	 * this function will ignore whether the items have been soft-deleted or not.
314
+	 *
315
+	 * @param boolean $delete true for delete, false for restore
316
+	 * @param mixed   $ID     int if primary key is an int, string otherwise
317
+	 * @return bool
318
+	 * @throws EE_Error
319
+	 */
320
+	public function delete_or_restore_by_ID($delete = true, $ID = false)
321
+	{
322
+		// returns false if entity doesn't have an ID or if delete/restore action failed
323
+		return $ID && $this->delete_or_restore($delete, $this->alter_query_params_to_restrict_by_ID($ID));
324
+	}
325
+
326
+
327
+	/**
328
+	 * Overrides parent's 'delete' method to instead do a soft delete on all rows that
329
+	 * meet the criteria in $where_col_n_values. This particular function ignores whether the items have been
330
+	 * soft-deleted or not. Note: because this item will be soft-deleted only, doesn't block because of model
331
+	 * dependencies
332
+	 *
333
+	 * @param array $query_params
334
+	 * @param bool  $block_deletes
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
338
+	 */
339
+	public function delete($query_params = [], $block_deletes = false)
340
+	{
341
+		// no matter what, we WON'T block soft deletes.
342
+		return $this->delete_or_restore(true, $query_params);
343
+	}
344
+
345
+
346
+	/**
347
+	 * 'Un-deletes' the chosen items. Note that this model is a SOFT-DELETABLE model! That means that, by default,
348
+	 * trashed/soft-deleted items are ignored in queries. However, this particular function ignores whether the items
349
+	 * have been soft-deleted or not.
350
+	 *
351
+	 * @param array $query_params
352
+	 * @return bool
353
+	 * @throws EE_Error
354
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
355
+	 */
356
+	public function restore($query_params = [])
357
+	{
358
+		return $this->delete_or_restore(false, $query_params);
359
+	}
360
+
361
+
362
+	/**
363
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
364
+	 *
365
+	 * @param boolean $delete true to indicate deletion, false to indicate restoration
366
+	 * @param array   $query_params
367
+	 * @return boolean
368
+	 * @throws EE_Error
369
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
370
+	 */
371
+	public function delete_or_restore($delete = true, $query_params = [])
372
+	{
373
+		$deletedFlagFieldName = $this->deleted_field_name();
374
+		$query_params         = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
375
+		return (bool) $this->update([$deletedFlagFieldName => $delete], $query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Updates all the items of this model which match the $query params, regardless of whether
381
+	 * they've been soft-deleted or not
382
+	 *
383
+	 * @param array   $fields_n_values         like EEM_Base::update's $fields_n_value
384
+	 * @param array   $query_params            like EEM_base::get_all's $query_params
385
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
386
+	 *                                         in this model's entity map according to $fields_n_values that match
387
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
388
+	 *                                         by setting this to FALSE, but be aware that model objects being used
389
+	 *                                         could get out-of-sync with the database
390
+	 * @return int number of items updated
391
+	 * @throws EE_Error
392
+	 */
393
+	public function update_deleted_and_undeleted($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
394
+	{
395
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
396
+		return $this->update($fields_n_values, $query_params, $keep_model_objs_in_sync);
397
+	}
398 398
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
      */
35 35
     protected function __construct($timezone = null)
36 36
     {
37
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
37
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
38 38
             $this->_default_where_conditions_strategy = new EE_Soft_Delete_Where_Conditions();
39 39
         }
40 40
         parent::__construct($timezone);
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
     protected function _alter_query_params_so_only_trashed_items_included($query_params)
144 144
     {
145 145
         $deletedFlagFieldName                     = $this->deleted_field_name();
146
-        $query_params[0][ $deletedFlagFieldName ] = true;
146
+        $query_params[0][$deletedFlagFieldName] = true;
147 147
         return $query_params;
148 148
     }
149 149
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
      */
183 183
     protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
184 184
     {
185
-        if (! isset($query_params['default_where_conditions'])) {
185
+        if ( ! isset($query_params['default_where_conditions'])) {
186 186
             $query_params['default_where_conditions'] = 'minimum';
187 187
         }
188 188
         return $query_params;
Please login to merge, or discard this patch.
core/db_models/EEM_Change_Log.model.php 2 patches
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -9,97 +9,97 @@  discard block
 block discarded – undo
9 9
  */
10 10
 class EEM_Change_Log extends EEM_Base
11 11
 {
12
-    /**
13
-     * the related object was created log type
14
-     */
15
-    const type_create = 'create';
12
+	/**
13
+	 * the related object was created log type
14
+	 */
15
+	const type_create = 'create';
16 16
 
17
-    /**
18
-     * the related object was updated (changed, or soft-deleted)
19
-     */
20
-    const type_update = 'update';
17
+	/**
18
+	 * the related object was updated (changed, or soft-deleted)
19
+	 */
20
+	const type_update = 'update';
21 21
 
22
-    /**
23
-     * the related object was trashed/restored/deleted
24
-     */
25
-    const type_delete = 'delete';
22
+	/**
23
+	 * the related object was trashed/restored/deleted
24
+	 */
25
+	const type_delete = 'delete';
26 26
 
27
-    /**
28
-     * the related item had something worth noting happen on it, but
29
-     * only for the purposes of debugging problems
30
-     */
31
-    const type_debug = 'debug';
27
+	/**
28
+	 * the related item had something worth noting happen on it, but
29
+	 * only for the purposes of debugging problems
30
+	 */
31
+	const type_debug = 'debug';
32 32
 
33
-    /**
34
-     * the related item had an error occur on it
35
-     */
36
-    const type_error = 'error';
33
+	/**
34
+	 * the related item had an error occur on it
35
+	 */
36
+	const type_error = 'error';
37 37
 
38
-    /**
39
-     * the related item is regarding some gateway interaction, like an IPN
40
-     * or request to process a payment
41
-     */
42
-    const type_gateway = 'gateway';
38
+	/**
39
+	 * the related item is regarding some gateway interaction, like an IPN
40
+	 * or request to process a payment
41
+	 */
42
+	const type_gateway = 'gateway';
43 43
 
44
-    /**
45
-     * private instance of the EEM_Change_Log object
46
-     *
47
-     * @access private
48
-     * @var EEM_Change_Log $_instance
49
-     */
50
-    protected static $_instance = null;
44
+	/**
45
+	 * private instance of the EEM_Change_Log object
46
+	 *
47
+	 * @access private
48
+	 * @var EEM_Change_Log $_instance
49
+	 */
50
+	protected static $_instance = null;
51 51
 
52 52
 
53
-    /**
54
-     * constructor
55
-     *
56
-     * @access protected
57
-     * @param null $timezone
58
-     * @throws EE_Error
59
-     */
60
-    protected function __construct($timezone = null)
61
-    {
62
-        $this->singular_item       = esc_html__('Log', 'event_espresso');
63
-        $this->plural_item         = esc_html__('Logs', 'event_espresso');
64
-        $this->_tables             = [
65
-            'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
-        ];
67
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
-        $this->_fields             = [
69
-            'Log' => [
70
-                'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
-                'LOG_time'    => new EE_Datetime_Field(
72
-                    'LOG_time',
73
-                    esc_html__("Log Time", 'event_espresso'),
74
-                    false,
75
-                    EE_Datetime_Field::now
76
-                ),
77
-                'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
-                    'OBJ_ID',
79
-                    esc_html__("Object ID (int or string)", 'event_espresso'),
80
-                    true,
81
-                    null,
82
-                    $models_this_can_attach_to
83
-                ),
84
-                'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
-                    'OBJ_type',
86
-                    esc_html__("Object Type", 'event_espresso'),
87
-                    true,
88
-                    null,
89
-                    $models_this_can_attach_to
90
-                ),
91
-                'LOG_type'    => new EE_Plain_Text_Field(
92
-                    'LOG_type',
93
-                    esc_html__("Type of log entry", "event_espresso"),
94
-                    false,
95
-                    self::type_debug
96
-                ),
97
-                'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
-                    'LOG_message',
99
-                    esc_html__("Log Message (body)", 'event_espresso'),
100
-                    true
101
-                ),
102
-                /*
53
+	/**
54
+	 * constructor
55
+	 *
56
+	 * @access protected
57
+	 * @param null $timezone
58
+	 * @throws EE_Error
59
+	 */
60
+	protected function __construct($timezone = null)
61
+	{
62
+		$this->singular_item       = esc_html__('Log', 'event_espresso');
63
+		$this->plural_item         = esc_html__('Logs', 'event_espresso');
64
+		$this->_tables             = [
65
+			'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
+		];
67
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
+		$this->_fields             = [
69
+			'Log' => [
70
+				'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
+				'LOG_time'    => new EE_Datetime_Field(
72
+					'LOG_time',
73
+					esc_html__("Log Time", 'event_espresso'),
74
+					false,
75
+					EE_Datetime_Field::now
76
+				),
77
+				'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
+					'OBJ_ID',
79
+					esc_html__("Object ID (int or string)", 'event_espresso'),
80
+					true,
81
+					null,
82
+					$models_this_can_attach_to
83
+				),
84
+				'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
+					'OBJ_type',
86
+					esc_html__("Object Type", 'event_espresso'),
87
+					true,
88
+					null,
89
+					$models_this_can_attach_to
90
+				),
91
+				'LOG_type'    => new EE_Plain_Text_Field(
92
+					'LOG_type',
93
+					esc_html__("Type of log entry", "event_espresso"),
94
+					false,
95
+					self::type_debug
96
+				),
97
+				'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
+					'LOG_message',
99
+					esc_html__("Log Message (body)", 'event_espresso'),
100
+					true
101
+				),
102
+				/*
103 103
                  * Note: when querying for a change log's user, the OBJ_ID and OBJ_type fields are used,
104 104
                  * not the LOG_wp_user field. E.g.,
105 105
                  * `EEM_Change_Log::instance()->get_all(array(array('WP_User.ID'=>1)))` will actually return
@@ -108,165 +108,165 @@  discard block
 block discarded – undo
108 108
                  *  If you want the latter, you can't use the model's magic joining. E.g, you would need to do
109 109
                  * `EEM_Change_Log::instance()->get_all(array(array('LOG_wp_user' => 1)))`.
110 110
                  */
111
-                'LOG_wp_user' => new EE_WP_User_Field(
112
-                    'LOG_wp_user',
113
-                    esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
-                    true
115
-                ),
116
-            ],
117
-        ];
118
-        $this->_model_relations    = [];
119
-        foreach ($models_this_can_attach_to as $model) {
120
-            if ($model != 'Change_Log') {
121
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
122
-            }
123
-        }
124
-        // use completely custom caps for this
125
-        $this->_cap_restriction_generators = false;
126
-        // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
-        foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
129
-                = new EE_Return_None_Where_Conditions();
130
-        }
131
-        parent::__construct($timezone);
132
-    }
111
+				'LOG_wp_user' => new EE_WP_User_Field(
112
+					'LOG_wp_user',
113
+					esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
+					true
115
+				),
116
+			],
117
+		];
118
+		$this->_model_relations    = [];
119
+		foreach ($models_this_can_attach_to as $model) {
120
+			if ($model != 'Change_Log') {
121
+				$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
122
+			}
123
+		}
124
+		// use completely custom caps for this
125
+		$this->_cap_restriction_generators = false;
126
+		// caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
+		foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
+			$this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
129
+				= new EE_Return_None_Where_Conditions();
130
+		}
131
+		parent::__construct($timezone);
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
137
-     * @param mixed         $message  array|string of the message you want to record
138
-     * @param EE_Base_Class $related_model_obj
139
-     * @return EE_Change_Log
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     */
143
-    public function log($log_type, $message, $related_model_obj)
144
-    {
145
-        if ($related_model_obj instanceof EE_Base_Class) {
146
-            $obj_id   = $related_model_obj->ID();
147
-            $obj_type = $related_model_obj->get_model()->get_this_model_name();
148
-        } else {
149
-            $obj_id   = null;
150
-            $obj_type = null;
151
-        }
152
-        $log = EE_Change_Log::new_instance(
153
-            [
154
-                'LOG_type'    => $log_type,
155
-                'LOG_message' => $message,
156
-                'OBJ_ID'      => $obj_id,
157
-                'OBJ_type'    => $obj_type,
158
-            ]
159
-        );
160
-        $log->save();
161
-        return $log;
162
-    }
135
+	/**
136
+	 * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
137
+	 * @param mixed         $message  array|string of the message you want to record
138
+	 * @param EE_Base_Class $related_model_obj
139
+	 * @return EE_Change_Log
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 */
143
+	public function log($log_type, $message, $related_model_obj)
144
+	{
145
+		if ($related_model_obj instanceof EE_Base_Class) {
146
+			$obj_id   = $related_model_obj->ID();
147
+			$obj_type = $related_model_obj->get_model()->get_this_model_name();
148
+		} else {
149
+			$obj_id   = null;
150
+			$obj_type = null;
151
+		}
152
+		$log = EE_Change_Log::new_instance(
153
+			[
154
+				'LOG_type'    => $log_type,
155
+				'LOG_message' => $message,
156
+				'OBJ_ID'      => $obj_id,
157
+				'OBJ_type'    => $obj_type,
158
+			]
159
+		);
160
+		$log->save();
161
+		return $log;
162
+	}
163 163
 
164 164
 
165
-    /**
166
-     * Adds a gateway log for the specified object, given its ID and type
167
-     *
168
-     * @param string $message
169
-     * @param mixed  $related_obj_id
170
-     * @param string $related_obj_type
171
-     * @return EE_Change_Log
172
-     * @throws ReflectionException
173
-     * @throws EE_Error
174
-     */
175
-    public function gateway_log($message, $related_obj_id, $related_obj_type)
176
-    {
177
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
178
-            throw new EE_Error(
179
-                sprintf(
180
-                    esc_html__(
181
-                        "'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
182
-                        "event_espresso"
183
-                    ),
184
-                    $related_obj_type
185
-                )
186
-            );
187
-        }
188
-        $log = EE_Change_Log::new_instance(
189
-            [
190
-                'LOG_type'    => EEM_Change_Log::type_gateway,
191
-                'LOG_message' => $message,
192
-                'OBJ_ID'      => $related_obj_id,
193
-                'OBJ_type'    => $related_obj_type,
194
-            ]
195
-        );
196
-        $log->save();
197
-        return $log;
198
-    }
165
+	/**
166
+	 * Adds a gateway log for the specified object, given its ID and type
167
+	 *
168
+	 * @param string $message
169
+	 * @param mixed  $related_obj_id
170
+	 * @param string $related_obj_type
171
+	 * @return EE_Change_Log
172
+	 * @throws ReflectionException
173
+	 * @throws EE_Error
174
+	 */
175
+	public function gateway_log($message, $related_obj_id, $related_obj_type)
176
+	{
177
+		if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
178
+			throw new EE_Error(
179
+				sprintf(
180
+					esc_html__(
181
+						"'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
182
+						"event_espresso"
183
+					),
184
+					$related_obj_type
185
+				)
186
+			);
187
+		}
188
+		$log = EE_Change_Log::new_instance(
189
+			[
190
+				'LOG_type'    => EEM_Change_Log::type_gateway,
191
+				'LOG_message' => $message,
192
+				'OBJ_ID'      => $related_obj_id,
193
+				'OBJ_type'    => $related_obj_type,
194
+			]
195
+		);
196
+		$log->save();
197
+		return $log;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
203
-     *
204
-     * @param array $query_params
205
-     * @return array of arrays
206
-     * @throws EE_Error
207
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
208
-     */
209
-    public function get_all_efficiently($query_params)
210
-    {
211
-        return $this->_get_all_wpdb_results($query_params);
212
-    }
201
+	/**
202
+	 * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
203
+	 *
204
+	 * @param array $query_params
205
+	 * @return array of arrays
206
+	 * @throws EE_Error
207
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
208
+	 */
209
+	public function get_all_efficiently($query_params)
210
+	{
211
+		return $this->_get_all_wpdb_results($query_params);
212
+	}
213 213
 
214 214
 
215
-    /**
216
-     * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
217
-     * models after this, they may be out-of-sync with the database
218
-     *
219
-     * @param DateTime $datetime
220
-     * @return false|int
221
-     * @throws EE_Error
222
-     */
223
-    public function delete_gateway_logs_older_than(DateTime $datetime)
224
-    {
225
-        global $wpdb;
226
-        return $wpdb->query(
227
-            $wpdb->prepare(
228
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
229
-                EEM_Change_Log::type_gateway,
230
-                $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231
-            )
232
-        );
233
-    }
215
+	/**
216
+	 * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
217
+	 * models after this, they may be out-of-sync with the database
218
+	 *
219
+	 * @param DateTime $datetime
220
+	 * @return false|int
221
+	 * @throws EE_Error
222
+	 */
223
+	public function delete_gateway_logs_older_than(DateTime $datetime)
224
+	{
225
+		global $wpdb;
226
+		return $wpdb->query(
227
+			$wpdb->prepare(
228
+				'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
229
+				EEM_Change_Log::type_gateway,
230
+				$datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231
+			)
232
+		);
233
+	}
234 234
 
235 235
 
236
-    /**
237
-     * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
238
-     * map vai the given filter.
239
-     *
240
-     * @return array
241
-     */
242
-    public static function get_pretty_label_map_for_registered_types()
243
-    {
244
-        return apply_filters(
245
-            'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
246
-            [
247
-                self::type_create  => esc_html__("Create", "event_espresso"),
248
-                self::type_update  => esc_html__("Update", "event_espresso"),
249
-                self::type_delete  => esc_html__("Delete", "event_espresso"),
250
-                self::type_debug   => esc_html__("Debug", "event_espresso"),
251
-                self::type_error   => esc_html__("Error", "event_espresso"),
252
-                self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso'),
253
-            ]
254
-        );
255
-    }
236
+	/**
237
+	 * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
238
+	 * map vai the given filter.
239
+	 *
240
+	 * @return array
241
+	 */
242
+	public static function get_pretty_label_map_for_registered_types()
243
+	{
244
+		return apply_filters(
245
+			'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
246
+			[
247
+				self::type_create  => esc_html__("Create", "event_espresso"),
248
+				self::type_update  => esc_html__("Update", "event_espresso"),
249
+				self::type_delete  => esc_html__("Delete", "event_espresso"),
250
+				self::type_debug   => esc_html__("Debug", "event_espresso"),
251
+				self::type_error   => esc_html__("Error", "event_espresso"),
252
+				self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso'),
253
+			]
254
+		);
255
+	}
256 256
 
257 257
 
258
-    /**
259
-     * Return the pretty (localized) label for the given log type identifier.
260
-     *
261
-     * @param string $type_identifier
262
-     * @return string
263
-     */
264
-    public static function get_pretty_label_for_type($type_identifier)
265
-    {
266
-        $type_identifier_map = self::get_pretty_label_map_for_registered_types();
267
-        // we fallback to the incoming type identifier if there is no localized label for it.
268
-        return isset($type_identifier_map[ $type_identifier ])
269
-            ? $type_identifier_map[ $type_identifier ]
270
-            : $type_identifier;
271
-    }
258
+	/**
259
+	 * Return the pretty (localized) label for the given log type identifier.
260
+	 *
261
+	 * @param string $type_identifier
262
+	 * @return string
263
+	 */
264
+	public static function get_pretty_label_for_type($type_identifier)
265
+	{
266
+		$type_identifier_map = self::get_pretty_label_map_for_registered_types();
267
+		// we fallback to the incoming type identifier if there is no localized label for it.
268
+		return isset($type_identifier_map[ $type_identifier ])
269
+			? $type_identifier_map[ $type_identifier ]
270
+			: $type_identifier;
271
+	}
272 272
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -115,17 +115,17 @@  discard block
 block discarded – undo
115 115
                 ),
116 116
             ],
117 117
         ];
118
-        $this->_model_relations    = [];
118
+        $this->_model_relations = [];
119 119
         foreach ($models_this_can_attach_to as $model) {
120 120
             if ($model != 'Change_Log') {
121
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
121
+                $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
122 122
             }
123 123
         }
124 124
         // use completely custom caps for this
125 125
         $this->_cap_restriction_generators = false;
126 126
         // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127 127
         foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
128
+            $this->_cap_restrictions[$cap_context][EE_Restriction_Generator_Base::get_default_restrictions_cap()]
129 129
                 = new EE_Return_None_Where_Conditions();
130 130
         }
131 131
         parent::__construct($timezone);
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
      */
175 175
     public function gateway_log($message, $related_obj_id, $related_obj_type)
176 176
     {
177
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
177
+        if ( ! EE_Registry::instance()->is_model_name($related_obj_type)) {
178 178
             throw new EE_Error(
179 179
                 sprintf(
180 180
                     esc_html__(
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
         global $wpdb;
226 226
         return $wpdb->query(
227 227
             $wpdb->prepare(
228
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
228
+                'DELETE FROM '.$this->table().' WHERE LOG_type = %s AND LOG_time < %s',
229 229
                 EEM_Change_Log::type_gateway,
230 230
                 $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
231 231
             )
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
     {
266 266
         $type_identifier_map = self::get_pretty_label_map_for_registered_types();
267 267
         // we fallback to the incoming type identifier if there is no localized label for it.
268
-        return isset($type_identifier_map[ $type_identifier ])
269
-            ? $type_identifier_map[ $type_identifier ]
268
+        return isset($type_identifier_map[$type_identifier])
269
+            ? $type_identifier_map[$type_identifier]
270 270
             : $type_identifier;
271 271
     }
272 272
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Event.model.php 1 patch
Indentation   +952 added lines, -952 removed lines patch added patch discarded remove patch
@@ -14,956 +14,956 @@
 block discarded – undo
14 14
  */
15 15
 class EEM_Event extends EEM_CPT_Base
16 16
 {
17
-    /**
18
-     * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
19
-     * event
20
-     */
21
-    const sold_out = 'sold_out';
22
-
23
-    /**
24
-     * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
25
-     * date)
26
-     */
27
-    const postponed = 'postponed';
28
-
29
-    /**
30
-     * constant used by status(), indicating that the event will no longer occur
31
-     */
32
-    const cancelled = 'cancelled';
33
-
34
-
35
-    /**
36
-     * @var string
37
-     */
38
-    protected static $_default_reg_status;
39
-
40
-
41
-    /**
42
-     * This is the default for the additional limit field.
43
-     * @var int
44
-     */
45
-    protected static $_default_additional_limit = 10;
46
-
47
-
48
-    /**
49
-     * private instance of the Event object
50
-     *
51
-     * @var EEM_Event
52
-     */
53
-    protected static $_instance;
54
-
55
-
56
-
57
-
58
-    /**
59
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
60
-     *
61
-     * @param string $timezone
62
-     * @throws \EE_Error
63
-     */
64
-    protected function __construct($timezone = null)
65
-    {
66
-        EE_Registry::instance()->load_model('Registration');
67
-        $this->singular_item = esc_html__('Event', 'event_espresso');
68
-        $this->plural_item = esc_html__('Events', 'event_espresso');
69
-        // to remove Cancelled events from the frontend, copy the following filter to your functions.php file
70
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
71
-        // to remove Postponed events from the frontend, copy the following filter to your functions.php file
72
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
73
-        // to remove Sold Out events from the frontend, copy the following filter to your functions.php file
74
-        //  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
75
-        $this->_custom_stati = apply_filters(
76
-            'AFEE__EEM_Event__construct___custom_stati',
77
-            array(
78
-                EEM_Event::cancelled => array(
79
-                    'label'  => esc_html__('Cancelled', 'event_espresso'),
80
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
81
-                ),
82
-                EEM_Event::postponed => array(
83
-                    'label'  => esc_html__('Postponed', 'event_espresso'),
84
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
85
-                ),
86
-                EEM_Event::sold_out  => array(
87
-                    'label'  => esc_html__('Sold Out', 'event_espresso'),
88
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
89
-                ),
90
-            )
91
-        );
92
-        self::$_default_reg_status = empty(self::$_default_reg_status) ? EEM_Registration::status_id_pending_payment
93
-            : self::$_default_reg_status;
94
-        $this->_tables = array(
95
-            'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
96
-            'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
97
-        );
98
-        $this->_fields = array(
99
-            'Event_CPT'  => array(
100
-                'EVT_ID'         => new EE_Primary_Key_Int_Field(
101
-                    'ID',
102
-                    esc_html__('Post ID for Event', 'event_espresso')
103
-                ),
104
-                'EVT_name'       => new EE_Plain_Text_Field(
105
-                    'post_title',
106
-                    esc_html__('Event Name', 'event_espresso'),
107
-                    false,
108
-                    ''
109
-                ),
110
-                'EVT_desc'       => new EE_Post_Content_Field(
111
-                    'post_content',
112
-                    esc_html__('Event Description', 'event_espresso'),
113
-                    false,
114
-                    ''
115
-                ),
116
-                'EVT_slug'       => new EE_Slug_Field(
117
-                    'post_name',
118
-                    esc_html__('Event Slug', 'event_espresso'),
119
-                    false,
120
-                    ''
121
-                ),
122
-                'EVT_created'    => new EE_Datetime_Field(
123
-                    'post_date',
124
-                    esc_html__('Date/Time Event Created', 'event_espresso'),
125
-                    false,
126
-                    EE_Datetime_Field::now
127
-                ),
128
-                'EVT_short_desc' => new EE_Simple_HTML_Field(
129
-                    'post_excerpt',
130
-                    esc_html__('Event Short Description', 'event_espresso'),
131
-                    false,
132
-                    ''
133
-                ),
134
-                'EVT_modified'   => new EE_Datetime_Field(
135
-                    'post_modified',
136
-                    esc_html__('Date/Time Event Modified', 'event_espresso'),
137
-                    false,
138
-                    EE_Datetime_Field::now
139
-                ),
140
-                'EVT_wp_user'    => new EE_WP_User_Field(
141
-                    'post_author',
142
-                    esc_html__('Event Creator ID', 'event_espresso'),
143
-                    false
144
-                ),
145
-                'parent'         => new EE_Integer_Field(
146
-                    'post_parent',
147
-                    esc_html__('Event Parent ID', 'event_espresso'),
148
-                    false,
149
-                    0
150
-                ),
151
-                'EVT_order'      => new EE_Integer_Field(
152
-                    'menu_order',
153
-                    esc_html__('Event Menu Order', 'event_espresso'),
154
-                    false,
155
-                    1
156
-                ),
157
-                'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
158
-                // EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
159
-                'status'         => new EE_WP_Post_Status_Field(
160
-                    'post_status',
161
-                    esc_html__('Event Status', 'event_espresso'),
162
-                    false,
163
-                    'draft',
164
-                    $this->_custom_stati
165
-                ),
166
-                'password' => new EE_Password_Field(
167
-                    'post_password',
168
-                    esc_html__('Password', 'event_espresso'),
169
-                    false,
170
-                    '',
171
-                    array(
172
-                        'EVT_desc',
173
-                        'EVT_short_desc',
174
-                        'EVT_display_desc',
175
-                        'EVT_display_ticket_selector',
176
-                        'EVT_visible_on',
177
-                        'EVT_additional_limit',
178
-                        'EVT_default_registration_status',
179
-                        'EVT_member_only',
180
-                        'EVT_phone',
181
-                        'EVT_allow_overflow',
182
-                        'EVT_timezone_string',
183
-                        'EVT_external_URL',
184
-                        'EVT_donations'
185
-                    )
186
-                )
187
-            ),
188
-            'Event_Meta' => array(
189
-                'EVTM_ID'                         => new EE_DB_Only_Float_Field(
190
-                    'EVTM_ID',
191
-                    esc_html__('Event Meta Row ID', 'event_espresso'),
192
-                    false
193
-                ),
194
-                'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
195
-                    'EVT_ID',
196
-                    esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
197
-                    false
198
-                ),
199
-                'EVT_display_desc'                => new EE_Boolean_Field(
200
-                    'EVT_display_desc',
201
-                    esc_html__('Display Description Flag', 'event_espresso'),
202
-                    false,
203
-                    true
204
-                ),
205
-                'EVT_display_ticket_selector'     => new EE_Boolean_Field(
206
-                    'EVT_display_ticket_selector',
207
-                    esc_html__('Display Ticket Selector Flag', 'event_espresso'),
208
-                    false,
209
-                    true
210
-                ),
211
-                'EVT_visible_on'                  => new EE_Datetime_Field(
212
-                    'EVT_visible_on',
213
-                    esc_html__('Event Visible Date', 'event_espresso'),
214
-                    true,
215
-                    EE_Datetime_Field::now
216
-                ),
217
-                'EVT_additional_limit'            => new EE_Integer_Field(
218
-                    'EVT_additional_limit',
219
-                    esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
220
-                    true,
221
-                    self::$_default_additional_limit
222
-                ),
223
-                'EVT_default_registration_status' => new EE_Enum_Text_Field(
224
-                    'EVT_default_registration_status',
225
-                    esc_html__('Default Registration Status on this Event', 'event_espresso'),
226
-                    false,
227
-                    EEM_Event::$_default_reg_status,
228
-                    EEM_Registration::reg_status_array()
229
-                ),
230
-                'EVT_member_only'                 => new EE_Boolean_Field(
231
-                    'EVT_member_only',
232
-                    esc_html__('Member-Only Event Flag', 'event_espresso'),
233
-                    false,
234
-                    false
235
-                ),
236
-                'EVT_phone'                       => new EE_Plain_Text_Field(
237
-                    'EVT_phone',
238
-                    esc_html__('Event Phone Number', 'event_espresso'),
239
-                    false,
240
-                    ''
241
-                ),
242
-                'EVT_allow_overflow'              => new EE_Boolean_Field(
243
-                    'EVT_allow_overflow',
244
-                    esc_html__('Allow Overflow on Event', 'event_espresso'),
245
-                    false,
246
-                    false
247
-                ),
248
-                'EVT_timezone_string'             => new EE_Plain_Text_Field(
249
-                    'EVT_timezone_string',
250
-                    esc_html__('Timezone (name) for Event times', 'event_espresso'),
251
-                    false,
252
-                    ''
253
-                ),
254
-                'EVT_external_URL'                => new EE_Plain_Text_Field(
255
-                    'EVT_external_URL',
256
-                    esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
257
-                    true
258
-                ),
259
-                'EVT_donations'                   => new EE_Boolean_Field(
260
-                    'EVT_donations',
261
-                    esc_html__('Accept Donations?', 'event_espresso'),
262
-                    false,
263
-                    false
264
-                ),
265
-            ),
266
-        );
267
-        $this->_model_relations = array(
268
-            'Registration'           => new EE_Has_Many_Relation(),
269
-            'Datetime'               => new EE_Has_Many_Relation(),
270
-            'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
271
-            'Event_Question_Group'   => new EE_Has_Many_Relation(),
272
-            'Venue'                  => new EE_HABTM_Relation('Event_Venue'),
273
-            'Term_Relationship'      => new EE_Has_Many_Relation(),
274
-            'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
275
-            'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
276
-            'Attendee'               => new EE_HABTM_Relation('Registration'),
277
-            'WP_User'                => new EE_Belongs_To_Relation(),
278
-        );
279
-        // this model is generally available for reading
280
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
281
-        $this->model_chain_to_password = '';
282
-        parent::__construct($timezone);
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * @param string $default_reg_status
289
-     */
290
-    public static function set_default_reg_status($default_reg_status)
291
-    {
292
-        self::$_default_reg_status = $default_reg_status;
293
-        // if EEM_Event has already been instantiated,
294
-        // then we need to reset the `EVT_default_reg_status` field to use the new default.
295
-        if (self::$_instance instanceof EEM_Event) {
296
-            $default_reg_status = new EE_Enum_Text_Field(
297
-                'EVT_default_registration_status',
298
-                esc_html__('Default Registration Status on this Event', 'event_espresso'),
299
-                false,
300
-                $default_reg_status,
301
-                EEM_Registration::reg_status_array()
302
-            );
303
-            $default_reg_status->_construct_finalize(
304
-                'Event_Meta',
305
-                'EVT_default_registration_status',
306
-                'EEM_Event'
307
-            );
308
-            self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
309
-        }
310
-    }
311
-
312
-
313
-    /**
314
-     * Used to override the default for the additional limit field.
315
-     * @param $additional_limit
316
-     */
317
-    public static function set_default_additional_limit($additional_limit)
318
-    {
319
-        self::$_default_additional_limit = (int) $additional_limit;
320
-        if (self::$_instance instanceof EEM_Event) {
321
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
322
-                'EVT_additional_limit',
323
-                esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
324
-                true,
325
-                self::$_default_additional_limit
326
-            );
327
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
328
-                'Event_Meta',
329
-                'EVT_additional_limit',
330
-                'EEM_Event'
331
-            );
332
-        }
333
-    }
334
-
335
-
336
-    /**
337
-     * Return what is currently set as the default additional limit for the event.
338
-     * @return int
339
-     */
340
-    public static function get_default_additional_limit()
341
-    {
342
-        return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
343
-    }
344
-
345
-
346
-    /**
347
-     * get_question_groups
348
-     *
349
-     * @return array
350
-     * @throws \EE_Error
351
-     */
352
-    public function get_all_question_groups()
353
-    {
354
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
355
-            array(
356
-                array('QSG_deleted' => false),
357
-                'order_by' => array('QSG_order' => 'ASC'),
358
-            )
359
-        );
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * get_question_groups
366
-     *
367
-     * @param int $EVT_ID
368
-     * @return array|bool
369
-     * @throws \EE_Error
370
-     */
371
-    public function get_all_event_question_groups($EVT_ID = 0)
372
-    {
373
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
374
-            EE_Error::add_error(
375
-                esc_html__(
376
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
377
-                    'event_espresso'
378
-                ),
379
-                __FILE__,
380
-                __FUNCTION__,
381
-                __LINE__
382
-            );
383
-            return false;
384
-        }
385
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
386
-            array(
387
-                array('EVT_ID' => $EVT_ID),
388
-            )
389
-        );
390
-    }
391
-
392
-
393
-    /**
394
-     * get_question_groups
395
-     *
396
-     * @param int $EVT_ID
397
-     * @param boolean $for_primary_attendee
398
-     * @return array|bool
399
-     * @throws EE_Error
400
-     * @throws InvalidArgumentException
401
-     * @throws ReflectionException
402
-     * @throws InvalidDataTypeException
403
-     * @throws InvalidInterfaceException
404
-     */
405
-    public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
406
-    {
407
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
408
-            EE_Error::add_error(
409
-                esc_html__(
410
-                    // @codingStandardsIgnoreStart
411
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
412
-                    // @codingStandardsIgnoreEnd
413
-                    'event_espresso'
414
-                ),
415
-                __FILE__,
416
-                __FUNCTION__,
417
-                __LINE__
418
-            );
419
-            return false;
420
-        }
421
-        $query_params = [
422
-            [
423
-                'EVT_ID' => $EVT_ID,
424
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true
425
-            ]
426
-        ];
427
-        if ($for_primary_attendee) {
428
-            $query_params[0]['EQG_primary'] = true;
429
-        } else {
430
-            $query_params[0]['EQG_additional'] = true;
431
-        }
432
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
433
-    }
434
-
435
-
436
-    /**
437
-     * get_question_groups
438
-     *
439
-     * @param int $EVT_ID
440
-     * @param EE_Registration $registration
441
-     * @return array|bool
442
-     * @throws EE_Error
443
-     * @throws InvalidArgumentException
444
-     * @throws InvalidDataTypeException
445
-     * @throws InvalidInterfaceException
446
-     * @throws ReflectionException
447
-     */
448
-    public function get_question_groups_for_event($EVT_ID, EE_Registration $registration)
449
-    {
450
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
451
-            EE_Error::add_error(
452
-                esc_html__(
453
-                    'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
454
-                    'event_espresso'
455
-                ),
456
-                __FILE__,
457
-                __FUNCTION__,
458
-                __LINE__
459
-            );
460
-            return false;
461
-        }
462
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
463
-            [
464
-                [
465
-                    'Event_Question_Group.EVT_ID'      => $EVT_ID,
466
-                    'Event_Question_Group.'
467
-                        . EEM_Event_Question_Group::instance()->fieldNameForContext(
468
-                            $registration->is_primary_registrant()
469
-                        ) => true
470
-                ],
471
-                'order_by' => ['QSG_order' => 'ASC'],
472
-            ]
473
-        );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * get_question_target_db_column
480
-     *
481
-     * @param string $QSG_IDs csv list of $QSG IDs
482
-     * @return array|bool
483
-     * @throws \EE_Error
484
-     */
485
-    public function get_questions_in_groups($QSG_IDs = '')
486
-    {
487
-        if (empty($QSG_IDs)) {
488
-            EE_Error::add_error(
489
-                esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
490
-                __FILE__,
491
-                __FUNCTION__,
492
-                __LINE__
493
-            );
494
-            return false;
495
-        }
496
-        return EE_Registry::instance()->load_model('Question')->get_all(
497
-            array(
498
-                array(
499
-                    'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
500
-                    'QST_deleted'           => false,
501
-                    'QST_admin_only'        => is_admin(),
502
-                ),
503
-                'order_by' => 'QST_order',
504
-            )
505
-        );
506
-    }
507
-
508
-
509
-
510
-    /**
511
-     * get_options_for_question
512
-     *
513
-     * @param string $QST_IDs csv list of $QST IDs
514
-     * @return array|bool
515
-     * @throws \EE_Error
516
-     */
517
-    public function get_options_for_question($QST_IDs)
518
-    {
519
-        if (empty($QST_IDs)) {
520
-            EE_Error::add_error(
521
-                esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
522
-                __FILE__,
523
-                __FUNCTION__,
524
-                __LINE__
525
-            );
526
-            return false;
527
-        }
528
-        return EE_Registry::instance()->load_model('Question_Option')->get_all(
529
-            array(
530
-                array(
531
-                    'Question.QST_ID' => array('IN', $QST_IDs),
532
-                    'QSO_deleted'     => false,
533
-                ),
534
-                'order_by' => 'QSO_ID',
535
-            )
536
-        );
537
-    }
538
-
539
-
540
-
541
-
542
-
543
-
544
-
545
-    /**
546
-     * Gets all events that are published
547
-     * and have event start time earlier than now and an event end time later than now
548
-     *
549
-     * @param  array $query_params An array of query params to further filter on
550
-     *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
551
-     * @param bool   $count        whether to return the count or not (default FALSE)
552
-     * @return EE_Event[]|int
553
-     * @throws \EE_Error
554
-     */
555
-    public function get_active_events($query_params, $count = false)
556
-    {
557
-        if (array_key_exists(0, $query_params)) {
558
-            $where_params = $query_params[0];
559
-            unset($query_params[0]);
560
-        } else {
561
-            $where_params = array();
562
-        }
563
-        // if we have count make sure we don't include group by
564
-        if ($count && isset($query_params['group_by'])) {
565
-            unset($query_params['group_by']);
566
-        }
567
-        // let's add specific query_params for active_events
568
-        // keep in mind this will override any sent status in the query AND any date queries.
569
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
570
-        // if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
571
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
572
-            $where_params['Datetime.DTT_EVT_start******'] = array(
573
-                '<',
574
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
575
-            );
576
-        } else {
577
-            $where_params['Datetime.DTT_EVT_start'] = array(
578
-                '<',
579
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
580
-            );
581
-        }
582
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
583
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
584
-                '>',
585
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
586
-            );
587
-        } else {
588
-            $where_params['Datetime.DTT_EVT_end'] = array(
589
-                '>',
590
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
591
-            );
592
-        }
593
-        $query_params[0] = $where_params;
594
-        // don't use $query_params with count()
595
-        // because we don't want to include additional query clauses like "GROUP BY"
596
-        return $count
597
-            ? $this->count(array($where_params), 'EVT_ID', true)
598
-            : $this->get_all($query_params);
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * get all events that are published and have an event start time later than now
605
-     *
606
-     * @param  array $query_params An array of query params to further filter on
607
-     *                             (Note that status and DTT_EVT_start will be overridden)
608
-     * @param bool   $count        whether to return the count or not (default FALSE)
609
-     * @return EE_Event[]|int
610
-     * @throws \EE_Error
611
-     */
612
-    public function get_upcoming_events($query_params, $count = false)
613
-    {
614
-        if (array_key_exists(0, $query_params)) {
615
-            $where_params = $query_params[0];
616
-            unset($query_params[0]);
617
-        } else {
618
-            $where_params = array();
619
-        }
620
-        // if we have count make sure we don't include group by
621
-        if ($count && isset($query_params['group_by'])) {
622
-            unset($query_params['group_by']);
623
-        }
624
-        // let's add specific query_params for active_events
625
-        // keep in mind this will override any sent status in the query AND any date queries.
626
-        // we need to pull events with a status of publish and sold_out
627
-        $event_status = array('publish', EEM_Event::sold_out);
628
-        // check if the user can read private events and if so add the 'private status to the were params'
629
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
630
-            $event_status[] = 'private';
631
-        }
632
-        $where_params['status'] = array('IN', $event_status);
633
-        // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
634
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
635
-            $where_params['Datetime.DTT_EVT_start*****'] = array(
636
-                '>',
637
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
638
-            );
639
-        } else {
640
-            $where_params['Datetime.DTT_EVT_start'] = array(
641
-                '>',
642
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
643
-            );
644
-        }
645
-        $query_params[0] = $where_params;
646
-        // don't use $query_params with count()
647
-        // because we don't want to include additional query clauses like "GROUP BY"
648
-        return $count
649
-            ? $this->count(array($where_params), 'EVT_ID', true)
650
-            : $this->get_all($query_params);
651
-    }
652
-
653
-
654
-
655
-    /**
656
-     * Gets all events that are published
657
-     * and have an event end time later than now
658
-     *
659
-     * @param  array $query_params An array of query params to further filter on
660
-     *                             (note that status and DTT_EVT_end will be overridden)
661
-     * @param bool   $count        whether to return the count or not (default FALSE)
662
-     * @return EE_Event[]|int
663
-     * @throws \EE_Error
664
-     */
665
-    public function get_active_and_upcoming_events($query_params, $count = false)
666
-    {
667
-        if (array_key_exists(0, $query_params)) {
668
-            $where_params = $query_params[0];
669
-            unset($query_params[0]);
670
-        } else {
671
-            $where_params = array();
672
-        }
673
-        // if we have count make sure we don't include group by
674
-        if ($count && isset($query_params['group_by'])) {
675
-            unset($query_params['group_by']);
676
-        }
677
-        // let's add specific query_params for active_events
678
-        // keep in mind this will override any sent status in the query AND any date queries.
679
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
680
-        // add where params for DTT_EVT_end
681
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
682
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
683
-                '>',
684
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
685
-            );
686
-        } else {
687
-            $where_params['Datetime.DTT_EVT_end'] = array(
688
-                '>',
689
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
690
-            );
691
-        }
692
-        $query_params[0] = $where_params;
693
-        // don't use $query_params with count()
694
-        // because we don't want to include additional query clauses like "GROUP BY"
695
-        return $count
696
-            ? $this->count(array($where_params), 'EVT_ID', true)
697
-            : $this->get_all($query_params);
698
-    }
699
-
700
-
701
-
702
-    /**
703
-     * This only returns events that are expired.
704
-     * They may still be published but all their datetimes have expired.
705
-     *
706
-     * @param  array $query_params An array of query params to further filter on
707
-     *                             (note that status and DTT_EVT_end will be overridden)
708
-     * @param bool   $count        whether to return the count or not (default FALSE)
709
-     * @return EE_Event[]|int
710
-     * @throws \EE_Error
711
-     */
712
-    public function get_expired_events($query_params, $count = false)
713
-    {
714
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
715
-        // if we have count make sure we don't include group by
716
-        if ($count && isset($query_params['group_by'])) {
717
-            unset($query_params['group_by']);
718
-        }
719
-        // let's add specific query_params for active_events
720
-        // keep in mind this will override any sent status in the query AND any date queries.
721
-        if (isset($where_params['status'])) {
722
-            unset($where_params['status']);
723
-        }
724
-        $exclude_query = $query_params;
725
-        if (isset($exclude_query[0])) {
726
-            unset($exclude_query[0]);
727
-        }
728
-        $exclude_query[0] = array(
729
-            'Datetime.DTT_EVT_end' => array(
730
-                '>',
731
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
732
-            ),
733
-        );
734
-        // first get all events that have datetimes where its not expired.
735
-        $event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
736
-        $event_ids = array_keys($event_ids);
737
-        // if we have any additional query_params, let's add them to the 'AND' condition
738
-        $and_condition = array(
739
-            'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
740
-            'EVT_ID'               => array('NOT IN', $event_ids),
741
-        );
742
-        if (isset($where_params['OR'])) {
743
-            $and_condition['OR'] = $where_params['OR'];
744
-            unset($where_params['OR']);
745
-        }
746
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
747
-            $and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
748
-            unset($where_params['Datetime.DTT_EVT_end']);
749
-        }
750
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
751
-            $and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
752
-            unset($where_params['Datetime.DTT_EVT_start']);
753
-        }
754
-        // merge remaining $where params with the and conditions.
755
-        $where_params['AND'] = array_merge($and_condition, $where_params);
756
-        $query_params[0] = $where_params;
757
-        // don't use $query_params with count()
758
-        // because we don't want to include additional query clauses like "GROUP BY"
759
-        return $count
760
-            ? $this->count(array($where_params), 'EVT_ID', true)
761
-            : $this->get_all($query_params);
762
-    }
763
-
764
-
765
-
766
-    /**
767
-     * This basically just returns the events that do not have the publish status.
768
-     *
769
-     * @param  array   $query_params An array of query params to further filter on
770
-     *                               (note that status will be overwritten)
771
-     * @param  boolean $count        whether to return the count or not (default FALSE)
772
-     * @return EE_Event[]|int
773
-     * @throws \EE_Error
774
-     */
775
-    public function get_inactive_events($query_params, $count = false)
776
-    {
777
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
778
-        // let's add in specific query_params for inactive events.
779
-        if (isset($where_params['status'])) {
780
-            unset($where_params['status']);
781
-        }
782
-        // if we have count make sure we don't include group by
783
-        if ($count && isset($query_params['group_by'])) {
784
-            unset($query_params['group_by']);
785
-        }
786
-        // if we have any additional query_params, let's add them to the 'AND' condition
787
-        $where_params['AND']['status'] = array('!=', 'publish');
788
-        if (isset($where_params['OR'])) {
789
-            $where_params['AND']['OR'] = $where_params['OR'];
790
-            unset($where_params['OR']);
791
-        }
792
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
793
-            $where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
794
-            unset($where_params['Datetime.DTT_EVT_end']);
795
-        }
796
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
797
-            $where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
798
-            unset($where_params['Datetime.DTT_EVT_start']);
799
-        }
800
-        $query_params[0] = $where_params;
801
-        // don't use $query_params with count()
802
-        // because we don't want to include additional query clauses like "GROUP BY"
803
-        return $count
804
-            ? $this->count(array($where_params), 'EVT_ID', true)
805
-            : $this->get_all($query_params);
806
-    }
807
-
808
-
809
-
810
-    /**
811
-     * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
812
-     * because we don't want to override any existing global default prices but instead insert NEW prices that get
813
-     * attached to the event. See parent for param descriptions
814
-     *
815
-     * @param        $id_or_obj
816
-     * @param        $other_model_id_or_obj
817
-     * @param string $relationName
818
-     * @param array  $where_query
819
-     * @return EE_Base_Class
820
-     * @throws EE_Error
821
-     */
822
-    public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
823
-    {
824
-        if ($relationName === 'Price') {
825
-            // let's get the PRC object for the given ID to make sure that we aren't dealing with a default
826
-            $prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
827
-            // if EVT_ID = 0, then this is a default
828
-            if ((int) $prc_chk->get('EVT_ID') === 0) {
829
-                // let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
830
-                $prc_chk->set('PRC_ID', 0);
831
-            }
832
-            // run parent
833
-            return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
834
-        }
835
-        // otherwise carry on as normal
836
-        return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
837
-    }
838
-
839
-
840
-
841
-    /******************** DEPRECATED METHODS ********************/
842
-
843
-
844
-
845
-    /**
846
-     * _get_question_target_db_column
847
-     *
848
-     * @deprecated as of 4.8.32.rc.001. Instead consider using
849
-     *             EE_Registration_Custom_Questions_Form located in
850
-     *             admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
851
-     * @access     public
852
-     * @param    EE_Registration $registration (so existing answers for registration are included)
853
-     * @param    int             $EVT_ID       so all question groups are included for event (not just answers from
854
-     *                                         registration).
855
-     * @throws EE_Error
856
-     * @return    array
857
-     */
858
-    public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
859
-    {
860
-        if (empty($EVT_ID)) {
861
-            throw new EE_Error(esc_html__(
862
-                'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
863
-                'event_espresso'
864
-            ));
865
-        }
866
-        $questions = array();
867
-        // get all question groups for event
868
-        $qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
869
-        if (! empty($qgs)) {
870
-            foreach ($qgs as $qg) {
871
-                $qsts = $qg->questions();
872
-                $questions[ $qg->ID() ] = $qg->model_field_array();
873
-                $questions[ $qg->ID() ]['QSG_questions'] = array();
874
-                foreach ($qsts as $qst) {
875
-                    if ($qst->is_system_question()) {
876
-                        continue;
877
-                    }
878
-                    $answer = EEM_Answer::instance()->get_one(array(
879
-                        array(
880
-                            'QST_ID' => $qst->ID(),
881
-                            'REG_ID' => $registration->ID(),
882
-                        ),
883
-                    ));
884
-                    $answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
885
-                    $qst_name = $qstn_id = $qst->ID();
886
-                    $ans_id = $answer->ID();
887
-                    $qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
888
-                    $input_name = '';
889
-                    $input_id = sanitize_key($qst->display_text());
890
-                    $input_class = '';
891
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ] = $qst->model_field_array();
892
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name'] = 'qstn'
893
-                                                                                           . $input_name
894
-                                                                                           . $qst_name;
895
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id'] = $input_id . '-' . $qstn_id;
896
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
897
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'] = array();
898
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj'] = $qst;
899
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj'] = $answer;
900
-                    // leave responses as-is, don't convert stuff into html entities please!
901
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
902
-                    if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
903
-                        $QSOs = $qst->options(true, $answer->value());
904
-                        if (is_array($QSOs)) {
905
-                            foreach ($QSOs as $QSO_ID => $QSO) {
906
-                                $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] = $QSO->model_field_array();
907
-                            }
908
-                        }
909
-                    }
910
-                }
911
-            }
912
-        }
913
-        return $questions;
914
-    }
915
-
916
-
917
-    /**
918
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
919
-     *                             or an stdClass where each property is the name of a column,
920
-     * @return EE_Base_Class
921
-     * @throws \EE_Error
922
-     */
923
-    public function instantiate_class_from_array_or_object($cols_n_values)
924
-    {
925
-        $classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
926
-        if ($classInstance instanceof EE_Event) {
927
-            // events have their timezone defined in the DB, so use it immediately
928
-            $this->set_timezone($classInstance->get_timezone());
929
-        }
930
-        return $classInstance;
931
-    }
932
-
933
-
934
-    /**
935
-     * Deletes the model objects that meet the query params. Note: this method is overridden
936
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
937
-     * as archived, not actually deleted
938
-     *
939
-     * @param array   $query_params
940
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
941
-     *                                that blocks it (ie, there' sno other data that depends on this data);
942
-     *                                if false, deletes regardless of other objects which may depend on it.
943
-     *                                Its generally advisable to always leave this as TRUE,
944
-     *                                otherwise you could easily corrupt your DB
945
-     * @return int                    number of rows deleted
946
-     * @throws EE_Error
947
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
948
-     */
949
-    public function delete_permanently($query_params, $allow_blocking = true)
950
-    {
951
-        $deleted = parent::delete_permanently($query_params, $allow_blocking);
952
-        if ($deleted) {
953
-            // get list of events with no prices
954
-            $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', []);
955
-            $where = isset($query_params[0]) ? $query_params[0] : [];
956
-            $where_event = isset($where['EVT_ID']) ? $where['EVT_ID'] : ['', ''];
957
-            $where_event_ids = isset($where_event[1]) ? $where_event[1] : '';
958
-            $event_ids = is_string($where_event_ids)
959
-                ? explode(',', $where_event_ids)
960
-                : (array) $where_event_ids;
961
-            array_walk($event_ids, 'trim');
962
-            $event_ids = array_filter($event_ids);
963
-            // remove events from list of events with no prices
964
-            $espresso_no_ticket_prices = array_diff($espresso_no_ticket_prices, $event_ids);
965
-            update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
966
-        }
967
-        return $deleted;
968
-    }
17
+	/**
18
+	 * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
19
+	 * event
20
+	 */
21
+	const sold_out = 'sold_out';
22
+
23
+	/**
24
+	 * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
25
+	 * date)
26
+	 */
27
+	const postponed = 'postponed';
28
+
29
+	/**
30
+	 * constant used by status(), indicating that the event will no longer occur
31
+	 */
32
+	const cancelled = 'cancelled';
33
+
34
+
35
+	/**
36
+	 * @var string
37
+	 */
38
+	protected static $_default_reg_status;
39
+
40
+
41
+	/**
42
+	 * This is the default for the additional limit field.
43
+	 * @var int
44
+	 */
45
+	protected static $_default_additional_limit = 10;
46
+
47
+
48
+	/**
49
+	 * private instance of the Event object
50
+	 *
51
+	 * @var EEM_Event
52
+	 */
53
+	protected static $_instance;
54
+
55
+
56
+
57
+
58
+	/**
59
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
60
+	 *
61
+	 * @param string $timezone
62
+	 * @throws \EE_Error
63
+	 */
64
+	protected function __construct($timezone = null)
65
+	{
66
+		EE_Registry::instance()->load_model('Registration');
67
+		$this->singular_item = esc_html__('Event', 'event_espresso');
68
+		$this->plural_item = esc_html__('Events', 'event_espresso');
69
+		// to remove Cancelled events from the frontend, copy the following filter to your functions.php file
70
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
71
+		// to remove Postponed events from the frontend, copy the following filter to your functions.php file
72
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
73
+		// to remove Sold Out events from the frontend, copy the following filter to your functions.php file
74
+		//  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
75
+		$this->_custom_stati = apply_filters(
76
+			'AFEE__EEM_Event__construct___custom_stati',
77
+			array(
78
+				EEM_Event::cancelled => array(
79
+					'label'  => esc_html__('Cancelled', 'event_espresso'),
80
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
81
+				),
82
+				EEM_Event::postponed => array(
83
+					'label'  => esc_html__('Postponed', 'event_espresso'),
84
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
85
+				),
86
+				EEM_Event::sold_out  => array(
87
+					'label'  => esc_html__('Sold Out', 'event_espresso'),
88
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
89
+				),
90
+			)
91
+		);
92
+		self::$_default_reg_status = empty(self::$_default_reg_status) ? EEM_Registration::status_id_pending_payment
93
+			: self::$_default_reg_status;
94
+		$this->_tables = array(
95
+			'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
96
+			'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
97
+		);
98
+		$this->_fields = array(
99
+			'Event_CPT'  => array(
100
+				'EVT_ID'         => new EE_Primary_Key_Int_Field(
101
+					'ID',
102
+					esc_html__('Post ID for Event', 'event_espresso')
103
+				),
104
+				'EVT_name'       => new EE_Plain_Text_Field(
105
+					'post_title',
106
+					esc_html__('Event Name', 'event_espresso'),
107
+					false,
108
+					''
109
+				),
110
+				'EVT_desc'       => new EE_Post_Content_Field(
111
+					'post_content',
112
+					esc_html__('Event Description', 'event_espresso'),
113
+					false,
114
+					''
115
+				),
116
+				'EVT_slug'       => new EE_Slug_Field(
117
+					'post_name',
118
+					esc_html__('Event Slug', 'event_espresso'),
119
+					false,
120
+					''
121
+				),
122
+				'EVT_created'    => new EE_Datetime_Field(
123
+					'post_date',
124
+					esc_html__('Date/Time Event Created', 'event_espresso'),
125
+					false,
126
+					EE_Datetime_Field::now
127
+				),
128
+				'EVT_short_desc' => new EE_Simple_HTML_Field(
129
+					'post_excerpt',
130
+					esc_html__('Event Short Description', 'event_espresso'),
131
+					false,
132
+					''
133
+				),
134
+				'EVT_modified'   => new EE_Datetime_Field(
135
+					'post_modified',
136
+					esc_html__('Date/Time Event Modified', 'event_espresso'),
137
+					false,
138
+					EE_Datetime_Field::now
139
+				),
140
+				'EVT_wp_user'    => new EE_WP_User_Field(
141
+					'post_author',
142
+					esc_html__('Event Creator ID', 'event_espresso'),
143
+					false
144
+				),
145
+				'parent'         => new EE_Integer_Field(
146
+					'post_parent',
147
+					esc_html__('Event Parent ID', 'event_espresso'),
148
+					false,
149
+					0
150
+				),
151
+				'EVT_order'      => new EE_Integer_Field(
152
+					'menu_order',
153
+					esc_html__('Event Menu Order', 'event_espresso'),
154
+					false,
155
+					1
156
+				),
157
+				'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
158
+				// EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
159
+				'status'         => new EE_WP_Post_Status_Field(
160
+					'post_status',
161
+					esc_html__('Event Status', 'event_espresso'),
162
+					false,
163
+					'draft',
164
+					$this->_custom_stati
165
+				),
166
+				'password' => new EE_Password_Field(
167
+					'post_password',
168
+					esc_html__('Password', 'event_espresso'),
169
+					false,
170
+					'',
171
+					array(
172
+						'EVT_desc',
173
+						'EVT_short_desc',
174
+						'EVT_display_desc',
175
+						'EVT_display_ticket_selector',
176
+						'EVT_visible_on',
177
+						'EVT_additional_limit',
178
+						'EVT_default_registration_status',
179
+						'EVT_member_only',
180
+						'EVT_phone',
181
+						'EVT_allow_overflow',
182
+						'EVT_timezone_string',
183
+						'EVT_external_URL',
184
+						'EVT_donations'
185
+					)
186
+				)
187
+			),
188
+			'Event_Meta' => array(
189
+				'EVTM_ID'                         => new EE_DB_Only_Float_Field(
190
+					'EVTM_ID',
191
+					esc_html__('Event Meta Row ID', 'event_espresso'),
192
+					false
193
+				),
194
+				'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
195
+					'EVT_ID',
196
+					esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
197
+					false
198
+				),
199
+				'EVT_display_desc'                => new EE_Boolean_Field(
200
+					'EVT_display_desc',
201
+					esc_html__('Display Description Flag', 'event_espresso'),
202
+					false,
203
+					true
204
+				),
205
+				'EVT_display_ticket_selector'     => new EE_Boolean_Field(
206
+					'EVT_display_ticket_selector',
207
+					esc_html__('Display Ticket Selector Flag', 'event_espresso'),
208
+					false,
209
+					true
210
+				),
211
+				'EVT_visible_on'                  => new EE_Datetime_Field(
212
+					'EVT_visible_on',
213
+					esc_html__('Event Visible Date', 'event_espresso'),
214
+					true,
215
+					EE_Datetime_Field::now
216
+				),
217
+				'EVT_additional_limit'            => new EE_Integer_Field(
218
+					'EVT_additional_limit',
219
+					esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
220
+					true,
221
+					self::$_default_additional_limit
222
+				),
223
+				'EVT_default_registration_status' => new EE_Enum_Text_Field(
224
+					'EVT_default_registration_status',
225
+					esc_html__('Default Registration Status on this Event', 'event_espresso'),
226
+					false,
227
+					EEM_Event::$_default_reg_status,
228
+					EEM_Registration::reg_status_array()
229
+				),
230
+				'EVT_member_only'                 => new EE_Boolean_Field(
231
+					'EVT_member_only',
232
+					esc_html__('Member-Only Event Flag', 'event_espresso'),
233
+					false,
234
+					false
235
+				),
236
+				'EVT_phone'                       => new EE_Plain_Text_Field(
237
+					'EVT_phone',
238
+					esc_html__('Event Phone Number', 'event_espresso'),
239
+					false,
240
+					''
241
+				),
242
+				'EVT_allow_overflow'              => new EE_Boolean_Field(
243
+					'EVT_allow_overflow',
244
+					esc_html__('Allow Overflow on Event', 'event_espresso'),
245
+					false,
246
+					false
247
+				),
248
+				'EVT_timezone_string'             => new EE_Plain_Text_Field(
249
+					'EVT_timezone_string',
250
+					esc_html__('Timezone (name) for Event times', 'event_espresso'),
251
+					false,
252
+					''
253
+				),
254
+				'EVT_external_URL'                => new EE_Plain_Text_Field(
255
+					'EVT_external_URL',
256
+					esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
257
+					true
258
+				),
259
+				'EVT_donations'                   => new EE_Boolean_Field(
260
+					'EVT_donations',
261
+					esc_html__('Accept Donations?', 'event_espresso'),
262
+					false,
263
+					false
264
+				),
265
+			),
266
+		);
267
+		$this->_model_relations = array(
268
+			'Registration'           => new EE_Has_Many_Relation(),
269
+			'Datetime'               => new EE_Has_Many_Relation(),
270
+			'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
271
+			'Event_Question_Group'   => new EE_Has_Many_Relation(),
272
+			'Venue'                  => new EE_HABTM_Relation('Event_Venue'),
273
+			'Term_Relationship'      => new EE_Has_Many_Relation(),
274
+			'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
275
+			'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
276
+			'Attendee'               => new EE_HABTM_Relation('Registration'),
277
+			'WP_User'                => new EE_Belongs_To_Relation(),
278
+		);
279
+		// this model is generally available for reading
280
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
281
+		$this->model_chain_to_password = '';
282
+		parent::__construct($timezone);
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * @param string $default_reg_status
289
+	 */
290
+	public static function set_default_reg_status($default_reg_status)
291
+	{
292
+		self::$_default_reg_status = $default_reg_status;
293
+		// if EEM_Event has already been instantiated,
294
+		// then we need to reset the `EVT_default_reg_status` field to use the new default.
295
+		if (self::$_instance instanceof EEM_Event) {
296
+			$default_reg_status = new EE_Enum_Text_Field(
297
+				'EVT_default_registration_status',
298
+				esc_html__('Default Registration Status on this Event', 'event_espresso'),
299
+				false,
300
+				$default_reg_status,
301
+				EEM_Registration::reg_status_array()
302
+			);
303
+			$default_reg_status->_construct_finalize(
304
+				'Event_Meta',
305
+				'EVT_default_registration_status',
306
+				'EEM_Event'
307
+			);
308
+			self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
309
+		}
310
+	}
311
+
312
+
313
+	/**
314
+	 * Used to override the default for the additional limit field.
315
+	 * @param $additional_limit
316
+	 */
317
+	public static function set_default_additional_limit($additional_limit)
318
+	{
319
+		self::$_default_additional_limit = (int) $additional_limit;
320
+		if (self::$_instance instanceof EEM_Event) {
321
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
322
+				'EVT_additional_limit',
323
+				esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
324
+				true,
325
+				self::$_default_additional_limit
326
+			);
327
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
328
+				'Event_Meta',
329
+				'EVT_additional_limit',
330
+				'EEM_Event'
331
+			);
332
+		}
333
+	}
334
+
335
+
336
+	/**
337
+	 * Return what is currently set as the default additional limit for the event.
338
+	 * @return int
339
+	 */
340
+	public static function get_default_additional_limit()
341
+	{
342
+		return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
343
+	}
344
+
345
+
346
+	/**
347
+	 * get_question_groups
348
+	 *
349
+	 * @return array
350
+	 * @throws \EE_Error
351
+	 */
352
+	public function get_all_question_groups()
353
+	{
354
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
355
+			array(
356
+				array('QSG_deleted' => false),
357
+				'order_by' => array('QSG_order' => 'ASC'),
358
+			)
359
+		);
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * get_question_groups
366
+	 *
367
+	 * @param int $EVT_ID
368
+	 * @return array|bool
369
+	 * @throws \EE_Error
370
+	 */
371
+	public function get_all_event_question_groups($EVT_ID = 0)
372
+	{
373
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
374
+			EE_Error::add_error(
375
+				esc_html__(
376
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
377
+					'event_espresso'
378
+				),
379
+				__FILE__,
380
+				__FUNCTION__,
381
+				__LINE__
382
+			);
383
+			return false;
384
+		}
385
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
386
+			array(
387
+				array('EVT_ID' => $EVT_ID),
388
+			)
389
+		);
390
+	}
391
+
392
+
393
+	/**
394
+	 * get_question_groups
395
+	 *
396
+	 * @param int $EVT_ID
397
+	 * @param boolean $for_primary_attendee
398
+	 * @return array|bool
399
+	 * @throws EE_Error
400
+	 * @throws InvalidArgumentException
401
+	 * @throws ReflectionException
402
+	 * @throws InvalidDataTypeException
403
+	 * @throws InvalidInterfaceException
404
+	 */
405
+	public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
406
+	{
407
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
408
+			EE_Error::add_error(
409
+				esc_html__(
410
+					// @codingStandardsIgnoreStart
411
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
412
+					// @codingStandardsIgnoreEnd
413
+					'event_espresso'
414
+				),
415
+				__FILE__,
416
+				__FUNCTION__,
417
+				__LINE__
418
+			);
419
+			return false;
420
+		}
421
+		$query_params = [
422
+			[
423
+				'EVT_ID' => $EVT_ID,
424
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true
425
+			]
426
+		];
427
+		if ($for_primary_attendee) {
428
+			$query_params[0]['EQG_primary'] = true;
429
+		} else {
430
+			$query_params[0]['EQG_additional'] = true;
431
+		}
432
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
433
+	}
434
+
435
+
436
+	/**
437
+	 * get_question_groups
438
+	 *
439
+	 * @param int $EVT_ID
440
+	 * @param EE_Registration $registration
441
+	 * @return array|bool
442
+	 * @throws EE_Error
443
+	 * @throws InvalidArgumentException
444
+	 * @throws InvalidDataTypeException
445
+	 * @throws InvalidInterfaceException
446
+	 * @throws ReflectionException
447
+	 */
448
+	public function get_question_groups_for_event($EVT_ID, EE_Registration $registration)
449
+	{
450
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
451
+			EE_Error::add_error(
452
+				esc_html__(
453
+					'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
454
+					'event_espresso'
455
+				),
456
+				__FILE__,
457
+				__FUNCTION__,
458
+				__LINE__
459
+			);
460
+			return false;
461
+		}
462
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
463
+			[
464
+				[
465
+					'Event_Question_Group.EVT_ID'      => $EVT_ID,
466
+					'Event_Question_Group.'
467
+						. EEM_Event_Question_Group::instance()->fieldNameForContext(
468
+							$registration->is_primary_registrant()
469
+						) => true
470
+				],
471
+				'order_by' => ['QSG_order' => 'ASC'],
472
+			]
473
+		);
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * get_question_target_db_column
480
+	 *
481
+	 * @param string $QSG_IDs csv list of $QSG IDs
482
+	 * @return array|bool
483
+	 * @throws \EE_Error
484
+	 */
485
+	public function get_questions_in_groups($QSG_IDs = '')
486
+	{
487
+		if (empty($QSG_IDs)) {
488
+			EE_Error::add_error(
489
+				esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
490
+				__FILE__,
491
+				__FUNCTION__,
492
+				__LINE__
493
+			);
494
+			return false;
495
+		}
496
+		return EE_Registry::instance()->load_model('Question')->get_all(
497
+			array(
498
+				array(
499
+					'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
500
+					'QST_deleted'           => false,
501
+					'QST_admin_only'        => is_admin(),
502
+				),
503
+				'order_by' => 'QST_order',
504
+			)
505
+		);
506
+	}
507
+
508
+
509
+
510
+	/**
511
+	 * get_options_for_question
512
+	 *
513
+	 * @param string $QST_IDs csv list of $QST IDs
514
+	 * @return array|bool
515
+	 * @throws \EE_Error
516
+	 */
517
+	public function get_options_for_question($QST_IDs)
518
+	{
519
+		if (empty($QST_IDs)) {
520
+			EE_Error::add_error(
521
+				esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
522
+				__FILE__,
523
+				__FUNCTION__,
524
+				__LINE__
525
+			);
526
+			return false;
527
+		}
528
+		return EE_Registry::instance()->load_model('Question_Option')->get_all(
529
+			array(
530
+				array(
531
+					'Question.QST_ID' => array('IN', $QST_IDs),
532
+					'QSO_deleted'     => false,
533
+				),
534
+				'order_by' => 'QSO_ID',
535
+			)
536
+		);
537
+	}
538
+
539
+
540
+
541
+
542
+
543
+
544
+
545
+	/**
546
+	 * Gets all events that are published
547
+	 * and have event start time earlier than now and an event end time later than now
548
+	 *
549
+	 * @param  array $query_params An array of query params to further filter on
550
+	 *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
551
+	 * @param bool   $count        whether to return the count or not (default FALSE)
552
+	 * @return EE_Event[]|int
553
+	 * @throws \EE_Error
554
+	 */
555
+	public function get_active_events($query_params, $count = false)
556
+	{
557
+		if (array_key_exists(0, $query_params)) {
558
+			$where_params = $query_params[0];
559
+			unset($query_params[0]);
560
+		} else {
561
+			$where_params = array();
562
+		}
563
+		// if we have count make sure we don't include group by
564
+		if ($count && isset($query_params['group_by'])) {
565
+			unset($query_params['group_by']);
566
+		}
567
+		// let's add specific query_params for active_events
568
+		// keep in mind this will override any sent status in the query AND any date queries.
569
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
570
+		// if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
571
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
572
+			$where_params['Datetime.DTT_EVT_start******'] = array(
573
+				'<',
574
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
575
+			);
576
+		} else {
577
+			$where_params['Datetime.DTT_EVT_start'] = array(
578
+				'<',
579
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
580
+			);
581
+		}
582
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
583
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
584
+				'>',
585
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
586
+			);
587
+		} else {
588
+			$where_params['Datetime.DTT_EVT_end'] = array(
589
+				'>',
590
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
591
+			);
592
+		}
593
+		$query_params[0] = $where_params;
594
+		// don't use $query_params with count()
595
+		// because we don't want to include additional query clauses like "GROUP BY"
596
+		return $count
597
+			? $this->count(array($where_params), 'EVT_ID', true)
598
+			: $this->get_all($query_params);
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * get all events that are published and have an event start time later than now
605
+	 *
606
+	 * @param  array $query_params An array of query params to further filter on
607
+	 *                             (Note that status and DTT_EVT_start will be overridden)
608
+	 * @param bool   $count        whether to return the count or not (default FALSE)
609
+	 * @return EE_Event[]|int
610
+	 * @throws \EE_Error
611
+	 */
612
+	public function get_upcoming_events($query_params, $count = false)
613
+	{
614
+		if (array_key_exists(0, $query_params)) {
615
+			$where_params = $query_params[0];
616
+			unset($query_params[0]);
617
+		} else {
618
+			$where_params = array();
619
+		}
620
+		// if we have count make sure we don't include group by
621
+		if ($count && isset($query_params['group_by'])) {
622
+			unset($query_params['group_by']);
623
+		}
624
+		// let's add specific query_params for active_events
625
+		// keep in mind this will override any sent status in the query AND any date queries.
626
+		// we need to pull events with a status of publish and sold_out
627
+		$event_status = array('publish', EEM_Event::sold_out);
628
+		// check if the user can read private events and if so add the 'private status to the were params'
629
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
630
+			$event_status[] = 'private';
631
+		}
632
+		$where_params['status'] = array('IN', $event_status);
633
+		// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
634
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
635
+			$where_params['Datetime.DTT_EVT_start*****'] = array(
636
+				'>',
637
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
638
+			);
639
+		} else {
640
+			$where_params['Datetime.DTT_EVT_start'] = array(
641
+				'>',
642
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
643
+			);
644
+		}
645
+		$query_params[0] = $where_params;
646
+		// don't use $query_params with count()
647
+		// because we don't want to include additional query clauses like "GROUP BY"
648
+		return $count
649
+			? $this->count(array($where_params), 'EVT_ID', true)
650
+			: $this->get_all($query_params);
651
+	}
652
+
653
+
654
+
655
+	/**
656
+	 * Gets all events that are published
657
+	 * and have an event end time later than now
658
+	 *
659
+	 * @param  array $query_params An array of query params to further filter on
660
+	 *                             (note that status and DTT_EVT_end will be overridden)
661
+	 * @param bool   $count        whether to return the count or not (default FALSE)
662
+	 * @return EE_Event[]|int
663
+	 * @throws \EE_Error
664
+	 */
665
+	public function get_active_and_upcoming_events($query_params, $count = false)
666
+	{
667
+		if (array_key_exists(0, $query_params)) {
668
+			$where_params = $query_params[0];
669
+			unset($query_params[0]);
670
+		} else {
671
+			$where_params = array();
672
+		}
673
+		// if we have count make sure we don't include group by
674
+		if ($count && isset($query_params['group_by'])) {
675
+			unset($query_params['group_by']);
676
+		}
677
+		// let's add specific query_params for active_events
678
+		// keep in mind this will override any sent status in the query AND any date queries.
679
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
680
+		// add where params for DTT_EVT_end
681
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
682
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
683
+				'>',
684
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
685
+			);
686
+		} else {
687
+			$where_params['Datetime.DTT_EVT_end'] = array(
688
+				'>',
689
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
690
+			);
691
+		}
692
+		$query_params[0] = $where_params;
693
+		// don't use $query_params with count()
694
+		// because we don't want to include additional query clauses like "GROUP BY"
695
+		return $count
696
+			? $this->count(array($where_params), 'EVT_ID', true)
697
+			: $this->get_all($query_params);
698
+	}
699
+
700
+
701
+
702
+	/**
703
+	 * This only returns events that are expired.
704
+	 * They may still be published but all their datetimes have expired.
705
+	 *
706
+	 * @param  array $query_params An array of query params to further filter on
707
+	 *                             (note that status and DTT_EVT_end will be overridden)
708
+	 * @param bool   $count        whether to return the count or not (default FALSE)
709
+	 * @return EE_Event[]|int
710
+	 * @throws \EE_Error
711
+	 */
712
+	public function get_expired_events($query_params, $count = false)
713
+	{
714
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
715
+		// if we have count make sure we don't include group by
716
+		if ($count && isset($query_params['group_by'])) {
717
+			unset($query_params['group_by']);
718
+		}
719
+		// let's add specific query_params for active_events
720
+		// keep in mind this will override any sent status in the query AND any date queries.
721
+		if (isset($where_params['status'])) {
722
+			unset($where_params['status']);
723
+		}
724
+		$exclude_query = $query_params;
725
+		if (isset($exclude_query[0])) {
726
+			unset($exclude_query[0]);
727
+		}
728
+		$exclude_query[0] = array(
729
+			'Datetime.DTT_EVT_end' => array(
730
+				'>',
731
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
732
+			),
733
+		);
734
+		// first get all events that have datetimes where its not expired.
735
+		$event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
736
+		$event_ids = array_keys($event_ids);
737
+		// if we have any additional query_params, let's add them to the 'AND' condition
738
+		$and_condition = array(
739
+			'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
740
+			'EVT_ID'               => array('NOT IN', $event_ids),
741
+		);
742
+		if (isset($where_params['OR'])) {
743
+			$and_condition['OR'] = $where_params['OR'];
744
+			unset($where_params['OR']);
745
+		}
746
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
747
+			$and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
748
+			unset($where_params['Datetime.DTT_EVT_end']);
749
+		}
750
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
751
+			$and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
752
+			unset($where_params['Datetime.DTT_EVT_start']);
753
+		}
754
+		// merge remaining $where params with the and conditions.
755
+		$where_params['AND'] = array_merge($and_condition, $where_params);
756
+		$query_params[0] = $where_params;
757
+		// don't use $query_params with count()
758
+		// because we don't want to include additional query clauses like "GROUP BY"
759
+		return $count
760
+			? $this->count(array($where_params), 'EVT_ID', true)
761
+			: $this->get_all($query_params);
762
+	}
763
+
764
+
765
+
766
+	/**
767
+	 * This basically just returns the events that do not have the publish status.
768
+	 *
769
+	 * @param  array   $query_params An array of query params to further filter on
770
+	 *                               (note that status will be overwritten)
771
+	 * @param  boolean $count        whether to return the count or not (default FALSE)
772
+	 * @return EE_Event[]|int
773
+	 * @throws \EE_Error
774
+	 */
775
+	public function get_inactive_events($query_params, $count = false)
776
+	{
777
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
778
+		// let's add in specific query_params for inactive events.
779
+		if (isset($where_params['status'])) {
780
+			unset($where_params['status']);
781
+		}
782
+		// if we have count make sure we don't include group by
783
+		if ($count && isset($query_params['group_by'])) {
784
+			unset($query_params['group_by']);
785
+		}
786
+		// if we have any additional query_params, let's add them to the 'AND' condition
787
+		$where_params['AND']['status'] = array('!=', 'publish');
788
+		if (isset($where_params['OR'])) {
789
+			$where_params['AND']['OR'] = $where_params['OR'];
790
+			unset($where_params['OR']);
791
+		}
792
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
793
+			$where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
794
+			unset($where_params['Datetime.DTT_EVT_end']);
795
+		}
796
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
797
+			$where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
798
+			unset($where_params['Datetime.DTT_EVT_start']);
799
+		}
800
+		$query_params[0] = $where_params;
801
+		// don't use $query_params with count()
802
+		// because we don't want to include additional query clauses like "GROUP BY"
803
+		return $count
804
+			? $this->count(array($where_params), 'EVT_ID', true)
805
+			: $this->get_all($query_params);
806
+	}
807
+
808
+
809
+
810
+	/**
811
+	 * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
812
+	 * because we don't want to override any existing global default prices but instead insert NEW prices that get
813
+	 * attached to the event. See parent for param descriptions
814
+	 *
815
+	 * @param        $id_or_obj
816
+	 * @param        $other_model_id_or_obj
817
+	 * @param string $relationName
818
+	 * @param array  $where_query
819
+	 * @return EE_Base_Class
820
+	 * @throws EE_Error
821
+	 */
822
+	public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
823
+	{
824
+		if ($relationName === 'Price') {
825
+			// let's get the PRC object for the given ID to make sure that we aren't dealing with a default
826
+			$prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
827
+			// if EVT_ID = 0, then this is a default
828
+			if ((int) $prc_chk->get('EVT_ID') === 0) {
829
+				// let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
830
+				$prc_chk->set('PRC_ID', 0);
831
+			}
832
+			// run parent
833
+			return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
834
+		}
835
+		// otherwise carry on as normal
836
+		return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
837
+	}
838
+
839
+
840
+
841
+	/******************** DEPRECATED METHODS ********************/
842
+
843
+
844
+
845
+	/**
846
+	 * _get_question_target_db_column
847
+	 *
848
+	 * @deprecated as of 4.8.32.rc.001. Instead consider using
849
+	 *             EE_Registration_Custom_Questions_Form located in
850
+	 *             admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
851
+	 * @access     public
852
+	 * @param    EE_Registration $registration (so existing answers for registration are included)
853
+	 * @param    int             $EVT_ID       so all question groups are included for event (not just answers from
854
+	 *                                         registration).
855
+	 * @throws EE_Error
856
+	 * @return    array
857
+	 */
858
+	public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
859
+	{
860
+		if (empty($EVT_ID)) {
861
+			throw new EE_Error(esc_html__(
862
+				'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
863
+				'event_espresso'
864
+			));
865
+		}
866
+		$questions = array();
867
+		// get all question groups for event
868
+		$qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
869
+		if (! empty($qgs)) {
870
+			foreach ($qgs as $qg) {
871
+				$qsts = $qg->questions();
872
+				$questions[ $qg->ID() ] = $qg->model_field_array();
873
+				$questions[ $qg->ID() ]['QSG_questions'] = array();
874
+				foreach ($qsts as $qst) {
875
+					if ($qst->is_system_question()) {
876
+						continue;
877
+					}
878
+					$answer = EEM_Answer::instance()->get_one(array(
879
+						array(
880
+							'QST_ID' => $qst->ID(),
881
+							'REG_ID' => $registration->ID(),
882
+						),
883
+					));
884
+					$answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
885
+					$qst_name = $qstn_id = $qst->ID();
886
+					$ans_id = $answer->ID();
887
+					$qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
888
+					$input_name = '';
889
+					$input_id = sanitize_key($qst->display_text());
890
+					$input_class = '';
891
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ] = $qst->model_field_array();
892
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name'] = 'qstn'
893
+																						   . $input_name
894
+																						   . $qst_name;
895
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id'] = $input_id . '-' . $qstn_id;
896
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
897
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'] = array();
898
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj'] = $qst;
899
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj'] = $answer;
900
+					// leave responses as-is, don't convert stuff into html entities please!
901
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
902
+					if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
903
+						$QSOs = $qst->options(true, $answer->value());
904
+						if (is_array($QSOs)) {
905
+							foreach ($QSOs as $QSO_ID => $QSO) {
906
+								$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] = $QSO->model_field_array();
907
+							}
908
+						}
909
+					}
910
+				}
911
+			}
912
+		}
913
+		return $questions;
914
+	}
915
+
916
+
917
+	/**
918
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
919
+	 *                             or an stdClass where each property is the name of a column,
920
+	 * @return EE_Base_Class
921
+	 * @throws \EE_Error
922
+	 */
923
+	public function instantiate_class_from_array_or_object($cols_n_values)
924
+	{
925
+		$classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
926
+		if ($classInstance instanceof EE_Event) {
927
+			// events have their timezone defined in the DB, so use it immediately
928
+			$this->set_timezone($classInstance->get_timezone());
929
+		}
930
+		return $classInstance;
931
+	}
932
+
933
+
934
+	/**
935
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
936
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
937
+	 * as archived, not actually deleted
938
+	 *
939
+	 * @param array   $query_params
940
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
941
+	 *                                that blocks it (ie, there' sno other data that depends on this data);
942
+	 *                                if false, deletes regardless of other objects which may depend on it.
943
+	 *                                Its generally advisable to always leave this as TRUE,
944
+	 *                                otherwise you could easily corrupt your DB
945
+	 * @return int                    number of rows deleted
946
+	 * @throws EE_Error
947
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
948
+	 */
949
+	public function delete_permanently($query_params, $allow_blocking = true)
950
+	{
951
+		$deleted = parent::delete_permanently($query_params, $allow_blocking);
952
+		if ($deleted) {
953
+			// get list of events with no prices
954
+			$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', []);
955
+			$where = isset($query_params[0]) ? $query_params[0] : [];
956
+			$where_event = isset($where['EVT_ID']) ? $where['EVT_ID'] : ['', ''];
957
+			$where_event_ids = isset($where_event[1]) ? $where_event[1] : '';
958
+			$event_ids = is_string($where_event_ids)
959
+				? explode(',', $where_event_ids)
960
+				: (array) $where_event_ids;
961
+			array_walk($event_ids, 'trim');
962
+			$event_ids = array_filter($event_ids);
963
+			// remove events from list of events with no prices
964
+			$espresso_no_ticket_prices = array_diff($espresso_no_ticket_prices, $event_ids);
965
+			update_option('ee_no_ticket_prices', $espresso_no_ticket_prices);
966
+		}
967
+		return $deleted;
968
+	}
969 969
 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/ExecuteBatchDeletion.php 2 patches
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -25,172 +25,172 @@
 block discarded – undo
25 25
  */
26 26
 class ExecuteBatchDeletion extends JobHandler
27 27
 {
28
-    /**
29
-     * @var NodeGroupDao
30
-     */
31
-    protected $model_obj_node_group_persister;
28
+	/**
29
+	 * @var NodeGroupDao
30
+	 */
31
+	protected $model_obj_node_group_persister;
32 32
 
33 33
 
34
-    public function __construct(NodeGroupDao $model_obj_node_group_persister)
35
-    {
36
-        $this->model_obj_node_group_persister = $model_obj_node_group_persister;
37
-    }
34
+	public function __construct(NodeGroupDao $model_obj_node_group_persister)
35
+	{
36
+		$this->model_obj_node_group_persister = $model_obj_node_group_persister;
37
+	}
38 38
 
39 39
 
40
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
40
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
41 41
 
42 42
 
43
-    /**
44
-     *
45
-     * @param JobParameters $job_parameters
46
-     * @return JobStepResponse
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public function create_job(JobParameters $job_parameters)
51
-    {
52
-        $deletion_job_code = $job_parameters->request_datum('deletion_job_code', null);
53
-        $roots             = $this->model_obj_node_group_persister->getModelObjNodesInGroup($deletion_job_code);
54
-        if ($roots === null) {
55
-            throw new UnexpectedEntityException(
56
-                $roots,
57
-                'array',
58
-                esc_html__(
59
-                    'The job seems to be stale. Please press the back button in your browser twice.',
60
-                    'event_espresso'
61
-                )
62
-            );
63
-        }
64
-        $models_and_ids_to_delete = [];
65
-        foreach ($roots as $root) {
66
-            if (! $root instanceof ModelObjNode) {
67
-                throw new UnexpectedEntityException($root, 'ModelObjNode');
68
-            }
69
-            $models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
70
-        }
71
-        $job_parameters->set_extra_data(
72
-            [
73
-                'models_and_ids_to_delete' => $models_and_ids_to_delete,
74
-            ]
75
-        );
76
-        // Find the job's actual size.
77
-        $job_size = 0;
78
-        foreach ($models_and_ids_to_delete as $ids) {
79
-            $job_size += count($ids);
80
-        }
81
-        $job_parameters->set_job_size($job_size);
82
-        return new JobStepResponse(
83
-            $job_parameters,
84
-            esc_html__('Beginning to delete items...', 'event_espresso')
85
-        );
86
-    }
43
+	/**
44
+	 *
45
+	 * @param JobParameters $job_parameters
46
+	 * @return JobStepResponse
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public function create_job(JobParameters $job_parameters)
51
+	{
52
+		$deletion_job_code = $job_parameters->request_datum('deletion_job_code', null);
53
+		$roots             = $this->model_obj_node_group_persister->getModelObjNodesInGroup($deletion_job_code);
54
+		if ($roots === null) {
55
+			throw new UnexpectedEntityException(
56
+				$roots,
57
+				'array',
58
+				esc_html__(
59
+					'The job seems to be stale. Please press the back button in your browser twice.',
60
+					'event_espresso'
61
+				)
62
+			);
63
+		}
64
+		$models_and_ids_to_delete = [];
65
+		foreach ($roots as $root) {
66
+			if (! $root instanceof ModelObjNode) {
67
+				throw new UnexpectedEntityException($root, 'ModelObjNode');
68
+			}
69
+			$models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
70
+		}
71
+		$job_parameters->set_extra_data(
72
+			[
73
+				'models_and_ids_to_delete' => $models_and_ids_to_delete,
74
+			]
75
+		);
76
+		// Find the job's actual size.
77
+		$job_size = 0;
78
+		foreach ($models_and_ids_to_delete as $ids) {
79
+			$job_size += count($ids);
80
+		}
81
+		$job_parameters->set_job_size($job_size);
82
+		return new JobStepResponse(
83
+			$job_parameters,
84
+			esc_html__('Beginning to delete items...', 'event_espresso')
85
+		);
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * Performs another step of the job
91
-     *
92
-     * @param JobParameters $job_parameters
93
-     * @param int           $batch_size
94
-     * @return JobStepResponse
95
-     * @throws EE_Error
96
-     * @throws ReflectionException
97
-     */
98
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
-    {
100
-        // We already have the items IDs. So deleting is really fast. Let's speed it up.
101
-        $batch_size               *= 10;
102
-        $units_processed          = 0;
103
-        $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104
-        // Build a new list of everything leftover after this request's of deletions.
105
-        $models_and_ids_remaining = [];
106
-        foreach ($models_and_ids_to_delete as $model_name => $ids_to_delete) {
107
-            // don't delete logs
108
-            if ($model_name === 'Change_Log') {
109
-                continue;
110
-            }
111
-            if ($units_processed < $batch_size) {
112
-                /** @var EEM_Base $model */
113
-                $model                    = EE_Registry::instance()->load_model($model_name);
114
-                $ids_to_delete_this_query = array_slice($ids_to_delete, 0, $batch_size - $units_processed, true);
115
-                if ($model->has_primary_key_field()) {
116
-                    $where_conditions = [
117
-                        $model->primary_key_name() => [
118
-                            'IN',
119
-                            $ids_to_delete_this_query,
120
-                        ],
121
-                    ];
122
-                } else {
123
-                    $where_conditions = [
124
-                        'OR' => [],
125
-                    ];
126
-                    foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127
-                        $keys_n_values                                                =
128
-                            $model->parse_index_primary_key_string($index_primary_key_string);
129
-                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
130
-                    }
131
-                }
132
-                // Deleting time!
133
-                // The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134
-                // two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
-                $model->delete_permanently([ $where_conditions ], false);
136
-                $units_processed += count($ids_to_delete_this_query);
137
-                $remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138
-                // If there's any more from this model, we'll do them next time.
139
-                if (count($remaining_ids) > 0) {
140
-                    $models_and_ids_remaining[ $model_name ] = $remaining_ids;
141
-                }
142
-            } else {
143
-                $models_and_ids_remaining[ $model_name ] = $ids_to_delete;
144
-            }
145
-        }
146
-        $job_parameters->mark_processed($units_processed);
147
-        // All done deleting for this request. Is there anything to do next time?
148
-        if (empty($models_and_ids_remaining)) {
149
-            $job_parameters->set_status(JobParameters::status_complete);
150
-            return new JobStepResponse(
151
-                $job_parameters,
152
-                esc_html__('Deletion complete.', 'event_espresso')
153
-            );
154
-        }
155
-        $job_parameters->add_extra_data('models_and_ids_to_delete', $models_and_ids_remaining);
156
-        return new JobStepResponse(
157
-            $job_parameters,
158
-            sprintf(
159
-                esc_html__('Deleted %d items.', 'event_espresso'),
160
-                $units_processed
161
-            )
162
-        );
163
-    }
89
+	/**
90
+	 * Performs another step of the job
91
+	 *
92
+	 * @param JobParameters $job_parameters
93
+	 * @param int           $batch_size
94
+	 * @return JobStepResponse
95
+	 * @throws EE_Error
96
+	 * @throws ReflectionException
97
+	 */
98
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99
+	{
100
+		// We already have the items IDs. So deleting is really fast. Let's speed it up.
101
+		$batch_size               *= 10;
102
+		$units_processed          = 0;
103
+		$models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104
+		// Build a new list of everything leftover after this request's of deletions.
105
+		$models_and_ids_remaining = [];
106
+		foreach ($models_and_ids_to_delete as $model_name => $ids_to_delete) {
107
+			// don't delete logs
108
+			if ($model_name === 'Change_Log') {
109
+				continue;
110
+			}
111
+			if ($units_processed < $batch_size) {
112
+				/** @var EEM_Base $model */
113
+				$model                    = EE_Registry::instance()->load_model($model_name);
114
+				$ids_to_delete_this_query = array_slice($ids_to_delete, 0, $batch_size - $units_processed, true);
115
+				if ($model->has_primary_key_field()) {
116
+					$where_conditions = [
117
+						$model->primary_key_name() => [
118
+							'IN',
119
+							$ids_to_delete_this_query,
120
+						],
121
+					];
122
+				} else {
123
+					$where_conditions = [
124
+						'OR' => [],
125
+					];
126
+					foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127
+						$keys_n_values                                                =
128
+							$model->parse_index_primary_key_string($index_primary_key_string);
129
+						$where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
130
+					}
131
+				}
132
+				// Deleting time!
133
+				// The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134
+				// two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
+				$model->delete_permanently([ $where_conditions ], false);
136
+				$units_processed += count($ids_to_delete_this_query);
137
+				$remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138
+				// If there's any more from this model, we'll do them next time.
139
+				if (count($remaining_ids) > 0) {
140
+					$models_and_ids_remaining[ $model_name ] = $remaining_ids;
141
+				}
142
+			} else {
143
+				$models_and_ids_remaining[ $model_name ] = $ids_to_delete;
144
+			}
145
+		}
146
+		$job_parameters->mark_processed($units_processed);
147
+		// All done deleting for this request. Is there anything to do next time?
148
+		if (empty($models_and_ids_remaining)) {
149
+			$job_parameters->set_status(JobParameters::status_complete);
150
+			return new JobStepResponse(
151
+				$job_parameters,
152
+				esc_html__('Deletion complete.', 'event_espresso')
153
+			);
154
+		}
155
+		$job_parameters->add_extra_data('models_and_ids_to_delete', $models_and_ids_remaining);
156
+		return new JobStepResponse(
157
+			$job_parameters,
158
+			sprintf(
159
+				esc_html__('Deleted %d items.', 'event_espresso'),
160
+				$units_processed
161
+			)
162
+		);
163
+	}
164 164
 
165 165
 
166
-    /**
167
-     * Performs any clean-up logic when we know the job is completed
168
-     *
169
-     * @param JobParameters $job_parameters
170
-     * @return JobStepResponse
171
-     */
172
-    public function cleanup_job(JobParameters $job_parameters)
173
-    {
174
-        $this->model_obj_node_group_persister->deleteModelObjNodesInGroup(
175
-            $job_parameters->request_datum('deletion_job_code')
176
-        );
177
-        // For backwards compatibility with how we used to delete events, make sure we still trigger the old action.
178
-        $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
179
-        foreach ($models_and_ids_to_delete['Event'] as $event_id) {
180
-            // TrashLogger hooks into the following to create a log entry
181
-            // so we know when and who permanently deleted this event.
182
-            do_action(
183
-                'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
184
-                $event_id,
185
-                'Event',
186
-                $job_parameters
187
-            );
188
-        }
189
-        return new JobStepResponse(
190
-            $job_parameters,
191
-            esc_html__('All done', 'event_espresso')
192
-        );
193
-    }
166
+	/**
167
+	 * Performs any clean-up logic when we know the job is completed
168
+	 *
169
+	 * @param JobParameters $job_parameters
170
+	 * @return JobStepResponse
171
+	 */
172
+	public function cleanup_job(JobParameters $job_parameters)
173
+	{
174
+		$this->model_obj_node_group_persister->deleteModelObjNodesInGroup(
175
+			$job_parameters->request_datum('deletion_job_code')
176
+		);
177
+		// For backwards compatibility with how we used to delete events, make sure we still trigger the old action.
178
+		$models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
179
+		foreach ($models_and_ids_to_delete['Event'] as $event_id) {
180
+			// TrashLogger hooks into the following to create a log entry
181
+			// so we know when and who permanently deleted this event.
182
+			do_action(
183
+				'AHEE__Events_Admin_Page___permanently_delete_event__after_event_deleted',
184
+				$event_id,
185
+				'Event',
186
+				$job_parameters
187
+			);
188
+		}
189
+		return new JobStepResponse(
190
+			$job_parameters,
191
+			esc_html__('All done', 'event_espresso')
192
+		);
193
+	}
194 194
 }
195 195
 // End of file EventDeletion.php
196 196
 // Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
         }
64 64
         $models_and_ids_to_delete = [];
65 65
         foreach ($roots as $root) {
66
-            if (! $root instanceof ModelObjNode) {
66
+            if ( ! $root instanceof ModelObjNode) {
67 67
                 throw new UnexpectedEntityException($root, 'ModelObjNode');
68 68
             }
69 69
             $models_and_ids_to_delete = array_replace_recursive($models_and_ids_to_delete, $root->getIds());
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
     public function continue_job(JobParameters $job_parameters, $batch_size = 50)
99 99
     {
100 100
         // We already have the items IDs. So deleting is really fast. Let's speed it up.
101
-        $batch_size               *= 10;
101
+        $batch_size *= 10;
102 102
         $units_processed          = 0;
103 103
         $models_and_ids_to_delete = $job_parameters->extra_datum('models_and_ids_to_delete', []);
104 104
         // Build a new list of everything leftover after this request's of deletions.
@@ -126,21 +126,21 @@  discard block
 block discarded – undo
126 126
                     foreach ($ids_to_delete_this_query as $index_primary_key_string) {
127 127
                         $keys_n_values                                                =
128 128
                             $model->parse_index_primary_key_string($index_primary_key_string);
129
-                        $where_conditions['OR'][ 'AND*' . $index_primary_key_string ] = $keys_n_values;
129
+                        $where_conditions['OR']['AND*'.$index_primary_key_string] = $keys_n_values;
130 130
                     }
131 131
                 }
132 132
                 // Deleting time!
133 133
                 // The model's deletion method reports every ROW deleted, and in the case of CPT models that will be
134 134
                 // two rows deleted for event CPT item. So don't rely on it for the count of items deleted.
135
-                $model->delete_permanently([ $where_conditions ], false);
135
+                $model->delete_permanently([$where_conditions], false);
136 136
                 $units_processed += count($ids_to_delete_this_query);
137
-                $remaining_ids   = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
137
+                $remaining_ids = array_diff_key($ids_to_delete, $ids_to_delete_this_query);
138 138
                 // If there's any more from this model, we'll do them next time.
139 139
                 if (count($remaining_ids) > 0) {
140
-                    $models_and_ids_remaining[ $model_name ] = $remaining_ids;
140
+                    $models_and_ids_remaining[$model_name] = $remaining_ids;
141 141
                 }
142 142
             } else {
143
-                $models_and_ids_remaining[ $model_name ] = $ids_to_delete;
143
+                $models_and_ids_remaining[$model_name] = $ids_to_delete;
144 144
             }
145 145
         }
146 146
         $job_parameters->mark_processed($units_processed);
Please login to merge, or discard this patch.