Completed
Branch FET/reg-form-builder/main (a2f871)
by
unknown
15:30 queued 13:14
created
core/services/form/meta/inputs/Select.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -5,59 +5,59 @@
 block discarded – undo
5 5
 class Select
6 6
 {
7 7
 
8
-    /**
9
-     * indicates that the input is an HTML dropdown (select input) that accepts only one value
10
-     */
11
-    public const TYPE_SELECT = 'select';
12
-
13
-    /**
14
-     * indicates that the input is an HTML dropdown (select input) that accepts multiple values
15
-     */
16
-    public const TYPE_SELECT_MULTI = 'select-multi';
17
-
18
-    // CUSTOM EE SELECT TYPES
19
-
20
-    /**
21
-     * indicates that input is an HTML dropdown (select input)
22
-     * populated with names of countries that are enabled for the site
23
-     */
24
-    public const TYPE_SELECT_COUNTRY = 'select-country';
25
-
26
-    /**
27
-     * indicates that the input is an HTML dropdown (select input)
28
-     * populated with names of states for the countries that are enabled for the site
29
-     */
30
-    public const TYPE_SELECT_STATE = 'select-state';
31
-
32
-
33
-    /**
34
-     * @var array
35
-     */
36
-    private $valid_type_options;
37
-
38
-
39
-    public function __construct()
40
-    {
41
-        $this->valid_type_options = apply_filters(
42
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Select__valid_type_options',
43
-            [
44
-                Select::TYPE_SELECT         => esc_html__('Dropdown', 'event_espresso'),
45
-                Select::TYPE_SELECT_MULTI   => esc_html__('Multi-Select Dropdown', 'event_espresso'),
46
-                Select::TYPE_SELECT_COUNTRY => esc_html__('Country Selector', 'event_espresso'),
47
-                Select::TYPE_SELECT_STATE   => esc_html__('State Selector', 'event_espresso'),
48
-            ]
49
-        );
50
-    }
51
-
52
-
53
-    /**
54
-     * @param bool $constants_only
55
-     * @return array
56
-     */
57
-    public function validTypeOptions(bool $constants_only = false): array
58
-    {
59
-        return $constants_only
60
-            ? array_keys($this->valid_type_options)
61
-            : $this->valid_type_options;
62
-    }
8
+	/**
9
+	 * indicates that the input is an HTML dropdown (select input) that accepts only one value
10
+	 */
11
+	public const TYPE_SELECT = 'select';
12
+
13
+	/**
14
+	 * indicates that the input is an HTML dropdown (select input) that accepts multiple values
15
+	 */
16
+	public const TYPE_SELECT_MULTI = 'select-multi';
17
+
18
+	// CUSTOM EE SELECT TYPES
19
+
20
+	/**
21
+	 * indicates that input is an HTML dropdown (select input)
22
+	 * populated with names of countries that are enabled for the site
23
+	 */
24
+	public const TYPE_SELECT_COUNTRY = 'select-country';
25
+
26
+	/**
27
+	 * indicates that the input is an HTML dropdown (select input)
28
+	 * populated with names of states for the countries that are enabled for the site
29
+	 */
30
+	public const TYPE_SELECT_STATE = 'select-state';
31
+
32
+
33
+	/**
34
+	 * @var array
35
+	 */
36
+	private $valid_type_options;
37
+
38
+
39
+	public function __construct()
40
+	{
41
+		$this->valid_type_options = apply_filters(
42
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Select__valid_type_options',
43
+			[
44
+				Select::TYPE_SELECT         => esc_html__('Dropdown', 'event_espresso'),
45
+				Select::TYPE_SELECT_MULTI   => esc_html__('Multi-Select Dropdown', 'event_espresso'),
46
+				Select::TYPE_SELECT_COUNTRY => esc_html__('Country Selector', 'event_espresso'),
47
+				Select::TYPE_SELECT_STATE   => esc_html__('State Selector', 'event_espresso'),
48
+			]
49
+		);
50
+	}
51
+
52
+
53
+	/**
54
+	 * @param bool $constants_only
55
+	 * @return array
56
+	 */
57
+	public function validTypeOptions(bool $constants_only = false): array
58
+	{
59
+		return $constants_only
60
+			? array_keys($this->valid_type_options)
61
+			: $this->valid_type_options;
62
+	}
63 63
 }
Please login to merge, or discard this patch.
core/services/form/meta/inputs/Phone.php 2 patches
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -5,109 +5,109 @@
 block discarded – undo
5 5
 class Phone
6 6
 {
7 7
 
8
-    /**
9
-     * indicates that the HTML input type is 'tel'
10
-     */
11
-    public const INPUT_TYPE = 'tel';
8
+	/**
9
+	 * indicates that the HTML input type is 'tel'
10
+	 */
11
+	public const INPUT_TYPE = 'tel';
12 12
 
13
-    /**
14
-     * indicates that the 'tel' input regex pattern is for a US formatted phone number, examples:
15
-     *      ##########
16
-     *      ###-###-####
17
-     *      ### ### ####
18
-     *      (###)-###-####
19
-     *      (###) ###-####
20
-     *
21
-     * captures the intl code to the first group (+1) and the rest of the number to group 2
22
-     *      +1 (###) ###-####
23
-     */
24
-    public const PATTERN_US = '(\+?\d{1,3})?[\ \-]?(\(?\d{3}\)?[\ \-]?\d{3}[\ \-]?\d{4})';
13
+	/**
14
+	 * indicates that the 'tel' input regex pattern is for a US formatted phone number, examples:
15
+	 *      ##########
16
+	 *      ###-###-####
17
+	 *      ### ### ####
18
+	 *      (###)-###-####
19
+	 *      (###) ###-####
20
+	 *
21
+	 * captures the intl code to the first group (+1) and the rest of the number to group 2
22
+	 *      +1 (###) ###-####
23
+	 */
24
+	public const PATTERN_US = '(\+?\d{1,3})?[\ \-]?(\(?\d{3}\)?[\ \-]?\d{3}[\ \-]?\d{4})';
25 25
 
26
-    /**
27
-     * indicates that the 'tel' input regex pattern is for a UK formatted phone number, examples:
28
-     *      (###) #### ####
29
-     *      (####) ### ####
30
-     *      (#####) ## ####
31
-     *
32
-     * captures the intl code to the first group (+44) and the rest of the number to group 2
33
-     *      +44 (###) #### ####
34
-     */
35
-    public const PATTERN_UK = '(\+?44)?[\ ]?(\(?(?:(?:\d{3,5})|(?:\d{4} \d{2}))\)?[\-\ ]?\d{2,4}[\-\ ]?\d{2,4})';
26
+	/**
27
+	 * indicates that the 'tel' input regex pattern is for a UK formatted phone number, examples:
28
+	 *      (###) #### ####
29
+	 *      (####) ### ####
30
+	 *      (#####) ## ####
31
+	 *
32
+	 * captures the intl code to the first group (+44) and the rest of the number to group 2
33
+	 *      +44 (###) #### ####
34
+	 */
35
+	public const PATTERN_UK = '(\+?44)?[\ ]?(\(?(?:(?:\d{3,5})|(?:\d{4} \d{2}))\)?[\-\ ]?\d{2,4}[\-\ ]?\d{2,4})';
36 36
 
37
-    /**
38
-     * indicates that the 'tel' input regex pattern is for a France formatted phone number, examples:
39
-     *      0# ## ## ## ##
40
-     *      0### ## ## ##
41
-     *
42
-     * captures the intl code to the first group (+33) and the rest of the number to group 2
43
-     *      +33 # ## ## ## ##
44
-     *      0033 # ## ## ## ##
45
-     */
46
-    public const PATTERN_FR = '((?:\+|00)33)?[\ \.\-]*((?:(?:\(0\)[\ \.\-]{0,3})?|0)[1-9](?:(?:[\ \.\-]?\d{2}){4}|\d{2}(?:[\ \.\-]?\d{3}){2}))';
37
+	/**
38
+	 * indicates that the 'tel' input regex pattern is for a France formatted phone number, examples:
39
+	 *      0# ## ## ## ##
40
+	 *      0### ## ## ##
41
+	 *
42
+	 * captures the intl code to the first group (+33) and the rest of the number to group 2
43
+	 *      +33 # ## ## ## ##
44
+	 *      0033 # ## ## ## ##
45
+	 */
46
+	public const PATTERN_FR = '((?:\+|00)33)?[\ \.\-]*((?:(?:\(0\)[\ \.\-]{0,3})?|0)[1-9](?:(?:[\ \.\-]?\d{2}){4}|\d{2}(?:[\ \.\-]?\d{3}){2}))';
47 47
 
48
-    /**
49
-     * indicates that the 'tel' input regex pattern is for a German formatted phone number, examples:
50
-     *      (0##) ####-####
51
-     *      (0###) ####-####
52
-     *      (0####) ###-####
53
-     *      (03####) ##-####
54
-     *
55
-     * captures the intl code to the first group (+49) and the rest of the number to group 2
56
-     *      +49 (0##) ####-####
57
-     */
58
-    public const PATTERN_DE = '(\+?49)?[\ \.\-]?(\(?(?:[\d \-\)\–\/\(]+){6,}\)?(?:[\ \.\-–\/]?)(?:[\d]+))';
48
+	/**
49
+	 * indicates that the 'tel' input regex pattern is for a German formatted phone number, examples:
50
+	 *      (0##) ####-####
51
+	 *      (0###) ####-####
52
+	 *      (0####) ###-####
53
+	 *      (03####) ##-####
54
+	 *
55
+	 * captures the intl code to the first group (+49) and the rest of the number to group 2
56
+	 *      +49 (0##) ####-####
57
+	 */
58
+	public const PATTERN_DE = '(\+?49)?[\ \.\-]?(\(?(?:[\d \-\)\–\/\(]+){6,}\)?(?:[\ \.\-–\/]?)(?:[\d]+))';
59 59
 
60
-    /**
61
-     * @var array
62
-     */
63
-    private $regex_patterns;
60
+	/**
61
+	 * @var array
62
+	 */
63
+	private $regex_patterns;
64 64
 
65
-    /**
66
-     * @var array
67
-     */
68
-    private $valid_type_options;
65
+	/**
66
+	 * @var array
67
+	 */
68
+	private $valid_type_options;
69 69
 
70 70
 
71
-    /**
72
-     * Phone constructor.
73
-     */
74
-    public function __construct()
75
-    {
76
-        $this->regex_patterns     = (array) apply_filters(
77
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Phone__regex_patterns',
78
-            [
79
-                'de_DE' => Phone::PATTERN_DE,
80
-                'fr_FR' => Phone::PATTERN_FR,
81
-                'en_UK' => Phone::PATTERN_UK,
82
-                'en_US' => Phone::PATTERN_US,
83
-            ]
84
-        );
85
-        $this->valid_type_options = apply_filters(
86
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Phone__valid_type_options',
87
-            [
88
-                Phone::INPUT_TYPE => esc_html__('Phone Number', 'event_espresso'),
89
-            ]
90
-        );
91
-    }
71
+	/**
72
+	 * Phone constructor.
73
+	 */
74
+	public function __construct()
75
+	{
76
+		$this->regex_patterns     = (array) apply_filters(
77
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Phone__regex_patterns',
78
+			[
79
+				'de_DE' => Phone::PATTERN_DE,
80
+				'fr_FR' => Phone::PATTERN_FR,
81
+				'en_UK' => Phone::PATTERN_UK,
82
+				'en_US' => Phone::PATTERN_US,
83
+			]
84
+		);
85
+		$this->valid_type_options = apply_filters(
86
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Phone__valid_type_options',
87
+			[
88
+				Phone::INPUT_TYPE => esc_html__('Phone Number', 'event_espresso'),
89
+			]
90
+		);
91
+	}
92 92
 
93 93
 
94
-    /**
95
-     * @return array
96
-     */
97
-    public function regexPatterns(): array
98
-    {
99
-        return $this->regex_patterns;
100
-    }
94
+	/**
95
+	 * @return array
96
+	 */
97
+	public function regexPatterns(): array
98
+	{
99
+		return $this->regex_patterns;
100
+	}
101 101
 
102 102
 
103
-    /**
104
-     * @param bool $constants_only
105
-     * @return array
106
-     */
107
-    public function validTypeOptions(bool $constants_only = false): array
108
-    {
109
-        return $constants_only
110
-            ? array_keys($this->valid_type_options)
111
-            : $this->valid_type_options;
112
-    }
103
+	/**
104
+	 * @param bool $constants_only
105
+	 * @return array
106
+	 */
107
+	public function validTypeOptions(bool $constants_only = false): array
108
+	{
109
+		return $constants_only
110
+			? array_keys($this->valid_type_options)
111
+			: $this->valid_type_options;
112
+	}
113 113
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@
 block discarded – undo
73 73
      */
74 74
     public function __construct()
75 75
     {
76
-        $this->regex_patterns     = (array) apply_filters(
76
+        $this->regex_patterns = (array) apply_filters(
77 77
             'FHEE__EventEspresso_core_services_form_meta_inputs_Phone__regex_patterns',
78 78
             [
79 79
                 'de_DE' => Phone::PATTERN_DE,
Please login to merge, or discard this patch.
core/services/form/meta/InputTypes.php 1 patch
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -12,102 +12,102 @@
 block discarded – undo
12 12
 
13 13
 class InputTypes
14 14
 {
15
-    /**
16
-     * @var Button
17
-     */
18
-    private $button;
19
-
20
-    /**
21
-     * @var DateTime
22
-     */
23
-    private $datetime;
24
-
25
-    /**
26
-     * @var Input
27
-     */
28
-    private $input;
29
-
30
-    /**
31
-     * @var Number
32
-     */
33
-    private $number;
34
-
35
-    /**
36
-     * @var Phone
37
-     */
38
-    private $phone;
39
-
40
-    /**
41
-     * @var Select
42
-     */
43
-    private $select;
44
-
45
-    /**
46
-     * @var Text
47
-     */
48
-    private $text;
49
-
50
-    /**
51
-     * @var array
52
-     */
53
-    private $valid_type_options;
54
-
55
-
56
-    /**
57
-     * InputTypes constructor.
58
-     *
59
-     * @param Button   $button
60
-     * @param DateTime $datetime
61
-     * @param Input    $input
62
-     * @param Number   $number
63
-     * @param Phone    $phone
64
-     * @param Select   $select
65
-     * @param Text     $text
66
-     */
67
-    public function __construct(
68
-        Button $button,
69
-        DateTime $datetime,
70
-        Input $input,
71
-        Number $number,
72
-        Phone $phone,
73
-        Select $select,
74
-        Text $text
75
-    ) {
76
-        $this->button   = $button;
77
-        $this->datetime = $datetime;
78
-        $this->input    = $input;
79
-        $this->number   = $number;
80
-        $this->phone    = $phone;
81
-        $this->select   = $select;
82
-        $this->text     = $text;
83
-        $this->assembleValidTypeOptions();
84
-    }
85
-
86
-
87
-    private function assembleValidTypeOptions()
88
-    {
89
-        $button     = $this->button->validTypeOptions();
90
-        $datetime   = $this->datetime->validTypeOptions();
91
-        $input      = $this->input->validTypeOptions();
92
-        $number     = $this->number->validTypeOptions();
93
-        $phone      = $this->phone->validTypeOptions();
94
-        $select     = $this->select->validTypeOptions();
95
-        $text       = $this->text->validTypeOptions();
96
-        $this->valid_type_options = apply_filters(
97
-            'FHEE__EventEspresso_core_services_form_meta_InputTypes__valid_type_options',
98
-            array_merge($button, $datetime, $input, $number, $phone, $select, $text)
99
-        );
100
-    }
101
-
102
-
103
-    /**
104
-     * @param bool $constants_only
105
-     * @return array
106
-     */
107
-    public function validTypeOptions(bool $constants_only = false): array
108
-    {
109
-        return $constants_only
110
-            ? array_keys($this->valid_type_options)
111
-            : $this->valid_type_options;
112
-    }
15
+	/**
16
+	 * @var Button
17
+	 */
18
+	private $button;
19
+
20
+	/**
21
+	 * @var DateTime
22
+	 */
23
+	private $datetime;
24
+
25
+	/**
26
+	 * @var Input
27
+	 */
28
+	private $input;
29
+
30
+	/**
31
+	 * @var Number
32
+	 */
33
+	private $number;
34
+
35
+	/**
36
+	 * @var Phone
37
+	 */
38
+	private $phone;
39
+
40
+	/**
41
+	 * @var Select
42
+	 */
43
+	private $select;
44
+
45
+	/**
46
+	 * @var Text
47
+	 */
48
+	private $text;
49
+
50
+	/**
51
+	 * @var array
52
+	 */
53
+	private $valid_type_options;
54
+
55
+
56
+	/**
57
+	 * InputTypes constructor.
58
+	 *
59
+	 * @param Button   $button
60
+	 * @param DateTime $datetime
61
+	 * @param Input    $input
62
+	 * @param Number   $number
63
+	 * @param Phone    $phone
64
+	 * @param Select   $select
65
+	 * @param Text     $text
66
+	 */
67
+	public function __construct(
68
+		Button $button,
69
+		DateTime $datetime,
70
+		Input $input,
71
+		Number $number,
72
+		Phone $phone,
73
+		Select $select,
74
+		Text $text
75
+	) {
76
+		$this->button   = $button;
77
+		$this->datetime = $datetime;
78
+		$this->input    = $input;
79
+		$this->number   = $number;
80
+		$this->phone    = $phone;
81
+		$this->select   = $select;
82
+		$this->text     = $text;
83
+		$this->assembleValidTypeOptions();
84
+	}
85
+
86
+
87
+	private function assembleValidTypeOptions()
88
+	{
89
+		$button     = $this->button->validTypeOptions();
90
+		$datetime   = $this->datetime->validTypeOptions();
91
+		$input      = $this->input->validTypeOptions();
92
+		$number     = $this->number->validTypeOptions();
93
+		$phone      = $this->phone->validTypeOptions();
94
+		$select     = $this->select->validTypeOptions();
95
+		$text       = $this->text->validTypeOptions();
96
+		$this->valid_type_options = apply_filters(
97
+			'FHEE__EventEspresso_core_services_form_meta_InputTypes__valid_type_options',
98
+			array_merge($button, $datetime, $input, $number, $phone, $select, $text)
99
+		);
100
+	}
101
+
102
+
103
+	/**
104
+	 * @param bool $constants_only
105
+	 * @return array
106
+	 */
107
+	public function validTypeOptions(bool $constants_only = false): array
108
+	{
109
+		return $constants_only
110
+			? array_keys($this->valid_type_options)
111
+			: $this->valid_type_options;
112
+	}
113 113
 }
Please login to merge, or discard this patch.
core/services/container/Mirror.php 2 patches
Indentation   +286 added lines, -286 removed lines patch added patch discarded remove patch
@@ -21,290 +21,290 @@
 block discarded – undo
21 21
 class Mirror
22 22
 {
23 23
 
24
-    /**
25
-     * @var ReflectionClass[]
26
-     */
27
-    private $classes = [];
28
-
29
-    /**
30
-     * @var ReflectionMethod[]
31
-     */
32
-    private $constructors = [];
33
-
34
-    /**
35
-     * @var ReflectionParameter[][]
36
-     */
37
-    private $parameters = [];
38
-
39
-    /**
40
-     * @var ReflectionParameter[][]
41
-     */
42
-    private $parameter_classes = [];
43
-
44
-    /**
45
-     * @var ReflectionProperty[][]
46
-     */
47
-    private $properties = [];
48
-
49
-    /**
50
-     * @var ReflectionMethod[][]
51
-     */
52
-    private $methods = [];
53
-
54
-    /**
55
-     * @var array
56
-     */
57
-    private $default_properties = [];
58
-
59
-    /**
60
-     * @var array
61
-     */
62
-    private $static_properties = [];
63
-
64
-
65
-    /**
66
-     * @param string $class_name
67
-     * @return ReflectionClass
68
-     * @throws ReflectionException
69
-     * @throws InvalidDataTypeException
70
-     */
71
-    public function getReflectionClass(string $class_name): ReflectionClass
72
-    {
73
-        if (! is_string($class_name)) {
74
-            throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
75
-        }
76
-        if (! isset($this->classes[ $class_name ])) {
77
-            $this->classes[ $class_name ] = new ReflectionClass($class_name);
78
-        }
79
-        return $this->classes[ $class_name ];
80
-    }
81
-
82
-
83
-    /**
84
-     * @param string $class_name
85
-     * @return ReflectionMethod|null
86
-     * @throws InvalidDataTypeException
87
-     * @throws ReflectionException
88
-     */
89
-    public function getConstructor(string $class_name): ?ReflectionMethod
90
-    {
91
-        if (! is_string($class_name)) {
92
-            throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
93
-        }
94
-        if (! isset($this->constructors[ $class_name ])) {
95
-            $reflection_class                  = $this->getReflectionClass($class_name);
96
-            $this->constructors[ $class_name ] = $reflection_class->getConstructor();
97
-        }
98
-        return $this->constructors[ $class_name ];
99
-    }
100
-
101
-
102
-    /**
103
-     * @param ReflectionClass $reflection_class
104
-     * @return ReflectionMethod|null
105
-     * @throws InvalidDataTypeException
106
-     * @throws ReflectionException
107
-     */
108
-    public function getConstructorFromReflection(ReflectionClass $reflection_class): ?ReflectionMethod
109
-    {
110
-        return $this->getConstructor($reflection_class->getName());
111
-    }
112
-
113
-
114
-    /**
115
-     * @param string $class_name
116
-     * @return ReflectionParameter[]
117
-     * @throws InvalidDataTypeException
118
-     * @throws ReflectionException
119
-     */
120
-    public function getParameters(string $class_name): array
121
-    {
122
-        if (! isset($this->parameters[ $class_name ])) {
123
-            $constructor                     = $this->getConstructor($class_name);
124
-            $this->parameters[ $class_name ] = $constructor->getParameters();
125
-        }
126
-        return $this->parameters[ $class_name ];
127
-    }
128
-
129
-
130
-    /**
131
-     * @param ReflectionClass $reflection_class
132
-     * @return ReflectionParameter[]
133
-     * @throws InvalidDataTypeException
134
-     * @throws ReflectionException
135
-     */
136
-    public function getParametersFromReflection(ReflectionClass $reflection_class): array
137
-    {
138
-        return $this->getParameters($reflection_class->getName());
139
-    }
140
-
141
-
142
-    /**
143
-     * @param ReflectionMethod $constructor
144
-     * @return ReflectionParameter[]
145
-     * @throws InvalidDataTypeException
146
-     * @throws ReflectionException
147
-     */
148
-    public function getParametersFromReflectionConstructor(ReflectionMethod $constructor): array
149
-    {
150
-        return $this->getParameters($constructor->getDeclaringClass());
151
-    }
152
-
153
-
154
-    /**
155
-     * returns array of ReflectionParameter objects for parameters that are NOT optional
156
-     *
157
-     * @param string $class_name
158
-     * @return ReflectionParameter[]
159
-     * @throws InvalidDataTypeException
160
-     * @throws ReflectionException
161
-     */
162
-    public function getRequiredParameters(string $class_name): array
163
-    {
164
-        $required_parameters = [];
165
-        $parameters          = $this->getParameters($class_name);
166
-        foreach ($parameters as $parameter) {
167
-            if ($parameter instanceof ReflectionParameter && ! $parameter->isOptional()) {
168
-                $required_parameters[] = $parameter;
169
-            }
170
-        }
171
-        return $required_parameters;
172
-    }
173
-
174
-
175
-    /**
176
-     * @param ReflectionParameter $param
177
-     * @param string              $class_name
178
-     * @param string              $index
179
-     * @return string|null
180
-     */
181
-    public function getParameterClassName(ReflectionParameter $param, string $class_name, string $index): ?string
182
-    {
183
-        if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_name'])) {
184
-            return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
185
-        }
186
-        if (! isset($this->parameter_classes[ $class_name ])) {
187
-            $this->parameter_classes[ $class_name ] = [];
188
-        }
189
-        if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
190
-            $this->parameter_classes[ $class_name ][ $index ] = [];
191
-        }
192
-        $this->parameter_classes[ $class_name ][ $index ]['param_class_name'] = $param->getClass()
193
-            ? $param->getClass()->name
194
-            : null;
195
-        return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
196
-    }
197
-
198
-
199
-    /**
200
-     * @param ReflectionParameter $param
201
-     * @param string              $class_name
202
-     * @param string              $index
203
-     * @return array|string|null
204
-     * @throws ReflectionException
205
-     */
206
-    public function getParameterDefaultValue(ReflectionParameter $param, string $class_name, string $index)
207
-    {
208
-        if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_default'])) {
209
-            return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
210
-        }
211
-        if (! isset($this->parameter_classes[ $class_name ])) {
212
-            $this->parameter_classes[ $class_name ] = [];
213
-        }
214
-        if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
215
-            $this->parameter_classes[ $class_name ][ $index ] = [];
216
-        }
217
-        $this->parameter_classes[ $class_name ][ $index ]['param_class_default'] = $param->isDefaultValueAvailable()
218
-            ? $param->getDefaultValue()
219
-            : null;
220
-        return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
221
-    }
222
-
223
-
224
-    /**
225
-     * @param string $class_name
226
-     * @return ReflectionProperty[]
227
-     * @throws InvalidDataTypeException
228
-     * @throws ReflectionException
229
-     */
230
-    public function getProperties(string $class_name): array
231
-    {
232
-        if (! isset($this->properties[ $class_name ])) {
233
-            $reflection_class                = $this->getReflectionClass($class_name);
234
-            $this->properties[ $class_name ] = $reflection_class->getProperties();
235
-        }
236
-        return $this->properties[ $class_name ];
237
-    }
238
-
239
-
240
-    /**
241
-     * @param ReflectionClass $reflection_class
242
-     * @return ReflectionProperty[]
243
-     * @throws InvalidDataTypeException
244
-     * @throws ReflectionException
245
-     */
246
-    public function getPropertiesFromReflection(ReflectionClass $reflection_class): array
247
-    {
248
-        return $this->getProperties($reflection_class->getName());
249
-    }
250
-
251
-
252
-    /**
253
-     * @param string $class_name
254
-     * @return ReflectionMethod[]
255
-     * @throws InvalidDataTypeException
256
-     * @throws ReflectionException
257
-     */
258
-    public function getMethods(string $class_name): array
259
-    {
260
-        if (! isset($this->methods[ $class_name ])) {
261
-            $reflection_class             = $this->getReflectionClass($class_name);
262
-            $this->methods[ $class_name ] = $reflection_class->getMethods();
263
-        }
264
-        return $this->methods[ $class_name ];
265
-    }
266
-
267
-
268
-    /**
269
-     * @param ReflectionClass $reflection_class )
270
-     * @return ReflectionMethod[]
271
-     * @throws InvalidDataTypeException
272
-     * @throws ReflectionException
273
-     */
274
-    public function getMethodsFromReflection(ReflectionClass $reflection_class): array
275
-    {
276
-        return $this->getMethods($reflection_class->getName());
277
-    }
278
-
279
-
280
-    /**
281
-     * @param string $class_name
282
-     * @return array
283
-     * @throws InvalidDataTypeException
284
-     * @throws ReflectionException
285
-     */
286
-    public function getDefaultProperties(string $class_name): array
287
-    {
288
-        if (! isset($this->default_properties[ $class_name ])) {
289
-            $reflection_class                        = $this->getReflectionClass($class_name);
290
-            $this->default_properties[ $class_name ] = $reflection_class->getDefaultProperties();
291
-        }
292
-        return $this->default_properties[ $class_name ];
293
-    }
294
-
295
-
296
-    /**
297
-     * @param string $class_name
298
-     * @return array
299
-     * @throws InvalidDataTypeException
300
-     * @throws ReflectionException
301
-     */
302
-    public function getStaticProperties(string $class_name): array
303
-    {
304
-        if (! isset($this->static_properties[ $class_name ])) {
305
-            $reflection_class                       = $this->getReflectionClass($class_name);
306
-            $this->static_properties[ $class_name ] = $reflection_class->getStaticProperties();
307
-        }
308
-        return $this->static_properties[ $class_name ];
309
-    }
24
+	/**
25
+	 * @var ReflectionClass[]
26
+	 */
27
+	private $classes = [];
28
+
29
+	/**
30
+	 * @var ReflectionMethod[]
31
+	 */
32
+	private $constructors = [];
33
+
34
+	/**
35
+	 * @var ReflectionParameter[][]
36
+	 */
37
+	private $parameters = [];
38
+
39
+	/**
40
+	 * @var ReflectionParameter[][]
41
+	 */
42
+	private $parameter_classes = [];
43
+
44
+	/**
45
+	 * @var ReflectionProperty[][]
46
+	 */
47
+	private $properties = [];
48
+
49
+	/**
50
+	 * @var ReflectionMethod[][]
51
+	 */
52
+	private $methods = [];
53
+
54
+	/**
55
+	 * @var array
56
+	 */
57
+	private $default_properties = [];
58
+
59
+	/**
60
+	 * @var array
61
+	 */
62
+	private $static_properties = [];
63
+
64
+
65
+	/**
66
+	 * @param string $class_name
67
+	 * @return ReflectionClass
68
+	 * @throws ReflectionException
69
+	 * @throws InvalidDataTypeException
70
+	 */
71
+	public function getReflectionClass(string $class_name): ReflectionClass
72
+	{
73
+		if (! is_string($class_name)) {
74
+			throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
75
+		}
76
+		if (! isset($this->classes[ $class_name ])) {
77
+			$this->classes[ $class_name ] = new ReflectionClass($class_name);
78
+		}
79
+		return $this->classes[ $class_name ];
80
+	}
81
+
82
+
83
+	/**
84
+	 * @param string $class_name
85
+	 * @return ReflectionMethod|null
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws ReflectionException
88
+	 */
89
+	public function getConstructor(string $class_name): ?ReflectionMethod
90
+	{
91
+		if (! is_string($class_name)) {
92
+			throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
93
+		}
94
+		if (! isset($this->constructors[ $class_name ])) {
95
+			$reflection_class                  = $this->getReflectionClass($class_name);
96
+			$this->constructors[ $class_name ] = $reflection_class->getConstructor();
97
+		}
98
+		return $this->constructors[ $class_name ];
99
+	}
100
+
101
+
102
+	/**
103
+	 * @param ReflectionClass $reflection_class
104
+	 * @return ReflectionMethod|null
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function getConstructorFromReflection(ReflectionClass $reflection_class): ?ReflectionMethod
109
+	{
110
+		return $this->getConstructor($reflection_class->getName());
111
+	}
112
+
113
+
114
+	/**
115
+	 * @param string $class_name
116
+	 * @return ReflectionParameter[]
117
+	 * @throws InvalidDataTypeException
118
+	 * @throws ReflectionException
119
+	 */
120
+	public function getParameters(string $class_name): array
121
+	{
122
+		if (! isset($this->parameters[ $class_name ])) {
123
+			$constructor                     = $this->getConstructor($class_name);
124
+			$this->parameters[ $class_name ] = $constructor->getParameters();
125
+		}
126
+		return $this->parameters[ $class_name ];
127
+	}
128
+
129
+
130
+	/**
131
+	 * @param ReflectionClass $reflection_class
132
+	 * @return ReflectionParameter[]
133
+	 * @throws InvalidDataTypeException
134
+	 * @throws ReflectionException
135
+	 */
136
+	public function getParametersFromReflection(ReflectionClass $reflection_class): array
137
+	{
138
+		return $this->getParameters($reflection_class->getName());
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param ReflectionMethod $constructor
144
+	 * @return ReflectionParameter[]
145
+	 * @throws InvalidDataTypeException
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function getParametersFromReflectionConstructor(ReflectionMethod $constructor): array
149
+	{
150
+		return $this->getParameters($constructor->getDeclaringClass());
151
+	}
152
+
153
+
154
+	/**
155
+	 * returns array of ReflectionParameter objects for parameters that are NOT optional
156
+	 *
157
+	 * @param string $class_name
158
+	 * @return ReflectionParameter[]
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws ReflectionException
161
+	 */
162
+	public function getRequiredParameters(string $class_name): array
163
+	{
164
+		$required_parameters = [];
165
+		$parameters          = $this->getParameters($class_name);
166
+		foreach ($parameters as $parameter) {
167
+			if ($parameter instanceof ReflectionParameter && ! $parameter->isOptional()) {
168
+				$required_parameters[] = $parameter;
169
+			}
170
+		}
171
+		return $required_parameters;
172
+	}
173
+
174
+
175
+	/**
176
+	 * @param ReflectionParameter $param
177
+	 * @param string              $class_name
178
+	 * @param string              $index
179
+	 * @return string|null
180
+	 */
181
+	public function getParameterClassName(ReflectionParameter $param, string $class_name, string $index): ?string
182
+	{
183
+		if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_name'])) {
184
+			return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
185
+		}
186
+		if (! isset($this->parameter_classes[ $class_name ])) {
187
+			$this->parameter_classes[ $class_name ] = [];
188
+		}
189
+		if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
190
+			$this->parameter_classes[ $class_name ][ $index ] = [];
191
+		}
192
+		$this->parameter_classes[ $class_name ][ $index ]['param_class_name'] = $param->getClass()
193
+			? $param->getClass()->name
194
+			: null;
195
+		return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
196
+	}
197
+
198
+
199
+	/**
200
+	 * @param ReflectionParameter $param
201
+	 * @param string              $class_name
202
+	 * @param string              $index
203
+	 * @return array|string|null
204
+	 * @throws ReflectionException
205
+	 */
206
+	public function getParameterDefaultValue(ReflectionParameter $param, string $class_name, string $index)
207
+	{
208
+		if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_default'])) {
209
+			return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
210
+		}
211
+		if (! isset($this->parameter_classes[ $class_name ])) {
212
+			$this->parameter_classes[ $class_name ] = [];
213
+		}
214
+		if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
215
+			$this->parameter_classes[ $class_name ][ $index ] = [];
216
+		}
217
+		$this->parameter_classes[ $class_name ][ $index ]['param_class_default'] = $param->isDefaultValueAvailable()
218
+			? $param->getDefaultValue()
219
+			: null;
220
+		return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
221
+	}
222
+
223
+
224
+	/**
225
+	 * @param string $class_name
226
+	 * @return ReflectionProperty[]
227
+	 * @throws InvalidDataTypeException
228
+	 * @throws ReflectionException
229
+	 */
230
+	public function getProperties(string $class_name): array
231
+	{
232
+		if (! isset($this->properties[ $class_name ])) {
233
+			$reflection_class                = $this->getReflectionClass($class_name);
234
+			$this->properties[ $class_name ] = $reflection_class->getProperties();
235
+		}
236
+		return $this->properties[ $class_name ];
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param ReflectionClass $reflection_class
242
+	 * @return ReflectionProperty[]
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws ReflectionException
245
+	 */
246
+	public function getPropertiesFromReflection(ReflectionClass $reflection_class): array
247
+	{
248
+		return $this->getProperties($reflection_class->getName());
249
+	}
250
+
251
+
252
+	/**
253
+	 * @param string $class_name
254
+	 * @return ReflectionMethod[]
255
+	 * @throws InvalidDataTypeException
256
+	 * @throws ReflectionException
257
+	 */
258
+	public function getMethods(string $class_name): array
259
+	{
260
+		if (! isset($this->methods[ $class_name ])) {
261
+			$reflection_class             = $this->getReflectionClass($class_name);
262
+			$this->methods[ $class_name ] = $reflection_class->getMethods();
263
+		}
264
+		return $this->methods[ $class_name ];
265
+	}
266
+
267
+
268
+	/**
269
+	 * @param ReflectionClass $reflection_class )
270
+	 * @return ReflectionMethod[]
271
+	 * @throws InvalidDataTypeException
272
+	 * @throws ReflectionException
273
+	 */
274
+	public function getMethodsFromReflection(ReflectionClass $reflection_class): array
275
+	{
276
+		return $this->getMethods($reflection_class->getName());
277
+	}
278
+
279
+
280
+	/**
281
+	 * @param string $class_name
282
+	 * @return array
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws ReflectionException
285
+	 */
286
+	public function getDefaultProperties(string $class_name): array
287
+	{
288
+		if (! isset($this->default_properties[ $class_name ])) {
289
+			$reflection_class                        = $this->getReflectionClass($class_name);
290
+			$this->default_properties[ $class_name ] = $reflection_class->getDefaultProperties();
291
+		}
292
+		return $this->default_properties[ $class_name ];
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param string $class_name
298
+	 * @return array
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws ReflectionException
301
+	 */
302
+	public function getStaticProperties(string $class_name): array
303
+	{
304
+		if (! isset($this->static_properties[ $class_name ])) {
305
+			$reflection_class                       = $this->getReflectionClass($class_name);
306
+			$this->static_properties[ $class_name ] = $reflection_class->getStaticProperties();
307
+		}
308
+		return $this->static_properties[ $class_name ];
309
+	}
310 310
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -70,13 +70,13 @@  discard block
 block discarded – undo
70 70
      */
71 71
     public function getReflectionClass(string $class_name): ReflectionClass
72 72
     {
73
-        if (! is_string($class_name)) {
73
+        if ( ! is_string($class_name)) {
74 74
             throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
75 75
         }
76
-        if (! isset($this->classes[ $class_name ])) {
77
-            $this->classes[ $class_name ] = new ReflectionClass($class_name);
76
+        if ( ! isset($this->classes[$class_name])) {
77
+            $this->classes[$class_name] = new ReflectionClass($class_name);
78 78
         }
79
-        return $this->classes[ $class_name ];
79
+        return $this->classes[$class_name];
80 80
     }
81 81
 
82 82
 
@@ -88,14 +88,14 @@  discard block
 block discarded – undo
88 88
      */
89 89
     public function getConstructor(string $class_name): ?ReflectionMethod
90 90
     {
91
-        if (! is_string($class_name)) {
91
+        if ( ! is_string($class_name)) {
92 92
             throw new InvalidDataTypeException($class_name, '$class_name', 'string (fully qualified class name)');
93 93
         }
94
-        if (! isset($this->constructors[ $class_name ])) {
94
+        if ( ! isset($this->constructors[$class_name])) {
95 95
             $reflection_class                  = $this->getReflectionClass($class_name);
96
-            $this->constructors[ $class_name ] = $reflection_class->getConstructor();
96
+            $this->constructors[$class_name] = $reflection_class->getConstructor();
97 97
         }
98
-        return $this->constructors[ $class_name ];
98
+        return $this->constructors[$class_name];
99 99
     }
100 100
 
101 101
 
@@ -119,11 +119,11 @@  discard block
 block discarded – undo
119 119
      */
120 120
     public function getParameters(string $class_name): array
121 121
     {
122
-        if (! isset($this->parameters[ $class_name ])) {
122
+        if ( ! isset($this->parameters[$class_name])) {
123 123
             $constructor                     = $this->getConstructor($class_name);
124
-            $this->parameters[ $class_name ] = $constructor->getParameters();
124
+            $this->parameters[$class_name] = $constructor->getParameters();
125 125
         }
126
-        return $this->parameters[ $class_name ];
126
+        return $this->parameters[$class_name];
127 127
     }
128 128
 
129 129
 
@@ -180,19 +180,19 @@  discard block
 block discarded – undo
180 180
      */
181 181
     public function getParameterClassName(ReflectionParameter $param, string $class_name, string $index): ?string
182 182
     {
183
-        if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_name'])) {
184
-            return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
183
+        if (isset($this->parameter_classes[$class_name][$index]['param_class_name'])) {
184
+            return $this->parameter_classes[$class_name][$index]['param_class_name'];
185 185
         }
186
-        if (! isset($this->parameter_classes[ $class_name ])) {
187
-            $this->parameter_classes[ $class_name ] = [];
186
+        if ( ! isset($this->parameter_classes[$class_name])) {
187
+            $this->parameter_classes[$class_name] = [];
188 188
         }
189
-        if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
190
-            $this->parameter_classes[ $class_name ][ $index ] = [];
189
+        if ( ! isset($this->parameter_classes[$class_name][$index])) {
190
+            $this->parameter_classes[$class_name][$index] = [];
191 191
         }
192
-        $this->parameter_classes[ $class_name ][ $index ]['param_class_name'] = $param->getClass()
192
+        $this->parameter_classes[$class_name][$index]['param_class_name'] = $param->getClass()
193 193
             ? $param->getClass()->name
194 194
             : null;
195
-        return $this->parameter_classes[ $class_name ][ $index ]['param_class_name'];
195
+        return $this->parameter_classes[$class_name][$index]['param_class_name'];
196 196
     }
197 197
 
198 198
 
@@ -205,19 +205,19 @@  discard block
 block discarded – undo
205 205
      */
206 206
     public function getParameterDefaultValue(ReflectionParameter $param, string $class_name, string $index)
207 207
     {
208
-        if (isset($this->parameter_classes[ $class_name ][ $index ]['param_class_default'])) {
209
-            return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
208
+        if (isset($this->parameter_classes[$class_name][$index]['param_class_default'])) {
209
+            return $this->parameter_classes[$class_name][$index]['param_class_default'];
210 210
         }
211
-        if (! isset($this->parameter_classes[ $class_name ])) {
212
-            $this->parameter_classes[ $class_name ] = [];
211
+        if ( ! isset($this->parameter_classes[$class_name])) {
212
+            $this->parameter_classes[$class_name] = [];
213 213
         }
214
-        if (! isset($this->parameter_classes[ $class_name ][ $index ])) {
215
-            $this->parameter_classes[ $class_name ][ $index ] = [];
214
+        if ( ! isset($this->parameter_classes[$class_name][$index])) {
215
+            $this->parameter_classes[$class_name][$index] = [];
216 216
         }
217
-        $this->parameter_classes[ $class_name ][ $index ]['param_class_default'] = $param->isDefaultValueAvailable()
217
+        $this->parameter_classes[$class_name][$index]['param_class_default'] = $param->isDefaultValueAvailable()
218 218
             ? $param->getDefaultValue()
219 219
             : null;
220
-        return $this->parameter_classes[ $class_name ][ $index ]['param_class_default'];
220
+        return $this->parameter_classes[$class_name][$index]['param_class_default'];
221 221
     }
222 222
 
223 223
 
@@ -229,11 +229,11 @@  discard block
 block discarded – undo
229 229
      */
230 230
     public function getProperties(string $class_name): array
231 231
     {
232
-        if (! isset($this->properties[ $class_name ])) {
232
+        if ( ! isset($this->properties[$class_name])) {
233 233
             $reflection_class                = $this->getReflectionClass($class_name);
234
-            $this->properties[ $class_name ] = $reflection_class->getProperties();
234
+            $this->properties[$class_name] = $reflection_class->getProperties();
235 235
         }
236
-        return $this->properties[ $class_name ];
236
+        return $this->properties[$class_name];
237 237
     }
238 238
 
239 239
 
@@ -257,11 +257,11 @@  discard block
 block discarded – undo
257 257
      */
258 258
     public function getMethods(string $class_name): array
259 259
     {
260
-        if (! isset($this->methods[ $class_name ])) {
260
+        if ( ! isset($this->methods[$class_name])) {
261 261
             $reflection_class             = $this->getReflectionClass($class_name);
262
-            $this->methods[ $class_name ] = $reflection_class->getMethods();
262
+            $this->methods[$class_name] = $reflection_class->getMethods();
263 263
         }
264
-        return $this->methods[ $class_name ];
264
+        return $this->methods[$class_name];
265 265
     }
266 266
 
267 267
 
@@ -285,11 +285,11 @@  discard block
 block discarded – undo
285 285
      */
286 286
     public function getDefaultProperties(string $class_name): array
287 287
     {
288
-        if (! isset($this->default_properties[ $class_name ])) {
288
+        if ( ! isset($this->default_properties[$class_name])) {
289 289
             $reflection_class                        = $this->getReflectionClass($class_name);
290
-            $this->default_properties[ $class_name ] = $reflection_class->getDefaultProperties();
290
+            $this->default_properties[$class_name] = $reflection_class->getDefaultProperties();
291 291
         }
292
-        return $this->default_properties[ $class_name ];
292
+        return $this->default_properties[$class_name];
293 293
     }
294 294
 
295 295
 
@@ -301,10 +301,10 @@  discard block
 block discarded – undo
301 301
      */
302 302
     public function getStaticProperties(string $class_name): array
303 303
     {
304
-        if (! isset($this->static_properties[ $class_name ])) {
304
+        if ( ! isset($this->static_properties[$class_name])) {
305 305
             $reflection_class                       = $this->getReflectionClass($class_name);
306
-            $this->static_properties[ $class_name ] = $reflection_class->getStaticProperties();
306
+            $this->static_properties[$class_name] = $reflection_class->getStaticProperties();
307 307
         }
308
-        return $this->static_properties[ $class_name ];
308
+        return $this->static_properties[$class_name];
309 309
     }
310 310
 }
Please login to merge, or discard this patch.
core/services/orm/ModelFieldFactory.php 2 patches
Indentation   +614 added lines, -614 removed lines patch added patch discarded remove patch
@@ -47,618 +47,618 @@
 block discarded – undo
47 47
 class ModelFieldFactory
48 48
 {
49 49
 
50
-    /**
51
-     * @var LoaderInterface $loader
52
-     */
53
-    private $loader;
54
-
55
-
56
-    /**
57
-     * ModelFieldFactory constructor.
58
-     *
59
-     * @param LoaderInterface $loader
60
-     */
61
-    public function __construct(LoaderInterface $loader)
62
-    {
63
-        $this->loader = $loader;
64
-    }
65
-
66
-
67
-    /**
68
-     * @param string $table_column
69
-     * @param string $nice_name
70
-     * @param bool   $nullable
71
-     * @param null   $default_value
72
-     * @return EE_All_Caps_Text_Field
73
-     */
74
-    public function createAllCapsTextField(
75
-        string $table_column,
76
-        string $nice_name,
77
-        bool $nullable,
78
-        $default_value = null
79
-    ): EE_All_Caps_Text_Field {
80
-        return $this->loader->getNew(
81
-            'EE_All_Caps_Text_Field',
82
-            [$table_column, $nice_name, $nullable, $default_value]
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     * @param string $table_column
89
-     * @param string $nice_name
90
-     * @param bool   $nullable
91
-     * @param null   $default_value
92
-     * @param string $model_name
93
-     * @return EE_Any_Foreign_Model_Name_Field
94
-     */
95
-    public function createAnyForeignModelNameField(
96
-        string $table_column,
97
-        string $nice_name,
98
-        bool $nullable,
99
-        $default_value = null,
100
-        string $model_name = ''
101
-    ): EE_Any_Foreign_Model_Name_Field {
102
-        return $this->loader->getNew(
103
-            'EE_Any_Foreign_Model_Name_Field',
104
-            [$table_column, $nice_name, $nullable, $default_value, $model_name]
105
-        );
106
-    }
107
-
108
-
109
-    /**
110
-     * @param string $table_column
111
-     * @param string $nice_name
112
-     * @param bool   $nullable
113
-     * @param null   $default_value
114
-     * @return EE_Boolean_Field
115
-     */
116
-    public function createBooleanField(
117
-        string $table_column,
118
-        string $nice_name,
119
-        bool $nullable,
120
-        $default_value = null
121
-    ): EE_Boolean_Field {
122
-        return $this->loader->getNew(
123
-            'EE_Boolean_Field',
124
-            [$table_column, $nice_name, $nullable, $default_value]
125
-        );
126
-    }
127
-
128
-
129
-    /**
130
-     * @param string $table_column
131
-     * @param string $nice_name
132
-     * @param bool   $nullable
133
-     * @param string $default_value
134
-     * @return EE_Datetime_Field
135
-     */
136
-    public function createDatetimeField(
137
-        string $table_column,
138
-        string $nice_name,
139
-        bool $nullable = false,
140
-        string $default_value = EE_Datetime_Field::now
141
-    ): EE_Datetime_Field {
142
-        return $this->loader->getNew('EE_Datetime_Field', [$table_column, $nice_name, $nullable, $default_value,]);
143
-    }
144
-
145
-
146
-    /**
147
-     * @param string $table_column
148
-     * @param string $nice_name
149
-     * @param bool   $nullable
150
-     * @param null   $default_value
151
-     * @return EE_DB_Only_Float_Field
152
-     */
153
-    public function createDbOnlyFloatField(
154
-        string $table_column,
155
-        string $nice_name,
156
-        bool $nullable,
157
-        $default_value = null
158
-    ): EE_DB_Only_Float_Field {
159
-        return $this->loader->getNew(
160
-            'EE_DB_Only_Float_Field',
161
-            [$table_column, $nice_name, $nullable, $default_value]
162
-        );
163
-    }
164
-
165
-
166
-    /**
167
-     * @param string $table_column
168
-     * @param string $nice_name
169
-     * @param bool   $nullable
170
-     * @param null   $default_value
171
-     * @return EE_DB_Only_Int_Field
172
-     */
173
-    public function createDbOnlyIntField(
174
-        string $table_column,
175
-        string $nice_name,
176
-        bool $nullable,
177
-        $default_value = null
178
-    ): EE_DB_Only_Int_Field {
179
-        return $this->loader->getNew(
180
-            'EE_DB_Only_Int_Field',
181
-            [$table_column, $nice_name, $nullable, $default_value]
182
-        );
183
-    }
184
-
185
-
186
-    /**
187
-     * @param string $table_column
188
-     * @param string $nice_name
189
-     * @param bool   $nullable
190
-     * @param null   $default_value
191
-     * @return EE_DB_Only_Text_Field
192
-     */
193
-    public function createDbOnlyTextField(
194
-        string $table_column,
195
-        string $nice_name,
196
-        bool $nullable,
197
-        $default_value = null
198
-    ): EE_DB_Only_Text_Field {
199
-        return $this->loader->getNew(
200
-            'EE_DB_Only_Text_Field',
201
-            [$table_column, $nice_name, $nullable, $default_value]
202
-        );
203
-    }
204
-
205
-
206
-    /**
207
-     * @param string      $table_column
208
-     * @param string      $nice_name
209
-     * @param bool        $nullable
210
-     * @param string|null $default_value
211
-     * @return EE_Email_Field
212
-     */
213
-    public function createEmailField(
214
-        string $table_column,
215
-        string $nice_name,
216
-        bool $nullable = true,
217
-        string $default_value = ''
218
-    ): EE_Email_Field {
219
-        return $this->loader->getNew(
220
-            'EE_Email_Field',
221
-            [$table_column, $nice_name, $nullable, $default_value]
222
-        );
223
-    }
224
-
225
-
226
-    /**
227
-     * @param string $table_column
228
-     * @param string $nice_name
229
-     * @param bool   $nullable
230
-     * @param null   $default_value
231
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
232
-     *                                    values are how they should be displayed
233
-     * @return EE_Enum_Integer_Field
234
-     */
235
-    public function createEnumIntegerField(
236
-        string $table_column,
237
-        string $nice_name,
238
-        bool $nullable,
239
-        $default_value = null,
240
-        array $allowed_enum_values = []
241
-    ): EE_Enum_Integer_Field {
242
-        return $this->loader->getNew(
243
-            'EE_Enum_Integer_Field',
244
-            [$table_column, $nice_name, $nullable, $default_value, $allowed_enum_values]
245
-        );
246
-    }
247
-
248
-
249
-    /**
250
-     * @param string $table_column
251
-     * @param string $nice_name
252
-     * @param bool   $nullable
253
-     * @param null   $default_value
254
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
255
-     *                                    values are how they should be displayed
256
-     * @return EE_Enum_Text_Field
257
-     */
258
-    public function createEnumTextField(
259
-        string $table_column,
260
-        string $nice_name,
261
-        bool $nullable,
262
-        $default_value,
263
-        array $allowed_enum_values
264
-    ): EE_Enum_Text_Field {
265
-        return $this->loader->getNew(
266
-            'EE_Enum_Text_Field',
267
-            [$table_column, $nice_name, $nullable, $default_value, $allowed_enum_values]
268
-        );
269
-    }
270
-
271
-
272
-    /**
273
-     * @param string $table_column
274
-     * @param string $nice_name
275
-     * @param bool   $nullable
276
-     * @param null   $default_value
277
-     * @return EE_Float_Field
278
-     */
279
-    public function createFloatField(
280
-        string $table_column,
281
-        string $nice_name,
282
-        bool $nullable,
283
-        $default_value = null
284
-    ): EE_Float_Field {
285
-        return $this->loader->getNew(
286
-            'EE_Float_Field',
287
-            [$table_column, $nice_name, $nullable, $default_value]
288
-        );
289
-    }
290
-
291
-
292
-    /**
293
-     * @param string $table_column
294
-     * @param string $nice_name
295
-     * @param bool   $nullable
296
-     * @param null   $default_value
297
-     * @param string $model_name
298
-     * @return EE_Foreign_Key_Int_Field
299
-     */
300
-    public function createForeignKeyIntField(
301
-        string $table_column,
302
-        string $nice_name,
303
-        bool $nullable,
304
-        $default_value,
305
-        string $model_name
306
-    ): EE_Foreign_Key_Int_Field {
307
-        return $this->loader->getNew(
308
-            'EE_Foreign_Key_Int_Field',
309
-            [$table_column, $nice_name, $nullable, $default_value, $model_name]
310
-        );
311
-    }
312
-
313
-
314
-    /**
315
-     * @param string $table_column
316
-     * @param string $nice_name
317
-     * @param bool   $nullable
318
-     * @param null   $default_value
319
-     * @param string $model_name
320
-     * @return EE_Foreign_Key_String_Field
321
-     */
322
-    public function createForeignKeyStringField(
323
-        string $table_column,
324
-        string $nice_name,
325
-        bool $nullable,
326
-        $default_value,
327
-        string $model_name
328
-    ): EE_Foreign_Key_String_Field {
329
-        return $this->loader->getNew(
330
-            'EE_Foreign_Key_String_Field',
331
-            [$table_column, $nice_name, $nullable, $default_value, $model_name]
332
-        );
333
-    }
334
-
335
-
336
-    /**
337
-     * @param string $table_column
338
-     * @param string $nice_name
339
-     * @param bool   $nullable
340
-     * @param null   $default_value
341
-     * @return EE_Full_HTML_Field
342
-     */
343
-    public function createFullHtmlField(
344
-        string $table_column,
345
-        string $nice_name,
346
-        bool $nullable,
347
-        $default_value = null
348
-    ): EE_Full_HTML_Field {
349
-        return $this->loader->getNew(
350
-            'EE_Full_HTML_Field',
351
-            [$table_column, $nice_name, $nullable, $default_value]
352
-        );
353
-    }
354
-
355
-
356
-    /**
357
-     * @param string $table_column
358
-     * @param string $nice_name
359
-     * @param bool   $nullable
360
-     * @param null   $default_value
361
-     * @return EE_Infinite_Integer_Field
362
-     */
363
-    public function createInfiniteIntegerField(
364
-        string $table_column,
365
-        string $nice_name,
366
-        bool $nullable,
367
-        $default_value = null
368
-    ): EE_Infinite_Integer_Field {
369
-        return $this->loader->getNew(
370
-            'EE_Infinite_Integer_Field',
371
-            [$table_column, $nice_name, $nullable, $default_value]
372
-        );
373
-    }
374
-
375
-
376
-    /**
377
-     * @param string  $table_column
378
-     * @param string  $nice_name
379
-     * @param bool    $nullable
380
-     * @param integer $default_value
381
-     * @return EE_Integer_Field
382
-     */
383
-    public function createIntegerField(
384
-        string $table_column,
385
-        string $nice_name,
386
-        bool $nullable = false,
387
-        int $default_value = 0
388
-    ): EE_Integer_Field {
389
-        return $this->loader->getNew(
390
-            'EE_Integer_Field',
391
-            [$table_column, $nice_name, $nullable, $default_value]
392
-        );
393
-    }
394
-
395
-
396
-    /**
397
-     * @param string $table_column
398
-     * @param string $nice_name
399
-     * @param bool   $nullable
400
-     * @param null   $default_value
401
-     * @return EE_Maybe_Serialized_Simple_HTML_Field
402
-     */
403
-    public function createMaybeSerializedSimpleHtmlField(
404
-        string $table_column,
405
-        string $nice_name,
406
-        bool $nullable,
407
-        $default_value = null
408
-    ): EE_Maybe_Serialized_Simple_HTML_Field {
409
-        return $this->loader->getNew(
410
-            'EE_Maybe_Serialized_Simple_HTML_Field',
411
-            [$table_column, $nice_name, $nullable, $default_value]
412
-        );
413
-    }
414
-
415
-
416
-    /**
417
-     * @param string $table_column
418
-     * @param string $nice_name
419
-     * @param bool   $nullable
420
-     * @param null   $default_value
421
-     * @return EE_Maybe_Serialized_Text_Field
422
-     */
423
-    public function createMaybeSerializedTextField(
424
-        string $table_column,
425
-        string $nice_name,
426
-        bool $nullable,
427
-        $default_value = null
428
-    ): EE_Maybe_Serialized_Text_Field {
429
-        return $this->loader->getNew(
430
-            'EE_Maybe_Serialized_Text_Field',
431
-            [$table_column, $nice_name, $nullable, $default_value]
432
-        );
433
-    }
434
-
435
-
436
-    /**
437
-     * @param string $table_column
438
-     * @param string $nice_name
439
-     * @param bool   $nullable
440
-     * @param null   $default_value
441
-     * @return EE_Money_Field
442
-     */
443
-    public function createMoneyField(
444
-        string $table_column,
445
-        string $nice_name,
446
-        bool $nullable,
447
-        $default_value = null
448
-    ): EE_Money_Field {
449
-        return $this->loader->getNew(
450
-            'EE_Money_Field',
451
-            [$table_column, $nice_name, $nullable, $default_value]
452
-        );
453
-    }
454
-
455
-
456
-    /**
457
-     * @param string $table_column
458
-     * @param string $nice_name
459
-     * @param bool   $nullable
460
-     * @param string $default_value
461
-     * @return EE_Plain_Text_Field
462
-     */
463
-    public function createPlainTextField(
464
-        string $table_column,
465
-        string $nice_name,
466
-        bool $nullable = true,
467
-        string $default_value = ''
468
-    ): EE_Plain_Text_Field {
469
-        return $this->loader->getNew(
470
-            'EE_Plain_Text_Field',
471
-            [$table_column, $nice_name, $nullable, $default_value]
472
-        );
473
-    }
474
-
475
-
476
-    /**
477
-     * @param string $table_column
478
-     * @param string $nice_name
479
-     * @param bool   $nullable
480
-     * @param null   $default_value
481
-     * @return EE_Post_Content_Field
482
-     */
483
-    public function createPostContentField(
484
-        string $table_column,
485
-        string $nice_name,
486
-        bool $nullable,
487
-        $default_value = null
488
-    ): EE_Post_Content_Field {
489
-        return $this->loader->getNew(
490
-            'EE_Post_Content_Field',
491
-            [$table_column, $nice_name, $nullable, $default_value]
492
-        );
493
-    }
494
-
495
-
496
-    /**
497
-     * @param string $table_column
498
-     * @param string $nice_name
499
-     * @return EE_Primary_Key_Int_Field
500
-     */
501
-    public function createPrimaryKeyIntField(string $table_column, string $nice_name): EE_Primary_Key_Int_Field
502
-    {
503
-        return $this->loader->getNew('EE_Primary_Key_Int_Field', [$table_column, $nice_name]);
504
-    }
505
-
506
-
507
-    /**
508
-     * @param string $table_column
509
-     * @param string $nice_name
510
-     * @return EE_Primary_Key_String_Field
511
-     */
512
-    public function createPrimaryKeyStringField(string $table_column, string $nice_name): EE_Primary_Key_String_Field
513
-    {
514
-        return $this->loader->getNew('EE_Primary_Key_String_Field', [$table_column, $nice_name]);
515
-    }
516
-
517
-
518
-    /**
519
-     * @param string $table_column
520
-     * @param string $nice_name
521
-     * @param bool   $nullable
522
-     * @param null   $default_value
523
-     * @return EE_Serialized_Text_Field
524
-     */
525
-    public function createSerializedTextField(
526
-        string $table_column,
527
-        string $nice_name,
528
-        bool $nullable,
529
-        $default_value = null
530
-    ): EE_Serialized_Text_Field {
531
-        return $this->loader->getNew(
532
-            'EE_Serialized_Text_Field',
533
-            [$table_column, $nice_name, $nullable, $default_value]
534
-        );
535
-    }
536
-
537
-
538
-    /**
539
-     * @param string $table_column
540
-     * @param string $nice_name
541
-     * @param bool   $nullable
542
-     * @param null   $default_value
543
-     * @return EE_Simple_HTML_Field
544
-     */
545
-    public function createSimpleHtmlField(
546
-        string $table_column,
547
-        string $nice_name,
548
-        bool $nullable,
549
-        $default_value = null
550
-    ): EE_Simple_HTML_Field {
551
-        return $this->loader->getNew(
552
-            'EE_Simple_HTML_Field',
553
-            [$table_column, $nice_name, $nullable, $default_value]
554
-        );
555
-    }
556
-
557
-
558
-    /**
559
-     * @param string $table_column
560
-     * @param string $nice_name
561
-     * @param bool   $nullable
562
-     * @param null   $default_value
563
-     * @return EE_Slug_Field
564
-     */
565
-    public function createSlugField(
566
-        string $table_column,
567
-        string $nice_name,
568
-        bool $nullable = false,
569
-        $default_value = null
570
-    ): EE_Slug_Field {
571
-        return $this->loader->getNew(
572
-            'EE_Slug_Field',
573
-            [$table_column, $nice_name, $nullable, $default_value]
574
-        );
575
-    }
576
-
577
-
578
-    /**
579
-     * @param string $table_column
580
-     * @param string $nice_name
581
-     * @param bool   $nullable
582
-     * @param null   $default_value
583
-     * @return EE_Trashed_Flag_Field
584
-     */
585
-    public function createTrashedFlagField(
586
-        string $table_column,
587
-        string $nice_name,
588
-        bool $nullable,
589
-        $default_value = null
590
-    ): EE_Trashed_Flag_Field {
591
-        return $this->loader->getNew(
592
-            'EE_Trashed_Flag_Field',
593
-            [$table_column, $nice_name, $nullable, $default_value]
594
-        );
595
-    }
596
-
597
-
598
-    /**
599
-     * @param string $table_column
600
-     * @param string $nice_name
601
-     * @param bool   $nullable
602
-     * @param mixed  $default_value
603
-     * @param array $values     If additional statuses are to be used other than the default WP statuses,
604
-     *                          then they can be registered via this property.
605
-     *                          The format of the array should be as follows:
606
-     *                          [
607
-     *                              'status_reference' => [
608
-     *                                  'label' => __('Status Reference Label', 'event_espresso'),
609
-     *                                  // whether status is shown on the frontend of the site
610
-     *                                  'public' => true,
611
-     *                                  // whether status is excluded from wp searches
612
-     *                                  'exclude_from_search' => false,
613
-     *                                  // whether status is included in queries
614
-     *                                  for the admin 'all' view in list table views.
615
-     *                                  'show_in_admin_all_list' => true,
616
-     *                                  // show in the list of statuses with post counts
617
-     *                                  // at the top of the admin list tables (i.e. Status Reference(2) )
618
-     *                                  'show_in_admin_status_list' => true,
619
-     *                                  // the text to display on the admin screen
620
-     *                                  // ( or you won't see your status count )
621
-     *                                  'label_count' => _n_noop(
622
-     *                                      'Status Reference <span class="count">(%s)</span>',
623
-     *                                      'Status References <span class="count">(%s)</span>'
624
-     *                                  ),
625
-     *                              ]
626
-     *                          ]
627
-     * @return EE_WP_Post_Status_Field
628
-     * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
629
-     */
630
-    public function createWpPostStatusField(
631
-        string $table_column,
632
-        string $nice_name,
633
-        bool $nullable,
634
-        $default_value = null,
635
-        array $values = []
636
-    ): EE_WP_Post_Status_Field {
637
-        return $this->loader->getNew(
638
-            'EE_WP_Post_Status_Field',
639
-            [$table_column, $nice_name, $nullable, $default_value, $values]
640
-        );
641
-    }
642
-
643
-
644
-    /**
645
-     * @param string $post_type
646
-     * @return EE_WP_Post_Type_Field
647
-     */
648
-    public function createWpPostTypeField(string $post_type): EE_WP_Post_Type_Field
649
-    {
650
-        return $this->loader->getNew('EE_WP_Post_Type_Field', [$post_type]);
651
-    }
652
-
653
-
654
-    /**
655
-     * @param string $table_column
656
-     * @param string $nice_name
657
-     * @param bool   $nullable
658
-     * @return EE_WP_User_Field
659
-     */
660
-    public function createWpUserField(string $table_column, string $nice_name, bool $nullable): EE_WP_User_Field
661
-    {
662
-        return $this->loader->getNew('EE_WP_User_Field', [$table_column, $nice_name, $nullable]);
663
-    }
50
+	/**
51
+	 * @var LoaderInterface $loader
52
+	 */
53
+	private $loader;
54
+
55
+
56
+	/**
57
+	 * ModelFieldFactory constructor.
58
+	 *
59
+	 * @param LoaderInterface $loader
60
+	 */
61
+	public function __construct(LoaderInterface $loader)
62
+	{
63
+		$this->loader = $loader;
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param string $table_column
69
+	 * @param string $nice_name
70
+	 * @param bool   $nullable
71
+	 * @param null   $default_value
72
+	 * @return EE_All_Caps_Text_Field
73
+	 */
74
+	public function createAllCapsTextField(
75
+		string $table_column,
76
+		string $nice_name,
77
+		bool $nullable,
78
+		$default_value = null
79
+	): EE_All_Caps_Text_Field {
80
+		return $this->loader->getNew(
81
+			'EE_All_Caps_Text_Field',
82
+			[$table_column, $nice_name, $nullable, $default_value]
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 * @param string $table_column
89
+	 * @param string $nice_name
90
+	 * @param bool   $nullable
91
+	 * @param null   $default_value
92
+	 * @param string $model_name
93
+	 * @return EE_Any_Foreign_Model_Name_Field
94
+	 */
95
+	public function createAnyForeignModelNameField(
96
+		string $table_column,
97
+		string $nice_name,
98
+		bool $nullable,
99
+		$default_value = null,
100
+		string $model_name = ''
101
+	): EE_Any_Foreign_Model_Name_Field {
102
+		return $this->loader->getNew(
103
+			'EE_Any_Foreign_Model_Name_Field',
104
+			[$table_column, $nice_name, $nullable, $default_value, $model_name]
105
+		);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param string $table_column
111
+	 * @param string $nice_name
112
+	 * @param bool   $nullable
113
+	 * @param null   $default_value
114
+	 * @return EE_Boolean_Field
115
+	 */
116
+	public function createBooleanField(
117
+		string $table_column,
118
+		string $nice_name,
119
+		bool $nullable,
120
+		$default_value = null
121
+	): EE_Boolean_Field {
122
+		return $this->loader->getNew(
123
+			'EE_Boolean_Field',
124
+			[$table_column, $nice_name, $nullable, $default_value]
125
+		);
126
+	}
127
+
128
+
129
+	/**
130
+	 * @param string $table_column
131
+	 * @param string $nice_name
132
+	 * @param bool   $nullable
133
+	 * @param string $default_value
134
+	 * @return EE_Datetime_Field
135
+	 */
136
+	public function createDatetimeField(
137
+		string $table_column,
138
+		string $nice_name,
139
+		bool $nullable = false,
140
+		string $default_value = EE_Datetime_Field::now
141
+	): EE_Datetime_Field {
142
+		return $this->loader->getNew('EE_Datetime_Field', [$table_column, $nice_name, $nullable, $default_value,]);
143
+	}
144
+
145
+
146
+	/**
147
+	 * @param string $table_column
148
+	 * @param string $nice_name
149
+	 * @param bool   $nullable
150
+	 * @param null   $default_value
151
+	 * @return EE_DB_Only_Float_Field
152
+	 */
153
+	public function createDbOnlyFloatField(
154
+		string $table_column,
155
+		string $nice_name,
156
+		bool $nullable,
157
+		$default_value = null
158
+	): EE_DB_Only_Float_Field {
159
+		return $this->loader->getNew(
160
+			'EE_DB_Only_Float_Field',
161
+			[$table_column, $nice_name, $nullable, $default_value]
162
+		);
163
+	}
164
+
165
+
166
+	/**
167
+	 * @param string $table_column
168
+	 * @param string $nice_name
169
+	 * @param bool   $nullable
170
+	 * @param null   $default_value
171
+	 * @return EE_DB_Only_Int_Field
172
+	 */
173
+	public function createDbOnlyIntField(
174
+		string $table_column,
175
+		string $nice_name,
176
+		bool $nullable,
177
+		$default_value = null
178
+	): EE_DB_Only_Int_Field {
179
+		return $this->loader->getNew(
180
+			'EE_DB_Only_Int_Field',
181
+			[$table_column, $nice_name, $nullable, $default_value]
182
+		);
183
+	}
184
+
185
+
186
+	/**
187
+	 * @param string $table_column
188
+	 * @param string $nice_name
189
+	 * @param bool   $nullable
190
+	 * @param null   $default_value
191
+	 * @return EE_DB_Only_Text_Field
192
+	 */
193
+	public function createDbOnlyTextField(
194
+		string $table_column,
195
+		string $nice_name,
196
+		bool $nullable,
197
+		$default_value = null
198
+	): EE_DB_Only_Text_Field {
199
+		return $this->loader->getNew(
200
+			'EE_DB_Only_Text_Field',
201
+			[$table_column, $nice_name, $nullable, $default_value]
202
+		);
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param string      $table_column
208
+	 * @param string      $nice_name
209
+	 * @param bool        $nullable
210
+	 * @param string|null $default_value
211
+	 * @return EE_Email_Field
212
+	 */
213
+	public function createEmailField(
214
+		string $table_column,
215
+		string $nice_name,
216
+		bool $nullable = true,
217
+		string $default_value = ''
218
+	): EE_Email_Field {
219
+		return $this->loader->getNew(
220
+			'EE_Email_Field',
221
+			[$table_column, $nice_name, $nullable, $default_value]
222
+		);
223
+	}
224
+
225
+
226
+	/**
227
+	 * @param string $table_column
228
+	 * @param string $nice_name
229
+	 * @param bool   $nullable
230
+	 * @param null   $default_value
231
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
232
+	 *                                    values are how they should be displayed
233
+	 * @return EE_Enum_Integer_Field
234
+	 */
235
+	public function createEnumIntegerField(
236
+		string $table_column,
237
+		string $nice_name,
238
+		bool $nullable,
239
+		$default_value = null,
240
+		array $allowed_enum_values = []
241
+	): EE_Enum_Integer_Field {
242
+		return $this->loader->getNew(
243
+			'EE_Enum_Integer_Field',
244
+			[$table_column, $nice_name, $nullable, $default_value, $allowed_enum_values]
245
+		);
246
+	}
247
+
248
+
249
+	/**
250
+	 * @param string $table_column
251
+	 * @param string $nice_name
252
+	 * @param bool   $nullable
253
+	 * @param null   $default_value
254
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
255
+	 *                                    values are how they should be displayed
256
+	 * @return EE_Enum_Text_Field
257
+	 */
258
+	public function createEnumTextField(
259
+		string $table_column,
260
+		string $nice_name,
261
+		bool $nullable,
262
+		$default_value,
263
+		array $allowed_enum_values
264
+	): EE_Enum_Text_Field {
265
+		return $this->loader->getNew(
266
+			'EE_Enum_Text_Field',
267
+			[$table_column, $nice_name, $nullable, $default_value, $allowed_enum_values]
268
+		);
269
+	}
270
+
271
+
272
+	/**
273
+	 * @param string $table_column
274
+	 * @param string $nice_name
275
+	 * @param bool   $nullable
276
+	 * @param null   $default_value
277
+	 * @return EE_Float_Field
278
+	 */
279
+	public function createFloatField(
280
+		string $table_column,
281
+		string $nice_name,
282
+		bool $nullable,
283
+		$default_value = null
284
+	): EE_Float_Field {
285
+		return $this->loader->getNew(
286
+			'EE_Float_Field',
287
+			[$table_column, $nice_name, $nullable, $default_value]
288
+		);
289
+	}
290
+
291
+
292
+	/**
293
+	 * @param string $table_column
294
+	 * @param string $nice_name
295
+	 * @param bool   $nullable
296
+	 * @param null   $default_value
297
+	 * @param string $model_name
298
+	 * @return EE_Foreign_Key_Int_Field
299
+	 */
300
+	public function createForeignKeyIntField(
301
+		string $table_column,
302
+		string $nice_name,
303
+		bool $nullable,
304
+		$default_value,
305
+		string $model_name
306
+	): EE_Foreign_Key_Int_Field {
307
+		return $this->loader->getNew(
308
+			'EE_Foreign_Key_Int_Field',
309
+			[$table_column, $nice_name, $nullable, $default_value, $model_name]
310
+		);
311
+	}
312
+
313
+
314
+	/**
315
+	 * @param string $table_column
316
+	 * @param string $nice_name
317
+	 * @param bool   $nullable
318
+	 * @param null   $default_value
319
+	 * @param string $model_name
320
+	 * @return EE_Foreign_Key_String_Field
321
+	 */
322
+	public function createForeignKeyStringField(
323
+		string $table_column,
324
+		string $nice_name,
325
+		bool $nullable,
326
+		$default_value,
327
+		string $model_name
328
+	): EE_Foreign_Key_String_Field {
329
+		return $this->loader->getNew(
330
+			'EE_Foreign_Key_String_Field',
331
+			[$table_column, $nice_name, $nullable, $default_value, $model_name]
332
+		);
333
+	}
334
+
335
+
336
+	/**
337
+	 * @param string $table_column
338
+	 * @param string $nice_name
339
+	 * @param bool   $nullable
340
+	 * @param null   $default_value
341
+	 * @return EE_Full_HTML_Field
342
+	 */
343
+	public function createFullHtmlField(
344
+		string $table_column,
345
+		string $nice_name,
346
+		bool $nullable,
347
+		$default_value = null
348
+	): EE_Full_HTML_Field {
349
+		return $this->loader->getNew(
350
+			'EE_Full_HTML_Field',
351
+			[$table_column, $nice_name, $nullable, $default_value]
352
+		);
353
+	}
354
+
355
+
356
+	/**
357
+	 * @param string $table_column
358
+	 * @param string $nice_name
359
+	 * @param bool   $nullable
360
+	 * @param null   $default_value
361
+	 * @return EE_Infinite_Integer_Field
362
+	 */
363
+	public function createInfiniteIntegerField(
364
+		string $table_column,
365
+		string $nice_name,
366
+		bool $nullable,
367
+		$default_value = null
368
+	): EE_Infinite_Integer_Field {
369
+		return $this->loader->getNew(
370
+			'EE_Infinite_Integer_Field',
371
+			[$table_column, $nice_name, $nullable, $default_value]
372
+		);
373
+	}
374
+
375
+
376
+	/**
377
+	 * @param string  $table_column
378
+	 * @param string  $nice_name
379
+	 * @param bool    $nullable
380
+	 * @param integer $default_value
381
+	 * @return EE_Integer_Field
382
+	 */
383
+	public function createIntegerField(
384
+		string $table_column,
385
+		string $nice_name,
386
+		bool $nullable = false,
387
+		int $default_value = 0
388
+	): EE_Integer_Field {
389
+		return $this->loader->getNew(
390
+			'EE_Integer_Field',
391
+			[$table_column, $nice_name, $nullable, $default_value]
392
+		);
393
+	}
394
+
395
+
396
+	/**
397
+	 * @param string $table_column
398
+	 * @param string $nice_name
399
+	 * @param bool   $nullable
400
+	 * @param null   $default_value
401
+	 * @return EE_Maybe_Serialized_Simple_HTML_Field
402
+	 */
403
+	public function createMaybeSerializedSimpleHtmlField(
404
+		string $table_column,
405
+		string $nice_name,
406
+		bool $nullable,
407
+		$default_value = null
408
+	): EE_Maybe_Serialized_Simple_HTML_Field {
409
+		return $this->loader->getNew(
410
+			'EE_Maybe_Serialized_Simple_HTML_Field',
411
+			[$table_column, $nice_name, $nullable, $default_value]
412
+		);
413
+	}
414
+
415
+
416
+	/**
417
+	 * @param string $table_column
418
+	 * @param string $nice_name
419
+	 * @param bool   $nullable
420
+	 * @param null   $default_value
421
+	 * @return EE_Maybe_Serialized_Text_Field
422
+	 */
423
+	public function createMaybeSerializedTextField(
424
+		string $table_column,
425
+		string $nice_name,
426
+		bool $nullable,
427
+		$default_value = null
428
+	): EE_Maybe_Serialized_Text_Field {
429
+		return $this->loader->getNew(
430
+			'EE_Maybe_Serialized_Text_Field',
431
+			[$table_column, $nice_name, $nullable, $default_value]
432
+		);
433
+	}
434
+
435
+
436
+	/**
437
+	 * @param string $table_column
438
+	 * @param string $nice_name
439
+	 * @param bool   $nullable
440
+	 * @param null   $default_value
441
+	 * @return EE_Money_Field
442
+	 */
443
+	public function createMoneyField(
444
+		string $table_column,
445
+		string $nice_name,
446
+		bool $nullable,
447
+		$default_value = null
448
+	): EE_Money_Field {
449
+		return $this->loader->getNew(
450
+			'EE_Money_Field',
451
+			[$table_column, $nice_name, $nullable, $default_value]
452
+		);
453
+	}
454
+
455
+
456
+	/**
457
+	 * @param string $table_column
458
+	 * @param string $nice_name
459
+	 * @param bool   $nullable
460
+	 * @param string $default_value
461
+	 * @return EE_Plain_Text_Field
462
+	 */
463
+	public function createPlainTextField(
464
+		string $table_column,
465
+		string $nice_name,
466
+		bool $nullable = true,
467
+		string $default_value = ''
468
+	): EE_Plain_Text_Field {
469
+		return $this->loader->getNew(
470
+			'EE_Plain_Text_Field',
471
+			[$table_column, $nice_name, $nullable, $default_value]
472
+		);
473
+	}
474
+
475
+
476
+	/**
477
+	 * @param string $table_column
478
+	 * @param string $nice_name
479
+	 * @param bool   $nullable
480
+	 * @param null   $default_value
481
+	 * @return EE_Post_Content_Field
482
+	 */
483
+	public function createPostContentField(
484
+		string $table_column,
485
+		string $nice_name,
486
+		bool $nullable,
487
+		$default_value = null
488
+	): EE_Post_Content_Field {
489
+		return $this->loader->getNew(
490
+			'EE_Post_Content_Field',
491
+			[$table_column, $nice_name, $nullable, $default_value]
492
+		);
493
+	}
494
+
495
+
496
+	/**
497
+	 * @param string $table_column
498
+	 * @param string $nice_name
499
+	 * @return EE_Primary_Key_Int_Field
500
+	 */
501
+	public function createPrimaryKeyIntField(string $table_column, string $nice_name): EE_Primary_Key_Int_Field
502
+	{
503
+		return $this->loader->getNew('EE_Primary_Key_Int_Field', [$table_column, $nice_name]);
504
+	}
505
+
506
+
507
+	/**
508
+	 * @param string $table_column
509
+	 * @param string $nice_name
510
+	 * @return EE_Primary_Key_String_Field
511
+	 */
512
+	public function createPrimaryKeyStringField(string $table_column, string $nice_name): EE_Primary_Key_String_Field
513
+	{
514
+		return $this->loader->getNew('EE_Primary_Key_String_Field', [$table_column, $nice_name]);
515
+	}
516
+
517
+
518
+	/**
519
+	 * @param string $table_column
520
+	 * @param string $nice_name
521
+	 * @param bool   $nullable
522
+	 * @param null   $default_value
523
+	 * @return EE_Serialized_Text_Field
524
+	 */
525
+	public function createSerializedTextField(
526
+		string $table_column,
527
+		string $nice_name,
528
+		bool $nullable,
529
+		$default_value = null
530
+	): EE_Serialized_Text_Field {
531
+		return $this->loader->getNew(
532
+			'EE_Serialized_Text_Field',
533
+			[$table_column, $nice_name, $nullable, $default_value]
534
+		);
535
+	}
536
+
537
+
538
+	/**
539
+	 * @param string $table_column
540
+	 * @param string $nice_name
541
+	 * @param bool   $nullable
542
+	 * @param null   $default_value
543
+	 * @return EE_Simple_HTML_Field
544
+	 */
545
+	public function createSimpleHtmlField(
546
+		string $table_column,
547
+		string $nice_name,
548
+		bool $nullable,
549
+		$default_value = null
550
+	): EE_Simple_HTML_Field {
551
+		return $this->loader->getNew(
552
+			'EE_Simple_HTML_Field',
553
+			[$table_column, $nice_name, $nullable, $default_value]
554
+		);
555
+	}
556
+
557
+
558
+	/**
559
+	 * @param string $table_column
560
+	 * @param string $nice_name
561
+	 * @param bool   $nullable
562
+	 * @param null   $default_value
563
+	 * @return EE_Slug_Field
564
+	 */
565
+	public function createSlugField(
566
+		string $table_column,
567
+		string $nice_name,
568
+		bool $nullable = false,
569
+		$default_value = null
570
+	): EE_Slug_Field {
571
+		return $this->loader->getNew(
572
+			'EE_Slug_Field',
573
+			[$table_column, $nice_name, $nullable, $default_value]
574
+		);
575
+	}
576
+
577
+
578
+	/**
579
+	 * @param string $table_column
580
+	 * @param string $nice_name
581
+	 * @param bool   $nullable
582
+	 * @param null   $default_value
583
+	 * @return EE_Trashed_Flag_Field
584
+	 */
585
+	public function createTrashedFlagField(
586
+		string $table_column,
587
+		string $nice_name,
588
+		bool $nullable,
589
+		$default_value = null
590
+	): EE_Trashed_Flag_Field {
591
+		return $this->loader->getNew(
592
+			'EE_Trashed_Flag_Field',
593
+			[$table_column, $nice_name, $nullable, $default_value]
594
+		);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @param string $table_column
600
+	 * @param string $nice_name
601
+	 * @param bool   $nullable
602
+	 * @param mixed  $default_value
603
+	 * @param array $values     If additional statuses are to be used other than the default WP statuses,
604
+	 *                          then they can be registered via this property.
605
+	 *                          The format of the array should be as follows:
606
+	 *                          [
607
+	 *                              'status_reference' => [
608
+	 *                                  'label' => __('Status Reference Label', 'event_espresso'),
609
+	 *                                  // whether status is shown on the frontend of the site
610
+	 *                                  'public' => true,
611
+	 *                                  // whether status is excluded from wp searches
612
+	 *                                  'exclude_from_search' => false,
613
+	 *                                  // whether status is included in queries
614
+	 *                                  for the admin 'all' view in list table views.
615
+	 *                                  'show_in_admin_all_list' => true,
616
+	 *                                  // show in the list of statuses with post counts
617
+	 *                                  // at the top of the admin list tables (i.e. Status Reference(2) )
618
+	 *                                  'show_in_admin_status_list' => true,
619
+	 *                                  // the text to display on the admin screen
620
+	 *                                  // ( or you won't see your status count )
621
+	 *                                  'label_count' => _n_noop(
622
+	 *                                      'Status Reference <span class="count">(%s)</span>',
623
+	 *                                      'Status References <span class="count">(%s)</span>'
624
+	 *                                  ),
625
+	 *                              ]
626
+	 *                          ]
627
+	 * @return EE_WP_Post_Status_Field
628
+	 * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
629
+	 */
630
+	public function createWpPostStatusField(
631
+		string $table_column,
632
+		string $nice_name,
633
+		bool $nullable,
634
+		$default_value = null,
635
+		array $values = []
636
+	): EE_WP_Post_Status_Field {
637
+		return $this->loader->getNew(
638
+			'EE_WP_Post_Status_Field',
639
+			[$table_column, $nice_name, $nullable, $default_value, $values]
640
+		);
641
+	}
642
+
643
+
644
+	/**
645
+	 * @param string $post_type
646
+	 * @return EE_WP_Post_Type_Field
647
+	 */
648
+	public function createWpPostTypeField(string $post_type): EE_WP_Post_Type_Field
649
+	{
650
+		return $this->loader->getNew('EE_WP_Post_Type_Field', [$post_type]);
651
+	}
652
+
653
+
654
+	/**
655
+	 * @param string $table_column
656
+	 * @param string $nice_name
657
+	 * @param bool   $nullable
658
+	 * @return EE_WP_User_Field
659
+	 */
660
+	public function createWpUserField(string $table_column, string $nice_name, bool $nullable): EE_WP_User_Field
661
+	{
662
+		return $this->loader->getNew('EE_WP_User_Field', [$table_column, $nice_name, $nullable]);
663
+	}
664 664
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@
 block discarded – undo
139 139
         bool $nullable = false,
140 140
         string $default_value = EE_Datetime_Field::now
141 141
     ): EE_Datetime_Field {
142
-        return $this->loader->getNew('EE_Datetime_Field', [$table_column, $nice_name, $nullable, $default_value,]);
142
+        return $this->loader->getNew('EE_Datetime_Field', [$table_column, $nice_name, $nullable, $default_value, ]);
143 143
     }
144 144
 
145 145
 
Please login to merge, or discard this patch.
core/db_models/EEM_Form_Element.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -5,30 +5,30 @@
 block discarded – undo
5 5
 abstract class EEM_Form_Element extends EEM_Base
6 6
 {
7 7
 
8
-    /**
9
-     * @var Element
10
-     */
11
-    protected $element;
12
-
13
-    /**
14
-     * @var array
15
-     */
16
-    protected $valid_status_options;
17
-
18
-
19
-    protected function __construct(Element $element, $timezone)
20
-    {
21
-        $this->element = $element;
22
-        parent::__construct($timezone);
23
-    }
24
-
25
-
26
-    /**
27
-     * @param bool $constants_only
28
-     * @return array
29
-     */
30
-    public function validStatusOptions(bool $constants_only = false): array
31
-    {
32
-        return $this->element->validStatusOptions($constants_only);
33
-    }
8
+	/**
9
+	 * @var Element
10
+	 */
11
+	protected $element;
12
+
13
+	/**
14
+	 * @var array
15
+	 */
16
+	protected $valid_status_options;
17
+
18
+
19
+	protected function __construct(Element $element, $timezone)
20
+	{
21
+		$this->element = $element;
22
+		parent::__construct($timezone);
23
+	}
24
+
25
+
26
+	/**
27
+	 * @param bool $constants_only
28
+	 * @return array
29
+	 */
30
+	public function validStatusOptions(bool $constants_only = false): array
31
+	{
32
+		return $this->element->validStatusOptions($constants_only);
33
+	}
34 34
 }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Boolean_Field.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -2,62 +2,62 @@
 block discarded – undo
2 2
 
3 3
 class EE_Boolean_Field extends EE_Integer_Field
4 4
 {
5
-    /**
6
-     * @param string $table_column
7
-     * @param string $nicename
8
-     * @param bool   $nullable
9
-     * @param null   $default_value
10
-     */
11
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
12
-    {
13
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
14
-        $this->setSchemaType('boolean');
15
-    }
5
+	/**
6
+	 * @param string $table_column
7
+	 * @param string $nicename
8
+	 * @param bool   $nullable
9
+	 * @param null   $default_value
10
+	 */
11
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
12
+	{
13
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
14
+		$this->setSchemaType('boolean');
15
+	}
16 16
 
17
-    /**
18
-     * Double-checks the value being returned is an boolean.
19
-     * @since 4.9.74.p
20
-     * @param mixed $value_of_field_on_model_object
21
-     * @return boolean
22
-     */
23
-    public function prepare_for_get($value_of_field_on_model_object)
24
-    {
25
-        return (bool) parent::prepare_for_get($value_of_field_on_model_object);
26
-    }
17
+	/**
18
+	 * Double-checks the value being returned is an boolean.
19
+	 * @since 4.9.74.p
20
+	 * @param mixed $value_of_field_on_model_object
21
+	 * @return boolean
22
+	 */
23
+	public function prepare_for_get($value_of_field_on_model_object)
24
+	{
25
+		return (bool) parent::prepare_for_get($value_of_field_on_model_object);
26
+	}
27 27
 
28
-    /**
29
-     * @since 4.9.74.p
30
-     * @param $value_inputted_for_field_on_model_object
31
-     * @return boolean
32
-     */
33
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
34
-    {
35
-        return filter_var($value_inputted_for_field_on_model_object, FILTER_VALIDATE_BOOLEAN);
36
-    }
28
+	/**
29
+	 * @since 4.9.74.p
30
+	 * @param $value_inputted_for_field_on_model_object
31
+	 * @return boolean
32
+	 */
33
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
34
+	{
35
+		return filter_var($value_inputted_for_field_on_model_object, FILTER_VALIDATE_BOOLEAN);
36
+	}
37 37
 
38
-    /**
39
-     * Make sure we're returning booleans
40
-     *
41
-     * @param string $value_inputted_for_field_on_model_object
42
-     * @return boolean
43
-     */
44
-    public function prepare_for_set_from_db($value_inputted_for_field_on_model_object)
45
-    {
46
-        return filter_var($value_inputted_for_field_on_model_object, FILTER_VALIDATE_BOOLEAN);
47
-    }
38
+	/**
39
+	 * Make sure we're returning booleans
40
+	 *
41
+	 * @param string $value_inputted_for_field_on_model_object
42
+	 * @return boolean
43
+	 */
44
+	public function prepare_for_set_from_db($value_inputted_for_field_on_model_object)
45
+	{
46
+		return filter_var($value_inputted_for_field_on_model_object, FILTER_VALIDATE_BOOLEAN);
47
+	}
48 48
 
49
-    /**
50
-     * Gets a nice Yes/No value for this field
51
-     *
52
-     * @param boolean $value_on_field_to_be_outputted
53
-     * @return string Yes or No
54
-     */
55
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted)
56
-    {
57
-        return apply_filters(
58
-            'FHEE__EE_Boolean_Field__prepare_for_pretty_echoing__return',
59
-            $value_on_field_to_be_outputted ? __('Yes', 'event_espresso') : __('No', 'event_espresso'),
60
-            $value_on_field_to_be_outputted
61
-        );
62
-    }
49
+	/**
50
+	 * Gets a nice Yes/No value for this field
51
+	 *
52
+	 * @param boolean $value_on_field_to_be_outputted
53
+	 * @return string Yes or No
54
+	 */
55
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted)
56
+	{
57
+		return apply_filters(
58
+			'FHEE__EE_Boolean_Field__prepare_for_pretty_echoing__return',
59
+			$value_on_field_to_be_outputted ? __('Yes', 'event_espresso') : __('No', 'event_espresso'),
60
+			$value_on_field_to_be_outputted
61
+		);
62
+	}
63 63
 }
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 1 patch
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -13,132 +13,132 @@
 block discarded – undo
13 13
 class EEM_WP_User extends EEM_Base
14 14
 {
15 15
 
16
-    /**
17
-     * private instance of the EEM_WP_User object
18
-     *
19
-     * @type EEM_WP_User
20
-     */
21
-    protected static $_instance;
16
+	/**
17
+	 * private instance of the EEM_WP_User object
18
+	 *
19
+	 * @type EEM_WP_User
20
+	 */
21
+	protected static $_instance;
22 22
 
23 23
 
24
-    /**
25
-     *    constructor
26
-     *
27
-     * @param null              $timezone
28
-     * @param ModelFieldFactory $model_field_factory
29
-     * @throws EE_Error
30
-     * @throws InvalidArgumentException
31
-     */
32
-    protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
33
-    {
34
-        $this->singular_item = esc_html__('WP_User', 'event_espresso');
35
-        $this->plural_item = esc_html__('WP_Users', 'event_espresso');
36
-        global $wpdb;
37
-        $this->_tables = array(
38
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
39
-        );
40
-        $this->_fields = array(
41
-            'WP_User' => array(
42
-                'ID'                  => $model_field_factory->createPrimaryKeyIntField(
43
-                    'ID',
44
-                    esc_html__('WP_User ID', 'event_espresso')
45
-                ),
46
-                'user_login'          => $model_field_factory->createPlainTextField(
47
-                    'user_login',
48
-                    esc_html__('User Login', 'event_espresso'),
49
-                    false
50
-                ),
51
-                'user_pass'           => $model_field_factory->createPlainTextField(
52
-                    'user_pass',
53
-                    esc_html__('User Password', 'event_espresso'),
54
-                    false
55
-                ),
56
-                'user_nicename'       => $model_field_factory->createPlainTextField(
57
-                    'user_nicename',
58
-                    esc_html__(' User Nice Name', 'event_espresso'),
59
-                    false
60
-                ),
61
-                'user_email'          => $model_field_factory->createEmailField(
62
-                    'user_email',
63
-                    esc_html__('User Email', 'event_espresso'),
64
-                    false
65
-                ),
66
-                'user_registered'     => $model_field_factory->createDatetimeField(
67
-                    'user_registered',
68
-                    esc_html__('Date User Registered', 'event_espresso'),
69
-                    $timezone
70
-                ),
71
-                'user_activation_key' => $model_field_factory->createPlainTextField(
72
-                    'user_activation_key',
73
-                    esc_html__('User Activation Key', 'event_espresso'),
74
-                    false
75
-                ),
76
-                'user_status'         => $model_field_factory->createIntegerField(
77
-                    'user_status',
78
-                    esc_html__('User Status', 'event_espresso')
79
-                ),
80
-                'display_name'        => $model_field_factory->createPlainTextField(
81
-                    'display_name',
82
-                    esc_html__('Display Name', 'event_espresso'),
83
-                    false
84
-                ),
85
-            ),
86
-        );
87
-        $this->_model_relations = array(
88
-            'Attendee'       => new EE_Has_Many_Relation(),
89
-            // all models are related to the change log
90
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
91
-            'Event'          => new EE_Has_Many_Relation(),
92
-            'Message'        => new EE_Has_Many_Relation(),
93
-            'Payment_Method' => new EE_Has_Many_Relation(),
94
-            'Price'          => new EE_Has_Many_Relation(),
95
-            'Price_Type'     => new EE_Has_Many_Relation(),
96
-            'Question'       => new EE_Has_Many_Relation(),
97
-            'Question_Group' => new EE_Has_Many_Relation(),
98
-            'Ticket'         => new EE_Has_Many_Relation(),
99
-            'Venue'          => new EE_Has_Many_Relation(),
100
-        );
101
-        $this->foreign_key_aliases = [
102
-            'Event.EVT_wp_user'          => 'WP_User.ID',
103
-            'Payment_Method.PMD_wp_user' => 'WP_User.ID',
104
-            'Price.PRC_wp_user'          => 'WP_User.ID',
105
-            'Price_Type.PRT_wp_user'     => 'WP_User.ID',
106
-            'Question.QST_wp_user'       => 'WP_User.ID',
107
-            'Question_Group.QSG_wp_user' => 'WP_User.ID',
108
-            'Ticket.VNU_wp_user'         => 'WP_User.ID',
109
-            'Venue.TKT_wp_user'          => 'WP_User.ID',
110
-        ];
111
-        $this->_wp_core_model = true;
112
-        $this->_caps_slug = 'users';
113
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
114
-        $this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
115
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
116
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
117
-        }
118
-        // @todo: account for create_users controls whether they can create users at all
119
-        parent::__construct($timezone);
120
-    }
24
+	/**
25
+	 *    constructor
26
+	 *
27
+	 * @param null              $timezone
28
+	 * @param ModelFieldFactory $model_field_factory
29
+	 * @throws EE_Error
30
+	 * @throws InvalidArgumentException
31
+	 */
32
+	protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
33
+	{
34
+		$this->singular_item = esc_html__('WP_User', 'event_espresso');
35
+		$this->plural_item = esc_html__('WP_Users', 'event_espresso');
36
+		global $wpdb;
37
+		$this->_tables = array(
38
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
39
+		);
40
+		$this->_fields = array(
41
+			'WP_User' => array(
42
+				'ID'                  => $model_field_factory->createPrimaryKeyIntField(
43
+					'ID',
44
+					esc_html__('WP_User ID', 'event_espresso')
45
+				),
46
+				'user_login'          => $model_field_factory->createPlainTextField(
47
+					'user_login',
48
+					esc_html__('User Login', 'event_espresso'),
49
+					false
50
+				),
51
+				'user_pass'           => $model_field_factory->createPlainTextField(
52
+					'user_pass',
53
+					esc_html__('User Password', 'event_espresso'),
54
+					false
55
+				),
56
+				'user_nicename'       => $model_field_factory->createPlainTextField(
57
+					'user_nicename',
58
+					esc_html__(' User Nice Name', 'event_espresso'),
59
+					false
60
+				),
61
+				'user_email'          => $model_field_factory->createEmailField(
62
+					'user_email',
63
+					esc_html__('User Email', 'event_espresso'),
64
+					false
65
+				),
66
+				'user_registered'     => $model_field_factory->createDatetimeField(
67
+					'user_registered',
68
+					esc_html__('Date User Registered', 'event_espresso'),
69
+					$timezone
70
+				),
71
+				'user_activation_key' => $model_field_factory->createPlainTextField(
72
+					'user_activation_key',
73
+					esc_html__('User Activation Key', 'event_espresso'),
74
+					false
75
+				),
76
+				'user_status'         => $model_field_factory->createIntegerField(
77
+					'user_status',
78
+					esc_html__('User Status', 'event_espresso')
79
+				),
80
+				'display_name'        => $model_field_factory->createPlainTextField(
81
+					'display_name',
82
+					esc_html__('Display Name', 'event_espresso'),
83
+					false
84
+				),
85
+			),
86
+		);
87
+		$this->_model_relations = array(
88
+			'Attendee'       => new EE_Has_Many_Relation(),
89
+			// all models are related to the change log
90
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
91
+			'Event'          => new EE_Has_Many_Relation(),
92
+			'Message'        => new EE_Has_Many_Relation(),
93
+			'Payment_Method' => new EE_Has_Many_Relation(),
94
+			'Price'          => new EE_Has_Many_Relation(),
95
+			'Price_Type'     => new EE_Has_Many_Relation(),
96
+			'Question'       => new EE_Has_Many_Relation(),
97
+			'Question_Group' => new EE_Has_Many_Relation(),
98
+			'Ticket'         => new EE_Has_Many_Relation(),
99
+			'Venue'          => new EE_Has_Many_Relation(),
100
+		);
101
+		$this->foreign_key_aliases = [
102
+			'Event.EVT_wp_user'          => 'WP_User.ID',
103
+			'Payment_Method.PMD_wp_user' => 'WP_User.ID',
104
+			'Price.PRC_wp_user'          => 'WP_User.ID',
105
+			'Price_Type.PRT_wp_user'     => 'WP_User.ID',
106
+			'Question.QST_wp_user'       => 'WP_User.ID',
107
+			'Question_Group.QSG_wp_user' => 'WP_User.ID',
108
+			'Ticket.VNU_wp_user'         => 'WP_User.ID',
109
+			'Venue.TKT_wp_user'          => 'WP_User.ID',
110
+		];
111
+		$this->_wp_core_model = true;
112
+		$this->_caps_slug = 'users';
113
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read ] = 'list';
114
+		$this->_cap_contexts_to_cap_action_map[ EEM_Base::caps_read_admin ] = 'list';
115
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
116
+			$this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_WP_User();
117
+		}
118
+		// @todo: account for create_users controls whether they can create users at all
119
+		parent::__construct($timezone);
120
+	}
121 121
 
122 122
 
123
-    /**
124
-     * We don't need a foreign key to the WP_User model, we just need its primary key
125
-     *
126
-     * @return string
127
-     * @throws EE_Error
128
-     */
129
-    public function wp_user_field_name()
130
-    {
131
-        return $this->primary_key_name();
132
-    }
123
+	/**
124
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
125
+	 *
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 */
129
+	public function wp_user_field_name()
130
+	{
131
+		return $this->primary_key_name();
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
-     *
138
-     * @return boolean
139
-     */
140
-    public function is_owned()
141
-    {
142
-        return true;
143
-    }
135
+	/**
136
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
137
+	 *
138
+	 * @return boolean
139
+	 */
140
+	public function is_owned()
141
+	{
142
+		return true;
143
+	}
144 144
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6528 added lines, -6528 removed lines patch added patch discarded remove patch
@@ -40,6534 +40,6534 @@
 block discarded – undo
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42 42
 
43
-    /**
44
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
-     * They almost always WILL NOT, but it's not necessarily a requirement.
47
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
-     *
49
-     * @var boolean
50
-     */
51
-    private $_values_already_prepared_by_model_object = 0;
52
-
53
-    /**
54
-     * when $_values_already_prepared_by_model_object equals this, we assume
55
-     * the data is just like form input that needs to have the model fields'
56
-     * prepare_for_set and prepare_for_use_in_db called on it
57
-     */
58
-    const not_prepared_by_model_object = 0;
59
-
60
-    /**
61
-     * when $_values_already_prepared_by_model_object equals this, we
62
-     * assume this value is coming from a model object and doesn't need to have
63
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
64
-     */
65
-    const prepared_by_model_object = 1;
66
-
67
-    /**
68
-     * when $_values_already_prepared_by_model_object equals this, we assume
69
-     * the values are already to be used in the database (ie no processing is done
70
-     * on them by the model's fields)
71
-     */
72
-    const prepared_for_use_in_db = 2;
73
-
74
-
75
-    protected $singular_item = 'Item';
76
-
77
-    protected $plural_item   = 'Items';
78
-
79
-    /**
80
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
-     */
82
-    protected $_tables;
83
-
84
-    /**
85
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
-     *
89
-     * @var EE_Model_Field_Base[][] $_fields
90
-     */
91
-    protected $_fields;
92
-
93
-    /**
94
-     * array of different kinds of relations
95
-     *
96
-     * @var EE_Model_Relation_Base[] $_model_relations
97
-     */
98
-    protected $_model_relations = [];
99
-
100
-    /**
101
-     * @var EE_Index[] $_indexes
102
-     */
103
-    protected $_indexes = array();
104
-
105
-    /**
106
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
107
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
-     * by setting the same columns as used in these queries in the query yourself.
109
-     *
110
-     * @var EE_Default_Where_Conditions
111
-     */
112
-    protected $_default_where_conditions_strategy;
113
-
114
-    /**
115
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
-     * This is particularly useful when you want something between 'none' and 'default'
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_minimum_where_conditions_strategy;
121
-
122
-    /**
123
-     * String describing how to find the "owner" of this model's objects.
124
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
-     * But when there isn't, this indicates which related model, or transiently-related model,
126
-     * has the foreign key to the wp_users table.
127
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
-     * related to events, and events have a foreign key to wp_users.
129
-     * On EEM_Transaction, this would be 'Transaction.Event'
130
-     *
131
-     * @var string
132
-     */
133
-    protected $_model_chain_to_wp_user = '';
134
-
135
-    /**
136
-     * String describing how to find the model with a password controlling access to this model. This property has the
137
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
-     * This value is the path of models to follow to arrive at the model with the password field.
139
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
-     * model with a password that should affect reading this on the front-end.
141
-     * Eg this is an empty string for the Event model because it has a password.
142
-     * This is null for the Registration model, because its event's password has no bearing on whether
143
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
-     * should hide tickets for datetimes for events that have a password set.
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = array(
178
-        self::caps_read       => array(),
179
-        self::caps_read_admin => array(),
180
-        self::caps_edit       => array(),
181
-        self::caps_delete     => array(),
182
-    );
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = array();
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = array(
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    );
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = array();
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     * @var boolean
298
-     */
299
-    protected $_wp_core_model = false;
300
-
301
-    /**
302
-     * @var bool stores whether this model has a password field or not.
303
-     * null until initialized by hasPasswordField()
304
-     */
305
-    protected $has_password_field;
306
-
307
-    /**
308
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
-     */
310
-    protected $password_field;
311
-
312
-    /**
313
-     *    List of valid operators that can be used for querying.
314
-     * The keys are all operators we'll accept, the values are the real SQL
315
-     * operators used
316
-     *
317
-     * @var array
318
-     */
319
-    protected $_valid_operators = array(
320
-        '='           => '=',
321
-        '<='          => '<=',
322
-        '<'           => '<',
323
-        '>='          => '>=',
324
-        '>'           => '>',
325
-        '!='          => '!=',
326
-        'LIKE'        => 'LIKE',
327
-        'like'        => 'LIKE',
328
-        'NOT_LIKE'    => 'NOT LIKE',
329
-        'not_like'    => 'NOT LIKE',
330
-        'NOT LIKE'    => 'NOT LIKE',
331
-        'not like'    => 'NOT LIKE',
332
-        'IN'          => 'IN',
333
-        'in'          => 'IN',
334
-        'NOT_IN'      => 'NOT IN',
335
-        'not_in'      => 'NOT IN',
336
-        'NOT IN'      => 'NOT IN',
337
-        'not in'      => 'NOT IN',
338
-        'between'     => 'BETWEEN',
339
-        'BETWEEN'     => 'BETWEEN',
340
-        'IS_NOT_NULL' => 'IS NOT NULL',
341
-        'is_not_null' => 'IS NOT NULL',
342
-        'IS NOT NULL' => 'IS NOT NULL',
343
-        'is not null' => 'IS NOT NULL',
344
-        'IS_NULL'     => 'IS NULL',
345
-        'is_null'     => 'IS NULL',
346
-        'IS NULL'     => 'IS NULL',
347
-        'is null'     => 'IS NULL',
348
-        'REGEXP'      => 'REGEXP',
349
-        'regexp'      => 'REGEXP',
350
-        'NOT_REGEXP'  => 'NOT REGEXP',
351
-        'not_regexp'  => 'NOT REGEXP',
352
-        'NOT REGEXP'  => 'NOT REGEXP',
353
-        'not regexp'  => 'NOT REGEXP',
354
-    );
355
-
356
-    /**
357
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
-     *
359
-     * @var array
360
-     */
361
-    protected $_in_style_operators = array('IN', 'NOT IN');
362
-
363
-    /**
364
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
-     * '12-31-2012'"
366
-     *
367
-     * @var array
368
-     */
369
-    protected $_between_style_operators = array('BETWEEN');
370
-
371
-    /**
372
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
-    /**
377
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
-     * on a join table.
379
-     *
380
-     * @var array
381
-     */
382
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
-
384
-    /**
385
-     * Allowed values for $query_params['order'] for ordering in queries
386
-     *
387
-     * @var array
388
-     */
389
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
-
391
-    /**
392
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
394
-     *
395
-     * @var array
396
-     */
397
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
-
399
-    /**
400
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
402
-     *
403
-     * @var array
404
-     */
405
-    private $_allowed_query_params = array(
406
-        0,
407
-        'limit',
408
-        'order_by',
409
-        'group_by',
410
-        'having',
411
-        'force_join',
412
-        'order',
413
-        'on_join_limit',
414
-        'default_where_conditions',
415
-        'caps',
416
-        'extra_selects',
417
-        'exclude_protected',
418
-    );
419
-
420
-    /**
421
-     * All the data types that can be used in $wpdb->prepare statements.
422
-     *
423
-     * @var array
424
-     */
425
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
-
427
-    /**
428
-     * @var EE_Registry $EE
429
-     */
430
-    protected $EE = null;
431
-
432
-
433
-    /**
434
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
-     *
436
-     * @var int
437
-     */
438
-    protected $_show_next_x_db_queries = 0;
439
-
440
-    /**
441
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
-     * WHERE, GROUP_BY, etc.
444
-     *
445
-     * @var CustomSelects
446
-     */
447
-    protected $_custom_selections = array();
448
-
449
-    /**
450
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
-     * caches every model object we've fetched from the DB on this request
452
-     *
453
-     * @var array
454
-     */
455
-    protected $_entity_map;
456
-
457
-    /**
458
-     * @var LoaderInterface
459
-     */
460
-    private static $loader;
461
-
462
-    /**
463
-     * @var Mirror
464
-     */
465
-    private static $mirror;
466
-
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-
547
-    /**
548
-     * About all child constructors:
549
-     * they should define the _tables, _fields and _model_relations arrays.
550
-     * Should ALWAYS be called after child constructor.
551
-     * In order to make the child constructors to be as simple as possible, this parent constructor
552
-     * finalizes constructing all the object's attributes.
553
-     * Generally, rather than requiring a child to code
554
-     * $this->_tables = array(
555
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
-     *        ...);
557
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
-     * each EE_Table has a function to set the table's alias after the constructor, using
559
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
-     * do something similar.
561
-     *
562
-     * @param null $timezone
563
-     * @throws EE_Error
564
-     */
565
-    protected function __construct($timezone = null)
566
-    {
567
-        // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
-            throw new EE_Error(
570
-                sprintf(
571
-                    __(
572
-                        '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.',
573
-                        'event_espresso'
574
-                    ),
575
-                    get_class($this)
576
-                )
577
-            );
578
-        }
579
-        /**
580
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
-         */
582
-        if (empty(EEM_Base::$_model_query_blog_id)) {
583
-            EEM_Base::set_model_query_blog_id();
584
-        }
585
-        /**
586
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
-         * just use EE_Register_Model_Extension
588
-         *
589
-         * @var EE_Table_Base[] $_tables
590
-         */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
-        foreach ($this->_tables as $table_alias => $table_obj) {
593
-            /** @var $table_obj EE_Table_Base */
594
-            $table_obj->_construct_finalize_with_alias($table_alias);
595
-            if ($table_obj instanceof EE_Secondary_Table) {
596
-                /** @var $table_obj EE_Secondary_Table */
597
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
-            }
599
-        }
600
-        /**
601
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
-         * EE_Register_Model_Extension
603
-         *
604
-         * @param EE_Model_Field_Base[] $_fields
605
-         */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
-        $this->_invalidate_field_caches();
608
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
610
-                throw new EE_Error(sprintf(__(
611
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
-                    'event_espresso'
613
-                ), $table_alias, implode(",", $this->_fields)));
614
-            }
615
-            foreach ($fields_for_table as $field_name => $field_obj) {
616
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
-                // primary key field base has a slightly different _construct_finalize
618
-                /** @var $field_obj EE_Model_Field_Base */
619
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
-            }
621
-        }
622
-        // everything is related to Extra_Meta
623
-        if (get_class($this) !== 'EEM_Extra_Meta') {
624
-            // make extra meta related to everything, but don't block deleting things just
625
-            // because they have related extra meta info. For now just orphan those extra meta
626
-            // in the future we should automatically delete them
627
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
-        }
629
-        // and change logs
630
-        if (get_class($this) !== 'EEM_Change_Log') {
631
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
-        }
633
-        /**
634
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
-         * EE_Register_Model_Extension
636
-         *
637
-         * @param EE_Model_Relation_Base[] $_model_relations
638
-         */
639
-        $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
641
-            $this->_model_relations
642
-        );
643
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
644
-            /** @var $relation_obj EE_Model_Relation_Base */
645
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
-        }
647
-        foreach ($this->_indexes as $index_name => $index_obj) {
648
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
-        }
650
-        $this->set_timezone($timezone);
651
-        // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
653
-            // nothing was set during child constructor, so set default
654
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
-        }
656
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
663
-        // to indicate to NOT set it, set it to the logical default
664
-        if ($this->_caps_slug === null) {
665
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
-        }
667
-        // initialize the standard cap restriction generators if none were specified by the child constructor
668
-        if (is_array($this->_cap_restriction_generators)) {
669
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
-                        new EE_Restriction_Generator_Protected(),
674
-                        $cap_context,
675
-                        $this
676
-                    );
677
-                }
678
-            }
679
-        }
680
-        // if there are cap restriction generators, use them to make the default cap restrictions
681
-        if (is_array($this->_cap_restriction_generators)) {
682
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
684
-                    continue;
685
-                }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
-                    throw new EE_Error(
688
-                        sprintf(
689
-                            __(
690
-                                '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.',
691
-                                'event_espresso'
692
-                            ),
693
-                            $context,
694
-                            $this->get_this_model_name()
695
-                        )
696
-                    );
697
-                }
698
-                $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
700
-                    $generator_object->_construct_finalize($this, $action);
701
-                }
702
-            }
703
-        }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
705
-    }
706
-
707
-
708
-    /**
709
-     * @return LoaderInterface
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     */
714
-    protected static function getLoader(): LoaderInterface
715
-    {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
717
-            EEM_Base::$loader = LoaderFactory::getLoader();
718
-        }
719
-        return EEM_Base::$loader;
720
-    }
721
-
722
-
723
-    /**
724
-     * @return Mirror
725
-     * @since   $VID:$
726
-     */
727
-    private static function getMirror(): Mirror
728
-    {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
730
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
-        }
732
-        return EEM_Base::$mirror;
733
-    }
734
-
735
-
736
-    /**
737
-     * @param string $model_class_Name
738
-     * @param string $timezone
739
-     * @return array
740
-     * @throws ReflectionException
741
-     * @since   $VID:$
742
-     */
743
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
744
-    {
745
-        $arguments = [$timezone];
746
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
-        if (count($params) > 1) {
748
-            if ($params[1]->getName() === 'model_field_factory') {
749
-                $arguments = [
750
-                    $timezone,
751
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
-                ];
753
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
754
-                $arguments = [
755
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
756
-                    $timezone
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Input') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
761
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
-                    $timezone
763
-                ];
764
-            }
765
-        }
766
-        return $arguments;
767
-    }
768
-
769
-
770
-    /**
771
-     * This function is a singleton method used to instantiate the Espresso_model object
772
-     *
773
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
-     *                                (and any incoming timezone data that gets saved).
775
-     *                                Note this just sends the timezone info to the date time model field objects.
776
-     *                                Default is NULL
777
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
-     * @return static (as in the concrete child class)
779
-     * @throws EE_Error
780
-     * @throws ReflectionException
781
-     */
782
-    public static function instance($timezone = null)
783
-    {
784
-        // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
786
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
-            $model = new static(...$arguments);
788
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
-            static::$_instance = $model;
790
-        }
791
-        // we might have a timezone set, let set_timezone decide what to do with it
792
-        if ($timezone){
793
-            static::$_instance->set_timezone($timezone);
794
-        }
795
-        // Espresso_model object
796
-        return static::$_instance;
797
-    }
798
-
799
-
800
-
801
-    /**
802
-     * resets the model and returns it
803
-     *
804
-     * @param string|null $timezone
805
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
-     * all its properties reset; if it wasn't instantiated, returns null)
807
-     * @throws EE_Error
808
-     * @throws ReflectionException
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidDataTypeException
811
-     * @throws InvalidInterfaceException
812
-     */
813
-    public static function reset($timezone = null)
814
-    {
815
-        if (! static::$_instance instanceof EEM_Base) {
816
-            return null;
817
-        }
818
-        // Let's NOT swap out the current instance for a new one
819
-        // because if someone has a reference to it, we can't remove their reference.
820
-        // It's best to keep using the same reference but change the original object instead,
821
-        // so reset all its properties to their original values as defined in the class.
822
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
-            // don't set instance to null like it was originally,
825
-            // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
827
-                static::$_instance->{$property} = $value;
828
-            }
829
-        }
830
-        // and then directly call its constructor again, like we would if we were creating a new one
831
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
-        static::$_instance->__construct(...$arguments);
833
-        return self::instance();
834
-    }
835
-
836
-
837
-    /**
838
-     * Used to set the $_model_query_blog_id static property.
839
-     *
840
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
-     *                      value for get_current_blog_id() will be used.
842
-     */
843
-    public static function set_model_query_blog_id($blog_id = 0)
844
-    {
845
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
846
-            ? (int) $blog_id
847
-            : get_current_blog_id();
848
-    }
849
-
850
-
851
-    /**
852
-     * Returns whatever is set as the internal $model_query_blog_id.
853
-     *
854
-     * @return int
855
-     */
856
-    public static function get_model_query_blog_id()
857
-    {
858
-        return EEM_Base::$_model_query_blog_id;
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
-     *
866
-     * @param  boolean $translated return localized strings or JUST the array.
867
-     * @return array
868
-     * @throws EE_Error
869
-     * @throws InvalidArgumentException
870
-     * @throws InvalidDataTypeException
871
-     * @throws InvalidInterfaceException
872
-     */
873
-    public function status_array($translated = false)
874
-    {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
876
-            return array();
877
-        }
878
-        $model_name = $this->get_this_model_name();
879
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
-        $status_array = array();
882
-        foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
884
-        }
885
-        return $translated
886
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
-            : $status_array;
888
-    }
889
-
890
-
891
-
892
-    /**
893
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
-     *
895
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
-     *                             or if you have the development copy of EE you can view this at the path:
897
-     *                             /docs/G--Model-System/model-query-params.md
898
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
-     *                                        array( array(
903
-     *                                        'OR'=>array(
904
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
-     *                                        )
907
-     *                                        ),
908
-     *                                        'limit'=>10,
909
-     *                                        'group_by'=>'TXN_ID'
910
-     *                                        ));
911
-     *                                        get all the answers to the question titled "shirt size" for event with id
912
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
-     *                                        'Question.QST_display_text'=>'shirt size',
914
-     *                                        'Registration.Event.EVT_ID'=>12
915
-     *                                        ),
916
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
917
-     *                                        ));
918
-     * @throws EE_Error
919
-     */
920
-    public function get_all($query_params = array())
921
-    {
922
-        if (
923
-            isset($query_params['limit'])
924
-            && ! isset($query_params['group_by'])
925
-        ) {
926
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
-        }
928
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * Modifies the query parameters so we only get back model objects
935
-     * that "belong" to the current user
936
-     *
937
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
-     */
940
-    public function alter_query_params_to_only_include_mine($query_params = array())
941
-    {
942
-        $wp_user_field_name = $this->wp_user_field_name();
943
-        if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
-        }
946
-        return $query_params;
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Returns the name of the field's name that points to the WP_User table
953
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
-     * foreign key to the WP_User table)
955
-     *
956
-     * @return string|boolean string on success, boolean false when there is no
957
-     * foreign key to the WP_User table
958
-     */
959
-    public function wp_user_field_name()
960
-    {
961
-        try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
963
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
-                $last_model_name = end($models_to_follow_to_wp_users);
965
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
-            } else {
968
-                $model_with_fk_to_wp_users = $this;
969
-                $model_chain_to_wp_user = '';
970
-            }
971
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
973
-        } catch (EE_Error $e) {
974
-            return false;
975
-        }
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
982
-     * (or transiently-related model) has a foreign key to the wp_users table;
983
-     * useful for finding if model objects of this type are 'owned' by the current user.
984
-     * This is an empty string when the foreign key is on this model and when it isn't,
985
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
986
-     * (or transiently-related model)
987
-     *
988
-     * @return string
989
-     */
990
-    public function model_chain_to_wp_user()
991
-    {
992
-        return $this->_model_chain_to_wp_user;
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
-     * like how registrations don't have a foreign key to wp_users, but the
1000
-     * events they are for are), or is unrelated to wp users.
1001
-     * generally available
1002
-     *
1003
-     * @return boolean
1004
-     */
1005
-    public function is_owned()
1006
-    {
1007
-        if ($this->model_chain_to_wp_user()) {
1008
-            return true;
1009
-        }
1010
-        try {
1011
-            $this->get_foreign_key_to('WP_User');
1012
-            return true;
1013
-        } catch (EE_Error $e) {
1014
-            return false;
1015
-        }
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
-     * the model)
1023
-     *
1024
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1028
-     *                                  override this and set the select to "*", or a specific column name, like
1029
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
-     *                                  the aliases used to refer to this selection, and values are to be
1032
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
-     * @throws EE_Error
1036
-     * @throws InvalidArgumentException
1037
-     */
1038
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
-    {
1040
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
-        ;
1042
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
-        $select_expressions = $columns_to_select === null
1044
-            ? $this->_construct_default_select_sql($model_query_info)
1045
-            : '';
1046
-        if ($this->_custom_selections instanceof CustomSelects) {
1047
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048
-            $select_expressions .= $select_expressions
1049
-                ? ', ' . $custom_expressions
1050
-                : $custom_expressions;
1051
-        }
1052
-
1053
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1054
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1060
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1061
-     * method of including extra select information.
1062
-     *
1063
-     * @param array             $query_params
1064
-     * @param null|array|string $columns_to_select
1065
-     * @return null|CustomSelects
1066
-     * @throws InvalidArgumentException
1067
-     */
1068
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069
-    {
1070
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071
-            return null;
1072
-        }
1073
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1074
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1075
-        return new CustomSelects($selects);
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1082
-     * but you can use the model query params to more easily
1083
-     * take care of joins, field preparation etc.
1084
-     *
1085
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1086
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1087
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1088
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1089
-     *                                  override this and set the select to "*", or a specific column name, like
1090
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1091
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1092
-     *                                  the aliases used to refer to this selection, and values are to be
1093
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1094
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1095
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1096
-     * @throws EE_Error
1097
-     */
1098
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1099
-    {
1100
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * For creating a custom select statement
1107
-     *
1108
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
-     *                                 SQL, and 1=>is the datatype
1111
-     * @throws EE_Error
1112
-     * @return string
1113
-     */
1114
-    private function _construct_select_from_input($columns_to_select)
1115
-    {
1116
-        if (is_array($columns_to_select)) {
1117
-            $select_sql_array = array();
1118
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
-                    throw new EE_Error(
1121
-                        sprintf(
1122
-                            __(
1123
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
-                                'event_espresso'
1125
-                            ),
1126
-                            $selection_and_datatype,
1127
-                            $alias
1128
-                        )
1129
-                    );
1130
-                }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype[1],
1139
-                            $selection_and_datatype[0],
1140
-                            $alias,
1141
-                            implode(', ', $this->_valid_wpdb_data_types)
1142
-                        )
1143
-                    );
1144
-                }
1145
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
-            }
1147
-            $columns_to_select_string = implode(', ', $select_sql_array);
1148
-        } else {
1149
-            $columns_to_select_string = $columns_to_select;
1150
-        }
1151
-        return $columns_to_select_string;
1152
-    }
1153
-
1154
-
1155
-
1156
-    /**
1157
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1158
-     *
1159
-     * @return string
1160
-     * @throws EE_Error
1161
-     */
1162
-    public function primary_key_name()
1163
-    {
1164
-        return $this->get_primary_key_field()->get_name();
1165
-    }
1166
-
1167
-
1168
-    /**
1169
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
-     * If there is no primary key on this model, $id is treated as primary key string
1171
-     *
1172
-     * @param mixed $id int or string, depending on the type of the model's primary key
1173
-     * @return EE_Base_Class
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_one_by_ID($id)
1177
-    {
1178
-        if ($this->get_from_entity_map($id)) {
1179
-            return $this->get_from_entity_map($id);
1180
-        }
1181
-        $model_object = $this->get_one(
1182
-            $this->alter_query_params_to_restrict_by_ID(
1183
-                $id,
1184
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1185
-            )
1186
-        );
1187
-        $className = $this->_get_class_name();
1188
-        if ($model_object instanceof $className) {
1189
-            // make sure valid objects get added to the entity map
1190
-            // so that the next call to this method doesn't trigger another trip to the db
1191
-            $this->add_to_entity_map($model_object);
1192
-        }
1193
-        return $model_object;
1194
-    }
1195
-
1196
-
1197
-
1198
-    /**
1199
-     * Alters query parameters to only get items with this ID are returned.
1200
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1201
-     * or could just be a simple primary key ID
1202
-     *
1203
-     * @param int   $id
1204
-     * @param array $query_params
1205
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1206
-     * @throws EE_Error
1207
-     */
1208
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209
-    {
1210
-        if (! isset($query_params[0])) {
1211
-            $query_params[0] = array();
1212
-        }
1213
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1214
-        if ($conditions_from_id === null) {
1215
-            $query_params[0][ $this->primary_key_name() ] = $id;
1216
-        } else {
1217
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1218
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1219
-        }
1220
-        return $query_params;
1221
-    }
1222
-
1223
-
1224
-
1225
-    /**
1226
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1227
-     * array. If no item is found, null is returned.
1228
-     *
1229
-     * @param array $query_params like EEM_Base's $query_params variable.
1230
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1231
-     * @throws EE_Error
1232
-     */
1233
-    public function get_one($query_params = array())
1234
-    {
1235
-        if (! is_array($query_params)) {
1236
-            EE_Error::doing_it_wrong(
1237
-                'EEM_Base::get_one',
1238
-                sprintf(
1239
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1240
-                    gettype($query_params)
1241
-                ),
1242
-                '4.6.0'
1243
-            );
1244
-            $query_params = array();
1245
-        }
1246
-        $query_params['limit'] = 1;
1247
-        $items = $this->get_all($query_params);
1248
-        if (empty($items)) {
1249
-            return null;
1250
-        }
1251
-        return array_shift($items);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the next x number of items in sequence from the given value as
1258
-     * found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function next_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive(
1280
-            $current_field_value,
1281
-            '>',
1282
-            $field_to_order_by,
1283
-            $limit,
1284
-            $query_params,
1285
-            $columns_to_select
1286
-        );
1287
-    }
1288
-
1289
-
1290
-
1291
-    /**
1292
-     * Returns the previous x number of items in sequence from the given value
1293
-     * as found in the database matching the given query conditions.
1294
-     *
1295
-     * @param mixed $current_field_value    Value used for the reference point.
1296
-     * @param null  $field_to_order_by      What field is used for the
1297
-     *                                      reference point.
1298
-     * @param int   $limit                  How many to return.
1299
-     * @param array $query_params           Extra conditions on the query.
1300
-     * @param null  $columns_to_select      If left null, then an array of
1301
-     *                                      EE_Base_Class objects is returned,
1302
-     *                                      otherwise you can indicate just the
1303
-     *                                      columns you want returned.
1304
-     * @return EE_Base_Class[]|array
1305
-     * @throws EE_Error
1306
-     */
1307
-    public function previous_x(
1308
-        $current_field_value,
1309
-        $field_to_order_by = null,
1310
-        $limit = 1,
1311
-        $query_params = array(),
1312
-        $columns_to_select = null
1313
-    ) {
1314
-        return $this->_get_consecutive(
1315
-            $current_field_value,
1316
-            '<',
1317
-            $field_to_order_by,
1318
-            $limit,
1319
-            $query_params,
1320
-            $columns_to_select
1321
-        );
1322
-    }
1323
-
1324
-
1325
-
1326
-    /**
1327
-     * Returns the next item in sequence from the given value as found in the
1328
-     * database matching the given query conditions.
1329
-     *
1330
-     * @param mixed $current_field_value    Value used for the reference point.
1331
-     * @param null  $field_to_order_by      What field is used for the
1332
-     *                                      reference point.
1333
-     * @param array $query_params           Extra conditions on the query.
1334
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1335
-     *                                      object is returned, otherwise you
1336
-     *                                      can indicate just the columns you
1337
-     *                                      want and a single array indexed by
1338
-     *                                      the columns will be returned.
1339
-     * @return EE_Base_Class|null|array()
1340
-     * @throws EE_Error
1341
-     */
1342
-    public function next(
1343
-        $current_field_value,
1344
-        $field_to_order_by = null,
1345
-        $query_params = array(),
1346
-        $columns_to_select = null
1347
-    ) {
1348
-        $results = $this->_get_consecutive(
1349
-            $current_field_value,
1350
-            '>',
1351
-            $field_to_order_by,
1352
-            1,
1353
-            $query_params,
1354
-            $columns_to_select
1355
-        );
1356
-        return empty($results) ? null : reset($results);
1357
-    }
1358
-
1359
-
1360
-
1361
-    /**
1362
-     * Returns the previous item in sequence from the given value as found in
1363
-     * the database matching the given query conditions.
1364
-     *
1365
-     * @param mixed $current_field_value    Value used for the reference point.
1366
-     * @param null  $field_to_order_by      What field is used for the
1367
-     *                                      reference point.
1368
-     * @param array $query_params           Extra conditions on the query.
1369
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
-     *                                      object is returned, otherwise you
1371
-     *                                      can indicate just the columns you
1372
-     *                                      want and a single array indexed by
1373
-     *                                      the columns will be returned.
1374
-     * @return EE_Base_Class|null|array()
1375
-     * @throws EE_Error
1376
-     */
1377
-    public function previous(
1378
-        $current_field_value,
1379
-        $field_to_order_by = null,
1380
-        $query_params = array(),
1381
-        $columns_to_select = null
1382
-    ) {
1383
-        $results = $this->_get_consecutive(
1384
-            $current_field_value,
1385
-            '<',
1386
-            $field_to_order_by,
1387
-            1,
1388
-            $query_params,
1389
-            $columns_to_select
1390
-        );
1391
-        return empty($results) ? null : reset($results);
1392
-    }
1393
-
1394
-
1395
-
1396
-    /**
1397
-     * Returns the a consecutive number of items in sequence from the given
1398
-     * value as found in the database matching the given query conditions.
1399
-     *
1400
-     * @param mixed  $current_field_value   Value used for the reference point.
1401
-     * @param string $operand               What operand is used for the sequence.
1402
-     * @param string $field_to_order_by     What field is used for the reference point.
1403
-     * @param int    $limit                 How many to return.
1404
-     * @param array  $query_params          Extra conditions on the query.
1405
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1406
-     *                                      otherwise you can indicate just the columns you want returned.
1407
-     * @return EE_Base_Class[]|array
1408
-     * @throws EE_Error
1409
-     */
1410
-    protected function _get_consecutive(
1411
-        $current_field_value,
1412
-        $operand = '>',
1413
-        $field_to_order_by = null,
1414
-        $limit = 1,
1415
-        $query_params = array(),
1416
-        $columns_to_select = null
1417
-    ) {
1418
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1419
-        if (empty($field_to_order_by)) {
1420
-            if ($this->has_primary_key_field()) {
1421
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1422
-            } else {
1423
-                if (WP_DEBUG) {
1424
-                    throw new EE_Error(__(
1425
-                        '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).',
1426
-                        'event_espresso'
1427
-                    ));
1428
-                }
1429
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1430
-                return array();
1431
-            }
1432
-        }
1433
-        if (! is_array($query_params)) {
1434
-            EE_Error::doing_it_wrong(
1435
-                'EEM_Base::_get_consecutive',
1436
-                sprintf(
1437
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1438
-                    gettype($query_params)
1439
-                ),
1440
-                '4.6.0'
1441
-            );
1442
-            $query_params = array();
1443
-        }
1444
-        // let's add the where query param for consecutive look up.
1445
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1446
-        $query_params['limit'] = $limit;
1447
-        // set direction
1448
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1449
-        $query_params['order_by'] = $operand === '>'
1450
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1451
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1452
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1453
-        if (empty($columns_to_select)) {
1454
-            return $this->get_all($query_params);
1455
-        }
1456
-        // getting just the fields
1457
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This sets the _timezone property after model object has been instantiated.
1464
-     *
1465
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1466
-     */
1467
-    public function set_timezone($timezone)
1468
-    {
1469
-        if ($timezone !== null) {
1470
-            $this->_timezone = $timezone;
1471
-        }
1472
-        // note we need to loop through relations and set the timezone on those objects as well.
1473
-        foreach ($this->_model_relations as $relation) {
1474
-            $relation->set_timezone($timezone);
1475
-        }
1476
-        // and finally we do the same for any datetime fields
1477
-        foreach ($this->_fields as $field) {
1478
-            if ($field instanceof EE_Datetime_Field) {
1479
-                $field->set_timezone($timezone);
1480
-            }
1481
-        }
1482
-    }
1483
-
1484
-
1485
-
1486
-    /**
1487
-     * This just returns whatever is set for the current timezone.
1488
-     *
1489
-     * @access public
1490
-     * @return string
1491
-     */
1492
-    public function get_timezone()
1493
-    {
1494
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1495
-        if (empty($this->_timezone)) {
1496
-            foreach ($this->_fields as $field) {
1497
-                if ($field instanceof EE_Datetime_Field) {
1498
-                    $this->set_timezone($field->get_timezone());
1499
-                    break;
1500
-                }
1501
-            }
1502
-        }
1503
-        // if timezone STILL empty then return the default timezone for the site.
1504
-        if (empty($this->_timezone)) {
1505
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1506
-        }
1507
-        return $this->_timezone;
1508
-    }
1509
-
1510
-
1511
-
1512
-    /**
1513
-     * This returns the date formats set for the given field name and also ensures that
1514
-     * $this->_timezone property is set correctly.
1515
-     *
1516
-     * @since 4.6.x
1517
-     * @param string $field_name The name of the field the formats are being retrieved for.
1518
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1519
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1520
-     * @return array formats in an array with the date format first, and the time format last.
1521
-     */
1522
-    public function get_formats_for($field_name, $pretty = false)
1523
-    {
1524
-        $field_settings = $this->field_settings_for($field_name);
1525
-        // if not a valid EE_Datetime_Field then throw error
1526
-        if (! $field_settings instanceof EE_Datetime_Field) {
1527
-            throw new EE_Error(sprintf(__(
1528
-                '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.',
1529
-                'event_espresso'
1530
-            ), $field_name));
1531
-        }
1532
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
-        // the field.
1534
-        $this->_timezone = $field_settings->get_timezone();
1535
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1536
-    }
1537
-
1538
-
1539
-
1540
-    /**
1541
-     * This returns the current time in a format setup for a query on this model.
1542
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1543
-     * it will return:
1544
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1545
-     *  NOW
1546
-     *  - or a unix timestamp (equivalent to time())
1547
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1548
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1549
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1550
-     * @since 4.6.x
1551
-     * @param string $field_name       The field the current time is needed for.
1552
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1553
-     *                                 formatted string matching the set format for the field in the set timezone will
1554
-     *                                 be returned.
1555
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1556
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1557
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1558
-     *                                 exception is triggered.
1559
-     */
1560
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
-    {
1562
-        $formats = $this->get_formats_for($field_name);
1563
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
-        if ($timestamp) {
1565
-            return $DateTime->format('U');
1566
-        }
1567
-        // not returning timestamp, so return formatted string in timezone.
1568
-        switch ($what) {
1569
-            case 'time':
1570
-                return $DateTime->format($formats[1]);
1571
-                break;
1572
-            case 'date':
1573
-                return $DateTime->format($formats[0]);
1574
-                break;
1575
-            default:
1576
-                return $DateTime->format(implode(' ', $formats));
1577
-                break;
1578
-        }
1579
-    }
1580
-
1581
-
1582
-
1583
-    /**
1584
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1585
-     * for the model are.  Returns a DateTime object.
1586
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1587
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1588
-     * ignored.
1589
-     *
1590
-     * @param string $field_name      The field being setup.
1591
-     * @param string $timestring      The date time string being used.
1592
-     * @param string $incoming_format The format for the time string.
1593
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1594
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1595
-     *                                format is
1596
-     *                                'U', this is ignored.
1597
-     * @return DateTime
1598
-     * @throws EE_Error
1599
-     */
1600
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1601
-    {
1602
-        // just using this to ensure the timezone is set correctly internally
1603
-        $this->get_formats_for($field_name);
1604
-        // load EEH_DTT_Helper
1605
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1606
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1607
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1608
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1609
-    }
1610
-
1611
-
1612
-
1613
-    /**
1614
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1615
-     *
1616
-     * @return EE_Table_Base[]
1617
-     */
1618
-    public function get_tables()
1619
-    {
1620
-        return $this->_tables;
1621
-    }
1622
-
1623
-
1624
-
1625
-    /**
1626
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1627
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1628
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1629
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1630
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1631
-     * model object with EVT_ID = 1
1632
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1633
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1634
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1635
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1636
-     * are not specified)
1637
-     *
1638
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1639
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1640
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1641
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1642
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1643
-     *                                         ID=34, we'd use this method as follows:
1644
-     *                                         EEM_Transaction::instance()->update(
1645
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1646
-     *                                         array(array('TXN_ID'=>34)));
1647
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1648
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1649
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
-     *                                         TRUE, it is assumed that you've already called
1654
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
-     *                                         malicious javascript. However, if
1656
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
-     *                                         and every other field, before insertion. We provide this parameter
1659
-     *                                         because model objects perform their prepare_for_set function on all
1660
-     *                                         their values, and so don't need to be called again (and in many cases,
1661
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
-     *                                         prepare_for_set method...)
1663
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
-     *                                         in this model's entity map according to $fields_n_values that match
1665
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1666
-     *                                         by setting this to FALSE, but be aware that model objects being used
1667
-     *                                         could get out-of-sync with the database
1668
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
-     *                                         bad)
1671
-     * @throws EE_Error
1672
-     */
1673
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
-    {
1675
-        if (! is_array($query_params)) {
1676
-            EE_Error::doing_it_wrong(
1677
-                'EEM_Base::update',
1678
-                sprintf(
1679
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1680
-                    gettype($query_params)
1681
-                ),
1682
-                '4.6.0'
1683
-            );
1684
-            $query_params = array();
1685
-        }
1686
-        /**
1687
-         * Action called before a model update call has been made.
1688
-         *
1689
-         * @param EEM_Base $model
1690
-         * @param array    $fields_n_values the updated fields and their new values
1691
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1692
-         */
1693
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1694
-        /**
1695
-         * Filters the fields about to be updated given the query parameters. You can provide the
1696
-         * $query_params to $this->get_all() to find exactly which records will be updated
1697
-         *
1698
-         * @param array    $fields_n_values fields and their new values
1699
-         * @param EEM_Base $model           the model being queried
1700
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1701
-         */
1702
-        $fields_n_values = (array) apply_filters(
1703
-            'FHEE__EEM_Base__update__fields_n_values',
1704
-            $fields_n_values,
1705
-            $this,
1706
-            $query_params
1707
-        );
1708
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1709
-        // to do that, for each table, verify that it's PK isn't null.
1710
-        $tables = $this->get_tables();
1711
-        // 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
1712
-        // NOTE: we should make this code more efficient by NOT querying twice
1713
-        // before the real update, but that needs to first go through ALPHA testing
1714
-        // as it's dangerous. says Mike August 8 2014
1715
-        // we want to make sure the default_where strategy is ignored
1716
-        $this->_ignore_where_strategy = true;
1717
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1718
-        foreach ($wpdb_select_results as $wpdb_result) {
1719
-            // type cast stdClass as array
1720
-            $wpdb_result = (array) $wpdb_result;
1721
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722
-            if ($this->has_primary_key_field()) {
1723
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1724
-            } else {
1725
-                // 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)
1726
-                $main_table_pk_value = null;
1727
-            }
1728
-            // 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
1729
-            // 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
1730
-            if (count($tables) > 1) {
1731
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1732
-                // in that table, and so we'll want to insert one
1733
-                foreach ($tables as $table_obj) {
1734
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1735
-                    // if there is no private key for this table on the results, it means there's no entry
1736
-                    // in this table, right? so insert a row in the current table, using any fields available
1737
-                    if (
1738
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
-                           && $wpdb_result[ $this_table_pk_column ])
1740
-                    ) {
1741
-                        $success = $this->_insert_into_specific_table(
1742
-                            $table_obj,
1743
-                            $fields_n_values,
1744
-                            $main_table_pk_value
1745
-                        );
1746
-                        // if we died here, report the error
1747
-                        if (! $success) {
1748
-                            return false;
1749
-                        }
1750
-                    }
1751
-                }
1752
-            }
1753
-            //              //and now check that if we have cached any models by that ID on the model, that
1754
-            //              //they also get updated properly
1755
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1756
-            //              if( $model_object ){
1757
-            //                  foreach( $fields_n_values as $field => $value ){
1758
-            //                      $model_object->set($field, $value);
1759
-            // let's make sure default_where strategy is followed now
1760
-            $this->_ignore_where_strategy = false;
1761
-        }
1762
-        // if we want to keep model objects in sync, AND
1763
-        // if this wasn't called from a model object (to update itself)
1764
-        // then we want to make sure we keep all the existing
1765
-        // model objects in sync with the db
1766
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1767
-            if ($this->has_primary_key_field()) {
1768
-                $model_objs_affected_ids = $this->get_col($query_params);
1769
-            } else {
1770
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1771
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1772
-                $model_objs_affected_ids = array();
1773
-                foreach ($models_affected_key_columns as $row) {
1774
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1775
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1776
-                }
1777
-            }
1778
-            if (! $model_objs_affected_ids) {
1779
-                // wait wait wait- if nothing was affected let's stop here
1780
-                return 0;
1781
-            }
1782
-            foreach ($model_objs_affected_ids as $id) {
1783
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1784
-                if ($model_obj_in_entity_map) {
1785
-                    foreach ($fields_n_values as $field => $new_value) {
1786
-                        $model_obj_in_entity_map->set($field, $new_value);
1787
-                    }
1788
-                }
1789
-            }
1790
-            // if there is a primary key on this model, we can now do a slight optimization
1791
-            if ($this->has_primary_key_field()) {
1792
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1793
-                $query_params = array(
1794
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1795
-                    'limit'                    => count($model_objs_affected_ids),
1796
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1797
-                );
1798
-            }
1799
-        }
1800
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1801
-        $SQL = "UPDATE "
1802
-               . $model_query_info->get_full_join_sql()
1803
-               . " SET "
1804
-               . $this->_construct_update_sql($fields_n_values)
1805
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807
-        /**
1808
-         * Action called after a model update call has been made.
1809
-         *
1810
-         * @param EEM_Base $model
1811
-         * @param array    $fields_n_values the updated fields and their new values
1812
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1813
-         * @param int      $rows_affected
1814
-         */
1815
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
-        return $rows_affected;// how many supposedly got updated
1817
-    }
1818
-
1819
-
1820
-
1821
-    /**
1822
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1823
-     * are teh values of the field specified (or by default the primary key field)
1824
-     * that matched the query params. Note that you should pass the name of the
1825
-     * model FIELD, not the database table's column name.
1826
-     *
1827
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
-     * @param string $field_to_select
1829
-     * @return array just like $wpdb->get_col()
1830
-     * @throws EE_Error
1831
-     */
1832
-    public function get_col($query_params = array(), $field_to_select = null)
1833
-    {
1834
-        if ($field_to_select) {
1835
-            $field = $this->field_settings_for($field_to_select);
1836
-        } elseif ($this->has_primary_key_field()) {
1837
-            $field = $this->get_primary_key_field();
1838
-        } else {
1839
-            // no primary key, just grab the first column
1840
-            $field = reset($this->field_settings());
1841
-        }
1842
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1843
-        $select_expressions = $field->get_qualified_column();
1844
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1845
-        return $this->_do_wpdb_query('get_col', array($SQL));
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Returns a single column value for a single row from the database
1852
-     *
1853
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1854
-     * @param string $field_to_select @see EEM_Base::get_col()
1855
-     * @return string
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function get_var($query_params = array(), $field_to_select = null)
1859
-    {
1860
-        $query_params['limit'] = 1;
1861
-        $col = $this->get_col($query_params, $field_to_select);
1862
-        if (! empty($col)) {
1863
-            return reset($col);
1864
-        }
1865
-        return null;
1866
-    }
1867
-
1868
-
1869
-
1870
-    /**
1871
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
-     * injection, but currently no further filtering is done
1874
-     *
1875
-     * @global      $wpdb
1876
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1877
-     *                               be updated to in the DB
1878
-     * @return string of SQL
1879
-     * @throws EE_Error
1880
-     */
1881
-    public function _construct_update_sql($fields_n_values)
1882
-    {
1883
-        /** @type WPDB $wpdb */
1884
-        global $wpdb;
1885
-        $cols_n_values = array();
1886
-        foreach ($fields_n_values as $field_name => $value) {
1887
-            $field_obj = $this->field_settings_for($field_name);
1888
-            // if the value is NULL, we want to assign the value to that.
1889
-            // wpdb->prepare doesn't really handle that properly
1890
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
-            $value_sql = $prepared_value === null ? 'NULL'
1892
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
-        }
1895
-        return implode(",", $cols_n_values);
1896
-    }
1897
-
1898
-
1899
-
1900
-    /**
1901
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
-     * Performs a HARD delete, meaning the database row should always be removed,
1903
-     * not just have a flag field on it switched
1904
-     * Wrapper for EEM_Base::delete_permanently()
1905
-     *
1906
-     * @param mixed $id
1907
-     * @param boolean $allow_blocking
1908
-     * @return int the number of rows deleted
1909
-     * @throws EE_Error
1910
-     */
1911
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1912
-    {
1913
-        return $this->delete_permanently(
1914
-            array(
1915
-                array($this->get_primary_key_field()->get_name() => $id),
1916
-                'limit' => 1,
1917
-            ),
1918
-            $allow_blocking
1919
-        );
1920
-    }
1921
-
1922
-
1923
-
1924
-    /**
1925
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1926
-     * Wrapper for EEM_Base::delete()
1927
-     *
1928
-     * @param mixed $id
1929
-     * @param boolean $allow_blocking
1930
-     * @return int the number of rows deleted
1931
-     * @throws EE_Error
1932
-     */
1933
-    public function delete_by_ID($id, $allow_blocking = true)
1934
-    {
1935
-        return $this->delete(
1936
-            array(
1937
-                array($this->get_primary_key_field()->get_name() => $id),
1938
-                'limit' => 1,
1939
-            ),
1940
-            $allow_blocking
1941
-        );
1942
-    }
1943
-
1944
-
1945
-
1946
-    /**
1947
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1948
-     * meaning if the model has a field that indicates its been "trashed" or
1949
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1950
-     *
1951
-     * @see EEM_Base::delete_permanently
1952
-     * @param array   $query_params
1953
-     * @param boolean $allow_blocking
1954
-     * @return int how many rows got deleted
1955
-     * @throws EE_Error
1956
-     */
1957
-    public function delete($query_params, $allow_blocking = true)
1958
-    {
1959
-        return $this->delete_permanently($query_params, $allow_blocking);
1960
-    }
1961
-
1962
-
1963
-
1964
-    /**
1965
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1966
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1967
-     * as archived, not actually deleted
1968
-     *
1969
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1970
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1971
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1972
-     *                                deletes regardless of other objects which may depend on it. Its generally
1973
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1974
-     *                                DB
1975
-     * @return int how many rows got deleted
1976
-     * @throws EE_Error
1977
-     */
1978
-    public function delete_permanently($query_params, $allow_blocking = true)
1979
-    {
1980
-        /**
1981
-         * Action called just before performing a real deletion query. You can use the
1982
-         * model and its $query_params to find exactly which items will be deleted
1983
-         *
1984
-         * @param EEM_Base $model
1985
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1986
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1987
-         *                                 to block (prevent) this deletion
1988
-         */
1989
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1990
-        // some MySQL databases may be running safe mode, which may restrict
1991
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1992
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1993
-        // to delete them
1994
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1995
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1996
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1997
-            $columns_and_ids_for_deleting
1998
-        );
1999
-        /**
2000
-         * Allows client code to act on the items being deleted before the query is actually executed.
2001
-         *
2002
-         * @param EEM_Base $this  The model instance being acted on.
2003
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2004
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
2005
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2006
-         *                                                  derived from the incoming query parameters.
2007
-         *                                                  @see details on the structure of this array in the phpdocs
2008
-         *                                                  for the `_get_ids_for_delete_method`
2009
-         *
2010
-         */
2011
-        do_action(
2012
-            'AHEE__EEM_Base__delete__before_query',
2013
-            $this,
2014
-            $query_params,
2015
-            $allow_blocking,
2016
-            $columns_and_ids_for_deleting
2017
-        );
2018
-        if ($deletion_where_query_part) {
2019
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2020
-            $table_aliases = array_keys($this->_tables);
2021
-            $SQL = "DELETE "
2022
-                   . implode(", ", $table_aliases)
2023
-                   . " FROM "
2024
-                   . $model_query_info->get_full_join_sql()
2025
-                   . " WHERE "
2026
-                   . $deletion_where_query_part;
2027
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2028
-        } else {
2029
-            $rows_deleted = 0;
2030
-        }
2031
-
2032
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2033
-        // there was no error with the delete query.
2034
-        if (
2035
-            $this->has_primary_key_field()
2036
-            && $rows_deleted !== false
2037
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2038
-        ) {
2039
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2040
-            foreach ($ids_for_removal as $id) {
2041
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2043
-                }
2044
-            }
2045
-
2046
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2047
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2048
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2049
-            // (although it is possible).
2050
-            // Note this can be skipped by using the provided filter and returning false.
2051
-            if (
2052
-                apply_filters(
2053
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2054
-                    ! $this instanceof EEM_Extra_Meta,
2055
-                    $this
2056
-                )
2057
-            ) {
2058
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2059
-                    0 => array(
2060
-                        'EXM_type' => $this->get_this_model_name(),
2061
-                        'OBJ_ID'   => array(
2062
-                            'IN',
2063
-                            $ids_for_removal
2064
-                        )
2065
-                    )
2066
-                ));
2067
-            }
2068
-        }
2069
-
2070
-        /**
2071
-         * Action called just after performing a real deletion query. Although at this point the
2072
-         * items should have been deleted
2073
-         *
2074
-         * @param EEM_Base $model
2075
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2076
-         * @param int      $rows_deleted
2077
-         */
2078
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
-        return $rows_deleted;// how many supposedly got deleted
2080
-    }
2081
-
2082
-
2083
-
2084
-    /**
2085
-     * Checks all the relations that throw error messages when there are blocking related objects
2086
-     * for related model objects. If there are any related model objects on those relations,
2087
-     * adds an EE_Error, and return true
2088
-     *
2089
-     * @param EE_Base_Class|int $this_model_obj_or_id
2090
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2091
-     *                                                 should be ignored when determining whether there are related
2092
-     *                                                 model objects which block this model object's deletion. Useful
2093
-     *                                                 if you know A is related to B and are considering deleting A,
2094
-     *                                                 but want to see if A has any other objects blocking its deletion
2095
-     *                                                 before removing the relation between A and B
2096
-     * @return boolean
2097
-     * @throws EE_Error
2098
-     */
2099
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2100
-    {
2101
-        // first, if $ignore_this_model_obj was supplied, get its model
2102
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2103
-            $ignored_model = $ignore_this_model_obj->get_model();
2104
-        } else {
2105
-            $ignored_model = null;
2106
-        }
2107
-        // now check all the relations of $this_model_obj_or_id and see if there
2108
-        // are any related model objects blocking it?
2109
-        $is_blocked = false;
2110
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2111
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2112
-                // if $ignore_this_model_obj was supplied, then for the query
2113
-                // on that model needs to be told to ignore $ignore_this_model_obj
2114
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2115
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2116
-                        array(
2117
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2118
-                                '!=',
2119
-                                $ignore_this_model_obj->ID(),
2120
-                            ),
2121
-                        ),
2122
-                    ));
2123
-                } else {
2124
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2125
-                }
2126
-                if ($related_model_objects) {
2127
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2128
-                    $is_blocked = true;
2129
-                }
2130
-            }
2131
-        }
2132
-        return $is_blocked;
2133
-    }
2134
-
2135
-
2136
-    /**
2137
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2138
-     * @param array $row_results_for_deleting
2139
-     * @param bool  $allow_blocking
2140
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2141
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2142
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2143
-     *                 deleted. Example:
2144
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2145
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2146
-     *                 where each element is a group of columns and values that get deleted. Example:
2147
-     *                      array(
2148
-     *                          0 => array(
2149
-     *                              'Term_Relationship.object_id' => 1
2150
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2151
-     *                          ),
2152
-     *                          1 => array(
2153
-     *                              'Term_Relationship.object_id' => 1
2154
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2155
-     *                          )
2156
-     *                      )
2157
-     * @throws EE_Error
2158
-     */
2159
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2160
-    {
2161
-        $ids_to_delete_indexed_by_column = array();
2162
-        if ($this->has_primary_key_field()) {
2163
-            $primary_table = $this->_get_main_table();
2164
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2165
-            $other_tables = $this->_get_other_tables();
2166
-            $ids_to_delete_indexed_by_column = $query = array();
2167
-            foreach ($row_results_for_deleting as $item_to_delete) {
2168
-                // before we mark this item for deletion,
2169
-                // make sure there's no related entities blocking its deletion (if we're checking)
2170
-                if (
2171
-                    $allow_blocking
2172
-                    && $this->delete_is_blocked_by_related_models(
2173
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2174
-                    )
2175
-                ) {
2176
-                    continue;
2177
-                }
2178
-                // primary table deletes
2179
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2182
-                }
2183
-            }
2184
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
-            $fields = $this->get_combined_primary_key_fields();
2186
-            foreach ($row_results_for_deleting as $item_to_delete) {
2187
-                $ids_to_delete_indexed_by_column_for_row = array();
2188
-                foreach ($fields as $cpk_field) {
2189
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2190
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2192
-                    }
2193
-                }
2194
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2195
-            }
2196
-        } else {
2197
-            // so there's no primary key and no combined key...
2198
-            // sorry, can't help you
2199
-            throw new EE_Error(
2200
-                sprintf(
2201
-                    __(
2202
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2203
-                        "event_espresso"
2204
-                    ),
2205
-                    get_class($this)
2206
-                )
2207
-            );
2208
-        }
2209
-        return $ids_to_delete_indexed_by_column;
2210
-    }
2211
-
2212
-
2213
-    /**
2214
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2215
-     * the corresponding query_part for the query performing the delete.
2216
-     *
2217
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2218
-     * @return string
2219
-     * @throws EE_Error
2220
-     */
2221
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2222
-    {
2223
-        $query_part = '';
2224
-        if (empty($ids_to_delete_indexed_by_column)) {
2225
-            return $query_part;
2226
-        } elseif ($this->has_primary_key_field()) {
2227
-            $query = array();
2228
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229
-                // make sure we have unique $ids
2230
-                $ids = array_unique($ids);
2231
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2232
-            }
2233
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2235
-            $ways_to_identify_a_row = array();
2236
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237
-                $values_for_each_combined_primary_key_for_a_row = array();
2238
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2240
-                }
2241
-                $ways_to_identify_a_row[] = '('
2242
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2243
-                                            . ')';
2244
-            }
2245
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2246
-        }
2247
-        return $query_part;
2248
-    }
2249
-
2250
-
2251
-
2252
-    /**
2253
-     * Gets the model field by the fully qualified name
2254
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2255
-     * @return EE_Model_Field_Base
2256
-     */
2257
-    public function get_field_by_column($qualified_column_name)
2258
-    {
2259
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2260
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2261
-                return $field_obj;
2262
-            }
2263
-        }
2264
-        throw new EE_Error(
2265
-            sprintf(
2266
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2267
-                $this->get_this_model_name(),
2268
-                $qualified_column_name
2269
-            )
2270
-        );
2271
-    }
2272
-
2273
-
2274
-
2275
-    /**
2276
-     * Count all the rows that match criteria the model query params.
2277
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2278
-     * column
2279
-     *
2280
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2281
-     * @param string $field_to_count field on model to count by (not column name)
2282
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2283
-     *                               that by the setting $distinct to TRUE;
2284
-     * @return int
2285
-     * @throws EE_Error
2286
-     */
2287
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2288
-    {
2289
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2290
-        if ($field_to_count) {
2291
-            $field_obj = $this->field_settings_for($field_to_count);
2292
-            $column_to_count = $field_obj->get_qualified_column();
2293
-        } elseif ($this->has_primary_key_field()) {
2294
-            $pk_field_obj = $this->get_primary_key_field();
2295
-            $column_to_count = $pk_field_obj->get_qualified_column();
2296
-        } else {
2297
-            // there's no primary key
2298
-            // if we're counting distinct items, and there's no primary key,
2299
-            // we need to list out the columns for distinction;
2300
-            // otherwise we can just use star
2301
-            if ($distinct) {
2302
-                $columns_to_use = array();
2303
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2304
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2305
-                }
2306
-                $column_to_count = implode(',', $columns_to_use);
2307
-            } else {
2308
-                $column_to_count = '*';
2309
-            }
2310
-        }
2311
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314
-    }
2315
-
2316
-
2317
-
2318
-    /**
2319
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2320
-     *
2321
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
-     * @param string $field_to_sum name of field (array key in $_fields array)
2323
-     * @return float
2324
-     * @throws EE_Error
2325
-     */
2326
-    public function sum($query_params, $field_to_sum = null)
2327
-    {
2328
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
-        if ($field_to_sum) {
2330
-            $field_obj = $this->field_settings_for($field_to_sum);
2331
-        } else {
2332
-            $field_obj = $this->get_primary_key_field();
2333
-        }
2334
-        $column_to_count = $field_obj->get_qualified_column();
2335
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2336
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337
-        $data_type = $field_obj->get_wpdb_data_type();
2338
-        if ($data_type === '%d' || $data_type === '%s') {
2339
-            return (float) $return_value;
2340
-        }
2341
-        // must be %f
2342
-        return (float) $return_value;
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Just calls the specified method on $wpdb with the given arguments
2349
-     * Consolidates a little extra error handling code
2350
-     *
2351
-     * @param string $wpdb_method
2352
-     * @param array  $arguments_to_provide
2353
-     * @throws EE_Error
2354
-     * @global wpdb  $wpdb
2355
-     * @return mixed
2356
-     */
2357
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
-    {
2359
-        // if we're in maintenance mode level 2, DON'T run any queries
2360
-        // because level 2 indicates the database needs updating and
2361
-        // is probably out of sync with the code
2362
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
-            throw new EE_Error(sprintf(__(
2364
-                "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.",
2365
-                "event_espresso"
2366
-            )));
2367
-        }
2368
-        /** @type WPDB $wpdb */
2369
-        global $wpdb;
2370
-        if (! method_exists($wpdb, $wpdb_method)) {
2371
-            throw new EE_Error(sprintf(__(
2372
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2373
-                'event_espresso'
2374
-            ), $wpdb_method));
2375
-        }
2376
-        if (WP_DEBUG) {
2377
-            $old_show_errors_value = $wpdb->show_errors;
2378
-            $wpdb->show_errors(false);
2379
-        }
2380
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2381
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2382
-        if (WP_DEBUG) {
2383
-            $wpdb->show_errors($old_show_errors_value);
2384
-            if (! empty($wpdb->last_error)) {
2385
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386
-            }
2387
-            if ($result === false) {
2388
-                throw new EE_Error(sprintf(__(
2389
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2390
-                    'event_espresso'
2391
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2392
-            }
2393
-        } elseif ($result === false) {
2394
-            EE_Error::add_error(
2395
-                sprintf(
2396
-                    __(
2397
-                        '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"',
2398
-                        'event_espresso'
2399
-                    ),
2400
-                    $wpdb_method,
2401
-                    var_export($arguments_to_provide, true),
2402
-                    $wpdb->last_error
2403
-                ),
2404
-                __FILE__,
2405
-                __FUNCTION__,
2406
-                __LINE__
2407
-            );
2408
-        }
2409
-        return $result;
2410
-    }
2411
-
2412
-
2413
-
2414
-    /**
2415
-     * Attempts to run the indicated WPDB method with the provided arguments,
2416
-     * and if there's an error tries to verify the DB is correct. Uses
2417
-     * the static property EEM_Base::$_db_verification_level to determine whether
2418
-     * we should try to fix the EE core db, the addons, or just give up
2419
-     *
2420
-     * @param string $wpdb_method
2421
-     * @param array  $arguments_to_provide
2422
-     * @return mixed
2423
-     */
2424
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2425
-    {
2426
-        /** @type WPDB $wpdb */
2427
-        global $wpdb;
2428
-        $wpdb->last_error = null;
2429
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2430
-        // was there an error running the query? but we don't care on new activations
2431
-        // (we're going to setup the DB anyway on new activations)
2432
-        if (
2433
-            ($result === false || ! empty($wpdb->last_error))
2434
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2435
-        ) {
2436
-            switch (EEM_Base::$_db_verification_level) {
2437
-                case EEM_Base::db_verified_none:
2438
-                    // let's double-check core's DB
2439
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2440
-                    break;
2441
-                case EEM_Base::db_verified_core:
2442
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2443
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2444
-                    break;
2445
-                case EEM_Base::db_verified_addons:
2446
-                    // ummmm... you in trouble
2447
-                    return $result;
2448
-                    break;
2449
-            }
2450
-            if (! empty($error_message)) {
2451
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452
-                trigger_error($error_message);
2453
-            }
2454
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2455
-        }
2456
-        return $result;
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Verifies the EE core database is up-to-date and records that we've done it on
2463
-     * EEM_Base::$_db_verification_level
2464
-     *
2465
-     * @param string $wpdb_method
2466
-     * @param array  $arguments_to_provide
2467
-     * @return string
2468
-     */
2469
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2470
-    {
2471
-        /** @type WPDB $wpdb */
2472
-        global $wpdb;
2473
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2474
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2475
-        $error_message = sprintf(
2476
-            __(
2477
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2478
-                'event_espresso'
2479
-            ),
2480
-            $wpdb->last_error,
2481
-            $wpdb_method,
2482
-            wp_json_encode($arguments_to_provide)
2483
-        );
2484
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2485
-        return $error_message;
2486
-    }
2487
-
2488
-
2489
-
2490
-    /**
2491
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2492
-     * EEM_Base::$_db_verification_level
2493
-     *
2494
-     * @param $wpdb_method
2495
-     * @param $arguments_to_provide
2496
-     * @return string
2497
-     */
2498
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2499
-    {
2500
-        /** @type WPDB $wpdb */
2501
-        global $wpdb;
2502
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2503
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2504
-        $error_message = sprintf(
2505
-            __(
2506
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2507
-                'event_espresso'
2508
-            ),
2509
-            $wpdb->last_error,
2510
-            $wpdb_method,
2511
-            wp_json_encode($arguments_to_provide)
2512
-        );
2513
-        EE_System::instance()->initialize_addons();
2514
-        return $error_message;
2515
-    }
2516
-
2517
-
2518
-
2519
-    /**
2520
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2521
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2522
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2523
-     * ..."
2524
-     *
2525
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2526
-     * @return string
2527
-     */
2528
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529
-    {
2530
-        return " FROM " . $model_query_info->get_full_join_sql() .
2531
-               $model_query_info->get_where_sql() .
2532
-               $model_query_info->get_group_by_sql() .
2533
-               $model_query_info->get_having_sql() .
2534
-               $model_query_info->get_order_by_sql() .
2535
-               $model_query_info->get_limit_sql();
2536
-    }
2537
-
2538
-
2539
-
2540
-    /**
2541
-     * Set to easily debug the next X queries ran from this model.
2542
-     *
2543
-     * @param int $count
2544
-     */
2545
-    public function show_next_x_db_queries($count = 1)
2546
-    {
2547
-        $this->_show_next_x_db_queries = $count;
2548
-    }
2549
-
2550
-
2551
-
2552
-    /**
2553
-     * @param $sql_query
2554
-     */
2555
-    public function show_db_query_if_previously_requested($sql_query)
2556
-    {
2557
-        if ($this->_show_next_x_db_queries > 0) {
2558
-            echo $sql_query;
2559
-            $this->_show_next_x_db_queries--;
2560
-        }
2561
-    }
2562
-
2563
-
2564
-
2565
-    /**
2566
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
-     * There are the 3 cases:
2568
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
-     * $otherModelObject has no ID, it is first saved.
2570
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
-     * has no ID, it is first saved.
2572
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
-     * join table
2575
-     *
2576
-     * @param        EE_Base_Class                     /int $thisModelObject
2577
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
-     * @param string $relationName                     , key in EEM_Base::_relations
2579
-     *                                                 an attendee to a group, you also want to specify which role they
2580
-     *                                                 will have in that group. So you would use this parameter to
2581
-     *                                                 specify array('role-column-name'=>'role-id')
2582
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
-     *                                                 to for relation to methods that allow you to further specify
2584
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
-     *                                                 because these will be inserted in any new rows created as well.
2587
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
-     * @throws EE_Error
2589
-     */
2590
-    public function add_relationship_to(
2591
-        $id_or_obj,
2592
-        $other_model_id_or_obj,
2593
-        $relationName,
2594
-        $extra_join_model_fields_n_values = array()
2595
-    ) {
2596
-        $relation_obj = $this->related_settings_for($relationName);
2597
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
-    }
2599
-
2600
-
2601
-
2602
-    /**
2603
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2604
-     * There are the 3 cases:
2605
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2606
-     * error
2607
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2608
-     * an error
2609
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2610
-     *
2611
-     * @param        EE_Base_Class /int $id_or_obj
2612
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2613
-     * @param string $relationName key in EEM_Base::_relations
2614
-     * @return boolean of success
2615
-     * @throws EE_Error
2616
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2617
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2618
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2619
-     *                             because these will be inserted in any new rows created as well.
2620
-     */
2621
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2622
-    {
2623
-        $relation_obj = $this->related_settings_for($relationName);
2624
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2625
-    }
2626
-
2627
-
2628
-
2629
-    /**
2630
-     * @param mixed           $id_or_obj
2631
-     * @param string          $relationName
2632
-     * @param array           $where_query_params
2633
-     * @param EE_Base_Class[] objects to which relations were removed
2634
-     * @return \EE_Base_Class[]
2635
-     * @throws EE_Error
2636
-     */
2637
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2638
-    {
2639
-        $relation_obj = $this->related_settings_for($relationName);
2640
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2641
-    }
2642
-
2643
-
2644
-
2645
-    /**
2646
-     * Gets all the related items of the specified $model_name, using $query_params.
2647
-     * Note: by default, we remove the "default query params"
2648
-     * because we want to get even deleted items etc.
2649
-     *
2650
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2651
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2652
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2653
-     * @return EE_Base_Class[]
2654
-     * @throws EE_Error
2655
-     */
2656
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2657
-    {
2658
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2659
-        $relation_settings = $this->related_settings_for($model_name);
2660
-        return $relation_settings->get_all_related($model_obj, $query_params);
2661
-    }
2662
-
2663
-
2664
-
2665
-    /**
2666
-     * Deletes all the model objects across the relation indicated by $model_name
2667
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2668
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2669
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2670
-     *
2671
-     * @param EE_Base_Class|int|string $id_or_obj
2672
-     * @param string                   $model_name
2673
-     * @param array                    $query_params
2674
-     * @return int how many deleted
2675
-     * @throws EE_Error
2676
-     */
2677
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2678
-    {
2679
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2680
-        $relation_settings = $this->related_settings_for($model_name);
2681
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * Hard deletes all the model objects across the relation indicated by $model_name
2688
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2689
-     * the model objects can't be hard deleted because of blocking related model objects,
2690
-     * just does a soft-delete on them instead.
2691
-     *
2692
-     * @param EE_Base_Class|int|string $id_or_obj
2693
-     * @param string                   $model_name
2694
-     * @param array                    $query_params
2695
-     * @return int how many deleted
2696
-     * @throws EE_Error
2697
-     */
2698
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2699
-    {
2700
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2701
-        $relation_settings = $this->related_settings_for($model_name);
2702
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2703
-    }
2704
-
2705
-
2706
-
2707
-    /**
2708
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2709
-     * unless otherwise specified in the $query_params
2710
-     *
2711
-     * @param        int             /EE_Base_Class $id_or_obj
2712
-     * @param string $model_name     like 'Event', or 'Registration'
2713
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2714
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2715
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2716
-     *                               that by the setting $distinct to TRUE;
2717
-     * @return int
2718
-     * @throws EE_Error
2719
-     */
2720
-    public function count_related(
2721
-        $id_or_obj,
2722
-        $model_name,
2723
-        $query_params = array(),
2724
-        $field_to_count = null,
2725
-        $distinct = false
2726
-    ) {
2727
-        $related_model = $this->get_related_model_obj($model_name);
2728
-        // we're just going to use the query params on the related model's normal get_all query,
2729
-        // except add a condition to say to match the current mod
2730
-        if (! isset($query_params['default_where_conditions'])) {
2731
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732
-        }
2733
-        $this_model_name = $this->get_this_model_name();
2734
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2736
-        return $related_model->count($query_params, $field_to_count, $distinct);
2737
-    }
2738
-
2739
-
2740
-
2741
-    /**
2742
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2743
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2744
-     *
2745
-     * @param        int           /EE_Base_Class $id_or_obj
2746
-     * @param string $model_name   like 'Event', or 'Registration'
2747
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2748
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2749
-     * @return float
2750
-     * @throws EE_Error
2751
-     */
2752
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753
-    {
2754
-        $related_model = $this->get_related_model_obj($model_name);
2755
-        if (! is_array($query_params)) {
2756
-            EE_Error::doing_it_wrong(
2757
-                'EEM_Base::sum_related',
2758
-                sprintf(
2759
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2760
-                    gettype($query_params)
2761
-                ),
2762
-                '4.6.0'
2763
-            );
2764
-            $query_params = array();
2765
-        }
2766
-        // we're just going to use the query params on the related model's normal get_all query,
2767
-        // except add a condition to say to match the current mod
2768
-        if (! isset($query_params['default_where_conditions'])) {
2769
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770
-        }
2771
-        $this_model_name = $this->get_this_model_name();
2772
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2774
-        return $related_model->sum($query_params, $field_to_sum);
2775
-    }
2776
-
2777
-
2778
-
2779
-    /**
2780
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2781
-     * $modelObject
2782
-     *
2783
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2784
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2785
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2786
-     * @return EE_Base_Class
2787
-     * @throws EE_Error
2788
-     */
2789
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2790
-    {
2791
-        $query_params['limit'] = 1;
2792
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2793
-        if ($results) {
2794
-            return array_shift($results);
2795
-        }
2796
-        return null;
2797
-    }
2798
-
2799
-
2800
-
2801
-    /**
2802
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2803
-     *
2804
-     * @return string
2805
-     */
2806
-    public function get_this_model_name()
2807
-    {
2808
-        return str_replace("EEM_", "", get_class($this));
2809
-    }
2810
-
2811
-
2812
-
2813
-    /**
2814
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2815
-     *
2816
-     * @return EE_Any_Foreign_Model_Name_Field
2817
-     * @throws EE_Error
2818
-     */
2819
-    public function get_field_containing_related_model_name()
2820
-    {
2821
-        foreach ($this->field_settings(true) as $field) {
2822
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2823
-                $field_with_model_name = $field;
2824
-            }
2825
-        }
2826
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2827
-            throw new EE_Error(sprintf(
2828
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829
-                $this->get_this_model_name()
2830
-            ));
2831
-        }
2832
-        return $field_with_model_name;
2833
-    }
2834
-
2835
-
2836
-
2837
-    /**
2838
-     * Inserts a new entry into the database, for each table.
2839
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2840
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2841
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2842
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2843
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2844
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2845
-     *
2846
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2847
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2848
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2849
-     *                              of EEM_Base)
2850
-     * @return int|string new primary key on main table that got inserted
2851
-     * @throws EE_Error
2852
-     */
2853
-    public function insert($field_n_values)
2854
-    {
2855
-        /**
2856
-         * Filters the fields and their values before inserting an item using the models
2857
-         *
2858
-         * @param array    $fields_n_values keys are the fields and values are their new values
2859
-         * @param EEM_Base $model           the model used
2860
-         */
2861
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2862
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2863
-            $main_table = $this->_get_main_table();
2864
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2865
-            if ($new_id !== false) {
2866
-                foreach ($this->_get_other_tables() as $other_table) {
2867
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2868
-                }
2869
-            }
2870
-            /**
2871
-             * Done just after attempting to insert a new model object
2872
-             *
2873
-             * @param EEM_Base   $model           used
2874
-             * @param array      $fields_n_values fields and their values
2875
-             * @param int|string the              ID of the newly-inserted model object
2876
-             */
2877
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2878
-            return $new_id;
2879
-        }
2880
-        return false;
2881
-    }
2882
-
2883
-
2884
-
2885
-    /**
2886
-     * Checks that the result would satisfy the unique indexes on this model
2887
-     *
2888
-     * @param array  $field_n_values
2889
-     * @param string $action
2890
-     * @return boolean
2891
-     * @throws EE_Error
2892
-     */
2893
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2894
-    {
2895
-        foreach ($this->unique_indexes() as $index_name => $index) {
2896
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2897
-            if ($this->exists(array($uniqueness_where_params))) {
2898
-                EE_Error::add_error(
2899
-                    sprintf(
2900
-                        __(
2901
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2902
-                            "event_espresso"
2903
-                        ),
2904
-                        $action,
2905
-                        $this->_get_class_name(),
2906
-                        $index_name,
2907
-                        implode(",", $index->field_names()),
2908
-                        http_build_query($uniqueness_where_params)
2909
-                    ),
2910
-                    __FILE__,
2911
-                    __FUNCTION__,
2912
-                    __LINE__
2913
-                );
2914
-                return false;
2915
-            }
2916
-        }
2917
-        return true;
2918
-    }
2919
-
2920
-
2921
-
2922
-    /**
2923
-     * Checks the database for an item that conflicts (ie, if this item were
2924
-     * saved to the DB would break some uniqueness requirement, like a primary key
2925
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2926
-     * can be either an EE_Base_Class or an array of fields n values
2927
-     *
2928
-     * @param EE_Base_Class|array $obj_or_fields_array
2929
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2930
-     *                                                 when looking for conflicts
2931
-     *                                                 (ie, if false, we ignore the model object's primary key
2932
-     *                                                 when finding "conflicts". If true, it's also considered).
2933
-     *                                                 Only works for INT primary key,
2934
-     *                                                 STRING primary keys cannot be ignored
2935
-     * @throws EE_Error
2936
-     * @return EE_Base_Class|array
2937
-     */
2938
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2939
-    {
2940
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2941
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2942
-        } elseif (is_array($obj_or_fields_array)) {
2943
-            $fields_n_values = $obj_or_fields_array;
2944
-        } else {
2945
-            throw new EE_Error(
2946
-                sprintf(
2947
-                    __(
2948
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2949
-                        "event_espresso"
2950
-                    ),
2951
-                    get_class($this),
2952
-                    $obj_or_fields_array
2953
-                )
2954
-            );
2955
-        }
2956
-        $query_params = array();
2957
-        if (
2958
-            $this->has_primary_key_field()
2959
-            && ($include_primary_key
2960
-                || $this->get_primary_key_field()
2961
-                   instanceof
2962
-                   EE_Primary_Key_String_Field)
2963
-            && isset($fields_n_values[ $this->primary_key_name() ])
2964
-        ) {
2965
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2966
-        }
2967
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2970
-        }
2971
-        // if there is nothing to base this search on, then we shouldn't find anything
2972
-        if (empty($query_params)) {
2973
-            return array();
2974
-        }
2975
-        return $this->get_one($query_params);
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * Like count, but is optimized and returns a boolean instead of an int
2982
-     *
2983
-     * @param array $query_params
2984
-     * @return boolean
2985
-     * @throws EE_Error
2986
-     */
2987
-    public function exists($query_params)
2988
-    {
2989
-        $query_params['limit'] = 1;
2990
-        return $this->count($query_params) > 0;
2991
-    }
2992
-
2993
-
2994
-
2995
-    /**
2996
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2997
-     *
2998
-     * @param int|string $id
2999
-     * @return boolean
3000
-     * @throws EE_Error
3001
-     */
3002
-    public function exists_by_ID($id)
3003
-    {
3004
-        return $this->exists(
3005
-            array(
3006
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3007
-                array(
3008
-                    $this->primary_key_name() => $id,
3009
-                ),
3010
-            )
3011
-        );
3012
-    }
3013
-
3014
-
3015
-
3016
-    /**
3017
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
-     * on the main table)
3021
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
-     * cases where we want to call it directly rather than via insert().
3023
-     *
3024
-     * @access   protected
3025
-     * @param EE_Table_Base $table
3026
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
-     *                                       float
3028
-     * @param int           $new_id          for now we assume only int keys
3029
-     * @throws EE_Error
3030
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3031
-     * @return int ID of new row inserted, or FALSE on failure
3032
-     */
3033
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
-    {
3035
-        global $wpdb;
3036
-        $insertion_col_n_values = array();
3037
-        $format_for_insertion = array();
3038
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3039
-        foreach ($fields_on_table as $field_name => $field_obj) {
3040
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
-            if ($field_obj->is_auto_increment()) {
3042
-                continue;
3043
-            }
3044
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
-            if ($prepared_value !== null) {
3047
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049
-            }
3050
-        }
3051
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3052
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3053
-            // so add the fk to the main table as a column
3054
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3056
-        }
3057
-        // insert the new entry
3058
-        $result = $this->_do_wpdb_query(
3059
-            'insert',
3060
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3061
-        );
3062
-        if ($result === false) {
3063
-            return false;
3064
-        }
3065
-        // ok, now what do we return for the ID of the newly-inserted thing?
3066
-        if ($this->has_primary_key_field()) {
3067
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3068
-                return $wpdb->insert_id;
3069
-            }
3070
-            // it's not an auto-increment primary key, so
3071
-            // it must have been supplied
3072
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3073
-        }
3074
-        // we can't return a  primary key because there is none. instead return
3075
-        // a unique string indicating this model
3076
-        return $this->get_index_primary_key_string($fields_n_values);
3077
-    }
3078
-
3079
-
3080
-
3081
-    /**
3082
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3083
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3084
-     * and there is no default, we pass it along. WPDB will take care of it)
3085
-     *
3086
-     * @param EE_Model_Field_Base $field_obj
3087
-     * @param array               $fields_n_values
3088
-     * @return mixed string|int|float depending on what the table column will be expecting
3089
-     * @throws EE_Error
3090
-     */
3091
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3092
-    {
3093
-        // if this field doesn't allow nullable, don't allow it
3094
-        if (
3095
-            ! $field_obj->is_nullable()
3096
-            && (
3097
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3098
-                || $fields_n_values[ $field_obj->get_name() ] === null
3099
-            )
3100
-        ) {
3101
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3102
-        }
3103
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
-            ? $fields_n_values[ $field_obj->get_name() ]
3105
-            : null;
3106
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107
-    }
3108
-
3109
-
3110
-
3111
-    /**
3112
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3113
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3114
-     * the field's prepare_for_set() method.
3115
-     *
3116
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3117
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3118
-     *                                   top of file)
3119
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3120
-     *                                   $value is a custom selection
3121
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3122
-     */
3123
-    private function _prepare_value_for_use_in_db($value, $field)
3124
-    {
3125
-        if ($field && $field instanceof EE_Model_Field_Base) {
3126
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3127
-            switch ($this->_values_already_prepared_by_model_object) {
3128
-                /** @noinspection PhpMissingBreakStatementInspection */
3129
-                case self::not_prepared_by_model_object:
3130
-                    $value = $field->prepare_for_set($value);
3131
-                // purposefully left out "return"
3132
-                case self::prepared_by_model_object:
3133
-                    /** @noinspection SuspiciousAssignmentsInspection */
3134
-                    $value = $field->prepare_for_use_in_db($value);
3135
-                case self::prepared_for_use_in_db:
3136
-                    // leave the value alone
3137
-            }
3138
-            return $value;
3139
-            // phpcs:enable
3140
-        }
3141
-        return $value;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * Returns the main table on this model
3148
-     *
3149
-     * @return EE_Primary_Table
3150
-     * @throws EE_Error
3151
-     */
3152
-    protected function _get_main_table()
3153
-    {
3154
-        foreach ($this->_tables as $table) {
3155
-            if ($table instanceof EE_Primary_Table) {
3156
-                return $table;
3157
-            }
3158
-        }
3159
-        throw new EE_Error(sprintf(__(
3160
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3161
-            'event_espresso'
3162
-        ), get_class($this)));
3163
-    }
3164
-
3165
-
3166
-
3167
-    /**
3168
-     * table
3169
-     * returns EE_Primary_Table table name
3170
-     *
3171
-     * @return string
3172
-     * @throws EE_Error
3173
-     */
3174
-    public function table()
3175
-    {
3176
-        return $this->_get_main_table()->get_table_name();
3177
-    }
3178
-
3179
-
3180
-
3181
-    /**
3182
-     * table
3183
-     * returns first EE_Secondary_Table table name
3184
-     *
3185
-     * @return string
3186
-     */
3187
-    public function second_table()
3188
-    {
3189
-        // grab second table from tables array
3190
-        $second_table = end($this->_tables);
3191
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3192
-    }
3193
-
3194
-
3195
-
3196
-    /**
3197
-     * get_table_obj_by_alias
3198
-     * returns table name given it's alias
3199
-     *
3200
-     * @param string $table_alias
3201
-     * @return EE_Primary_Table | EE_Secondary_Table
3202
-     */
3203
-    public function get_table_obj_by_alias($table_alias = '')
3204
-    {
3205
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3206
-    }
3207
-
3208
-
3209
-
3210
-    /**
3211
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3212
-     *
3213
-     * @return EE_Secondary_Table[]
3214
-     */
3215
-    protected function _get_other_tables()
3216
-    {
3217
-        $other_tables = array();
3218
-        foreach ($this->_tables as $table_alias => $table) {
3219
-            if ($table instanceof EE_Secondary_Table) {
3220
-                $other_tables[ $table_alias ] = $table;
3221
-            }
3222
-        }
3223
-        return $other_tables;
3224
-    }
3225
-
3226
-
3227
-
3228
-    /**
3229
-     * Finds all the fields that correspond to the given table
3230
-     *
3231
-     * @param string $table_alias , array key in EEM_Base::_tables
3232
-     * @return EE_Model_Field_Base[]
3233
-     */
3234
-    public function _get_fields_for_table($table_alias)
3235
-    {
3236
-        return $this->_fields[ $table_alias ];
3237
-    }
3238
-
3239
-
3240
-
3241
-    /**
3242
-     * Recurses through all the where parameters, and finds all the related models we'll need
3243
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3244
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3245
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3246
-     * related Registration, Transaction, and Payment models.
3247
-     *
3248
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3249
-     * @return EE_Model_Query_Info_Carrier
3250
-     * @throws EE_Error
3251
-     */
3252
-    public function _extract_related_models_from_query($query_params)
3253
-    {
3254
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3255
-        if (array_key_exists(0, $query_params)) {
3256
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3257
-        }
3258
-        if (array_key_exists('group_by', $query_params)) {
3259
-            if (is_array($query_params['group_by'])) {
3260
-                $this->_extract_related_models_from_sub_params_array_values(
3261
-                    $query_params['group_by'],
3262
-                    $query_info_carrier,
3263
-                    'group_by'
3264
-                );
3265
-            } elseif (! empty($query_params['group_by'])) {
3266
-                $this->_extract_related_model_info_from_query_param(
3267
-                    $query_params['group_by'],
3268
-                    $query_info_carrier,
3269
-                    'group_by'
3270
-                );
3271
-            }
3272
-        }
3273
-        if (array_key_exists('having', $query_params)) {
3274
-            $this->_extract_related_models_from_sub_params_array_keys(
3275
-                $query_params[0],
3276
-                $query_info_carrier,
3277
-                'having'
3278
-            );
3279
-        }
3280
-        if (array_key_exists('order_by', $query_params)) {
3281
-            if (is_array($query_params['order_by'])) {
3282
-                $this->_extract_related_models_from_sub_params_array_keys(
3283
-                    $query_params['order_by'],
3284
-                    $query_info_carrier,
3285
-                    'order_by'
3286
-                );
3287
-            } elseif (! empty($query_params['order_by'])) {
3288
-                $this->_extract_related_model_info_from_query_param(
3289
-                    $query_params['order_by'],
3290
-                    $query_info_carrier,
3291
-                    'order_by'
3292
-                );
3293
-            }
3294
-        }
3295
-        if (array_key_exists('force_join', $query_params)) {
3296
-            $this->_extract_related_models_from_sub_params_array_values(
3297
-                $query_params['force_join'],
3298
-                $query_info_carrier,
3299
-                'force_join'
3300
-            );
3301
-        }
3302
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3303
-        return $query_info_carrier;
3304
-    }
3305
-
3306
-
3307
-
3308
-    /**
3309
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3310
-     *
3311
-     * @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
3312
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3313
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3314
-     * @throws EE_Error
3315
-     * @return \EE_Model_Query_Info_Carrier
3316
-     */
3317
-    private function _extract_related_models_from_sub_params_array_keys(
3318
-        $sub_query_params,
3319
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320
-        $query_param_type
3321
-    ) {
3322
-        if (! empty($sub_query_params)) {
3323
-            $sub_query_params = (array) $sub_query_params;
3324
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3326
-                $this->_extract_related_model_info_from_query_param(
3327
-                    $param,
3328
-                    $model_query_info_carrier,
3329
-                    $query_param_type
3330
-                );
3331
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3332
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3333
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3334
-                // of array('Registration.TXN_ID'=>23)
3335
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
-                    if (! is_array($possibly_array_of_params)) {
3338
-                        throw new EE_Error(sprintf(
3339
-                            __(
3340
-                                "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'))",
3341
-                                "event_espresso"
3342
-                            ),
3343
-                            $param,
3344
-                            $possibly_array_of_params
3345
-                        ));
3346
-                    }
3347
-                    $this->_extract_related_models_from_sub_params_array_keys(
3348
-                        $possibly_array_of_params,
3349
-                        $model_query_info_carrier,
3350
-                        $query_param_type
3351
-                    );
3352
-                } elseif (
3353
-                    $query_param_type === 0 // ie WHERE
3354
-                          && is_array($possibly_array_of_params)
3355
-                          && isset($possibly_array_of_params[2])
3356
-                          && $possibly_array_of_params[2] == true
3357
-                ) {
3358
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3360
-                    // from which we should extract query parameters!
3361
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362
-                        throw new EE_Error(sprintf(__(
3363
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364
-                            "event_espresso"
3365
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3366
-                    }
3367
-                    $this->_extract_related_model_info_from_query_param(
3368
-                        $possibly_array_of_params[1],
3369
-                        $model_query_info_carrier,
3370
-                        $query_param_type
3371
-                    );
3372
-                }
3373
-            }
3374
-        }
3375
-        return $model_query_info_carrier;
3376
-    }
3377
-
3378
-
3379
-
3380
-    /**
3381
-     * For extracting related models from forced_joins, where the array values contain the info about what
3382
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3383
-     *
3384
-     * @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
3385
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3386
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3387
-     * @throws EE_Error
3388
-     * @return \EE_Model_Query_Info_Carrier
3389
-     */
3390
-    private function _extract_related_models_from_sub_params_array_values(
3391
-        $sub_query_params,
3392
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393
-        $query_param_type
3394
-    ) {
3395
-        if (! empty($sub_query_params)) {
3396
-            if (! is_array($sub_query_params)) {
3397
-                throw new EE_Error(sprintf(
3398
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
-                    $sub_query_params
3400
-                ));
3401
-            }
3402
-            foreach ($sub_query_params as $param) {
3403
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
-                $this->_extract_related_model_info_from_query_param(
3405
-                    $param,
3406
-                    $model_query_info_carrier,
3407
-                    $query_param_type
3408
-                );
3409
-            }
3410
-        }
3411
-        return $model_query_info_carrier;
3412
-    }
3413
-
3414
-
3415
-    /**
3416
-     * Extract all the query parts from  model query params
3417
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
-     * but use them in a different order. Eg, we need to know what models we are querying
3420
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
-     * other models before we can finalize the where clause SQL.
3422
-     *
3423
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
-     * @throws EE_Error
3425
-     * @return EE_Model_Query_Info_Carrier
3426
-     * @throws ModelConfigurationException
3427
-     */
3428
-    public function _create_model_query_info_carrier($query_params)
3429
-    {
3430
-        if (! is_array($query_params)) {
3431
-            EE_Error::doing_it_wrong(
3432
-                'EEM_Base::_create_model_query_info_carrier',
3433
-                sprintf(
3434
-                    __(
3435
-                        '$query_params should be an array, you passed a variable of type %s',
3436
-                        'event_espresso'
3437
-                    ),
3438
-                    gettype($query_params)
3439
-                ),
3440
-                '4.6.0'
3441
-            );
3442
-            $query_params = array();
3443
-        }
3444
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3445
-        // first check if we should alter the query to account for caps or not
3446
-        // because the caps might require us to do extra joins
3447
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3448
-            $query_params[0] = array_replace_recursive(
3449
-                $query_params[0],
3450
-                $this->caps_where_conditions(
3451
-                    $query_params['caps']
3452
-                )
3453
-            );
3454
-        }
3455
-
3456
-        // check if we should alter the query to remove data related to protected
3457
-        // custom post types
3458
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3459
-            $where_param_key_for_password = $this->modelChainAndPassword();
3460
-            // only include if related to a cpt where no password has been set
3461
-            $query_params[0]['OR*nopassword'] = array(
3462
-                $where_param_key_for_password => '',
3463
-                $where_param_key_for_password . '*' => array('IS_NULL')
3464
-            );
3465
-        }
3466
-        $query_object = $this->_extract_related_models_from_query($query_params);
3467
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3468
-        foreach ($query_params[0] as $key => $value) {
3469
-            if (is_int($key)) {
3470
-                throw new EE_Error(
3471
-                    sprintf(
3472
-                        __(
3473
-                            "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.",
3474
-                            "event_espresso"
3475
-                        ),
3476
-                        $key,
3477
-                        var_export($value, true),
3478
-                        var_export($query_params, true),
3479
-                        get_class($this)
3480
-                    )
3481
-                );
3482
-            }
3483
-        }
3484
-        if (
3485
-            array_key_exists('default_where_conditions', $query_params)
3486
-            && ! empty($query_params['default_where_conditions'])
3487
-        ) {
3488
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3489
-        } else {
3490
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3491
-        }
3492
-        $query_params[0] = array_merge(
3493
-            $this->_get_default_where_conditions_for_models_in_query(
3494
-                $query_object,
3495
-                $use_default_where_conditions,
3496
-                $query_params[0]
3497
-            ),
3498
-            $query_params[0]
3499
-        );
3500
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3501
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3502
-        // So we need to setup a subquery and use that for the main join.
3503
-        // Note for now this only works on the primary table for the model.
3504
-        // So for instance, you could set the limit array like this:
3505
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3506
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3507
-            $query_object->set_main_model_join_sql(
3508
-                $this->_construct_limit_join_select(
3509
-                    $query_params['on_join_limit'][0],
3510
-                    $query_params['on_join_limit'][1]
3511
-                )
3512
-            );
3513
-        }
3514
-        // set limit
3515
-        if (array_key_exists('limit', $query_params)) {
3516
-            if (is_array($query_params['limit'])) {
3517
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
-                    $e = sprintf(
3519
-                        __(
3520
-                            "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)",
3521
-                            "event_espresso"
3522
-                        ),
3523
-                        http_build_query($query_params['limit'])
3524
-                    );
3525
-                    throw new EE_Error($e . "|" . $e);
3526
-                }
3527
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
-            } elseif (! empty($query_params['limit'])) {
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3531
-            }
3532
-        }
3533
-        // set order by
3534
-        if (array_key_exists('order_by', $query_params)) {
3535
-            if (is_array($query_params['order_by'])) {
3536
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3537
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3538
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3539
-                if (array_key_exists('order', $query_params)) {
3540
-                    throw new EE_Error(
3541
-                        sprintf(
3542
-                            __(
3543
-                                "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 ",
3544
-                                "event_espresso"
3545
-                            ),
3546
-                            get_class($this),
3547
-                            implode(", ", array_keys($query_params['order_by'])),
3548
-                            implode(", ", $query_params['order_by']),
3549
-                            $query_params['order']
3550
-                        )
3551
-                    );
3552
-                }
3553
-                $this->_extract_related_models_from_sub_params_array_keys(
3554
-                    $query_params['order_by'],
3555
-                    $query_object,
3556
-                    'order_by'
3557
-                );
3558
-                // assume it's an array of fields to order by
3559
-                $order_array = array();
3560
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561
-                    $order = $this->_extract_order($order);
3562
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
-                }
3564
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
-            } elseif (! empty($query_params['order_by'])) {
3566
-                $this->_extract_related_model_info_from_query_param(
3567
-                    $query_params['order_by'],
3568
-                    $query_object,
3569
-                    'order',
3570
-                    $query_params['order_by']
3571
-                );
3572
-                $order = isset($query_params['order'])
3573
-                    ? $this->_extract_order($query_params['order'])
3574
-                    : 'DESC';
3575
-                $query_object->set_order_by_sql(
3576
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
-                );
3578
-            }
3579
-        }
3580
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3581
-        if (
3582
-            ! array_key_exists('order_by', $query_params)
3583
-            && array_key_exists('order', $query_params)
3584
-            && ! empty($query_params['order'])
3585
-        ) {
3586
-            $pk_field = $this->get_primary_key_field();
3587
-            $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
-        }
3590
-        // set group by
3591
-        if (array_key_exists('group_by', $query_params)) {
3592
-            if (is_array($query_params['group_by'])) {
3593
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3594
-                $group_by_array = array();
3595
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
-                }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3600
-                $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
-                );
3603
-            }
3604
-        }
3605
-        // set having
3606
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
-        }
3609
-        // now, just verify they didn't pass anything wack
3610
-        foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
-                throw new EE_Error(
3613
-                    sprintf(
3614
-                        __(
3615
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
-                            'event_espresso'
3617
-                        ),
3618
-                        $query_key,
3619
-                        get_class($this),
3620
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3621
-                        implode(',', $this->_allowed_query_params)
3622
-                    )
3623
-                );
3624
-            }
3625
-        }
3626
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3627
-        if (empty($main_model_join_sql)) {
3628
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
-        }
3630
-        return $query_object;
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Gets the where conditions that should be imposed on the query based on the
3637
-     * context (eg reading frontend, backend, edit or delete).
3638
-     *
3639
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3640
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3641
-     * @throws EE_Error
3642
-     */
3643
-    public function caps_where_conditions($context = self::caps_read)
3644
-    {
3645
-        EEM_Base::verify_is_valid_cap_context($context);
3646
-        $cap_where_conditions = array();
3647
-        $cap_restrictions = $this->caps_missing($context);
3648
-        /**
3649
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
-         */
3651
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
-            $cap_where_conditions = array_replace_recursive(
3653
-                $cap_where_conditions,
3654
-                $restriction_if_no_cap->get_default_where_conditions()
3655
-            );
3656
-        }
3657
-        return apply_filters(
3658
-            'FHEE__EEM_Base__caps_where_conditions__return',
3659
-            $cap_where_conditions,
3660
-            $this,
3661
-            $context,
3662
-            $cap_restrictions
3663
-        );
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
-     * otherwise throws an exception
3671
-     *
3672
-     * @param string $should_be_order_string
3673
-     * @return string either ASC, asc, DESC or desc
3674
-     * @throws EE_Error
3675
-     */
3676
-    private function _extract_order($should_be_order_string)
3677
-    {
3678
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
-            return $should_be_order_string;
3680
-        }
3681
-        throw new EE_Error(
3682
-            sprintf(
3683
-                __(
3684
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
-                    "event_espresso"
3686
-                ),
3687
-                get_class($this),
3688
-                $should_be_order_string
3689
-            )
3690
-        );
3691
-    }
3692
-
3693
-
3694
-
3695
-    /**
3696
-     * Looks at all the models which are included in this query, and asks each
3697
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
-     * so they can be merged
3699
-     *
3700
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
-     *                                                                  'none' means NO default where conditions will
3703
-     *                                                                  be used AT ALL during this query.
3704
-     *                                                                  'other_models_only' means default where
3705
-     *                                                                  conditions from other models will be used, but
3706
-     *                                                                  not for this primary model. 'all', the default,
3707
-     *                                                                  means default where conditions will apply as
3708
-     *                                                                  normal
3709
-     * @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
3710
-     * @throws EE_Error
3711
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
-     */
3713
-    private function _get_default_where_conditions_for_models_in_query(
3714
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3715
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
-        $where_query_params = array()
3717
-    ) {
3718
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
-            throw new EE_Error(sprintf(
3721
-                __(
3722
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
-                    "event_espresso"
3724
-                ),
3725
-                $use_default_where_conditions,
3726
-                implode(", ", $allowed_used_default_where_conditions_values)
3727
-            ));
3728
-        }
3729
-        $universal_query_params = array();
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
-            } else {
3742
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3743
-                continue;
3744
-            }
3745
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3746
-                $related_model_universal_where_params,
3747
-                $where_query_params,
3748
-                $related_model,
3749
-                $model_relation_path
3750
-            );
3751
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
-                $universal_query_params,
3753
-                $overrides
3754
-            );
3755
-        }
3756
-        return $universal_query_params;
3757
-    }
3758
-
3759
-
3760
-
3761
-    /**
3762
-     * Determines whether or not we should use default where conditions for the model in question
3763
-     * (this model, or other related models).
3764
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
-     * We should use default where conditions on related models when they requested to use default where conditions
3767
-     * on all models, or specifically just on other related models
3768
-     * @param      $default_where_conditions_value
3769
-     * @param bool $for_this_model false means this is for OTHER related models
3770
-     * @return bool
3771
-     */
3772
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
-    {
3774
-        return (
3775
-                   $for_this_model
3776
-                   && in_array(
3777
-                       $default_where_conditions_value,
3778
-                       array(
3779
-                           EEM_Base::default_where_conditions_all,
3780
-                           EEM_Base::default_where_conditions_this_only,
3781
-                           EEM_Base::default_where_conditions_minimum_others,
3782
-                       ),
3783
-                       true
3784
-                   )
3785
-               )
3786
-               || (
3787
-                   ! $for_this_model
3788
-                   && in_array(
3789
-                       $default_where_conditions_value,
3790
-                       array(
3791
-                           EEM_Base::default_where_conditions_all,
3792
-                           EEM_Base::default_where_conditions_others_only,
3793
-                       ),
3794
-                       true
3795
-                   )
3796
-               );
3797
-    }
3798
-
3799
-    /**
3800
-     * Determines whether or not we should use default minimum conditions for the model in question
3801
-     * (this model, or other related models).
3802
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
-     * where conditions.
3804
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
-     * on this model or others
3806
-     * @param      $default_where_conditions_value
3807
-     * @param bool $for_this_model false means this is for OTHER related models
3808
-     * @return bool
3809
-     */
3810
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
-    {
3812
-        return (
3813
-                   $for_this_model
3814
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
-               )
3816
-               || (
3817
-                   ! $for_this_model
3818
-                   && in_array(
3819
-                       $default_where_conditions_value,
3820
-                       array(
3821
-                           EEM_Base::default_where_conditions_minimum_others,
3822
-                           EEM_Base::default_where_conditions_minimum_all,
3823
-                       ),
3824
-                       true
3825
-                   )
3826
-               );
3827
-    }
3828
-
3829
-
3830
-    /**
3831
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
-     * then we also add a special where condition which allows for that model's primary key
3833
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
-     *
3836
-     * @param array    $default_where_conditions
3837
-     * @param array    $provided_where_conditions
3838
-     * @param EEM_Base $model
3839
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3840
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
-     * @throws EE_Error
3842
-     */
3843
-    private function _override_defaults_or_make_null_friendly(
3844
-        $default_where_conditions,
3845
-        $provided_where_conditions,
3846
-        $model,
3847
-        $model_relation_path
3848
-    ) {
3849
-        $null_friendly_where_conditions = array();
3850
-        $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
-        foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3854
-                $none_overridden = false;
3855
-            } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
-            }
3858
-        }
3859
-        if ($none_overridden && $default_where_conditions) {
3860
-            if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
-                                                                                . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3864
-            }/*else{
43
+	/**
44
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
47
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
+	 *
49
+	 * @var boolean
50
+	 */
51
+	private $_values_already_prepared_by_model_object = 0;
52
+
53
+	/**
54
+	 * when $_values_already_prepared_by_model_object equals this, we assume
55
+	 * the data is just like form input that needs to have the model fields'
56
+	 * prepare_for_set and prepare_for_use_in_db called on it
57
+	 */
58
+	const not_prepared_by_model_object = 0;
59
+
60
+	/**
61
+	 * when $_values_already_prepared_by_model_object equals this, we
62
+	 * assume this value is coming from a model object and doesn't need to have
63
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
64
+	 */
65
+	const prepared_by_model_object = 1;
66
+
67
+	/**
68
+	 * when $_values_already_prepared_by_model_object equals this, we assume
69
+	 * the values are already to be used in the database (ie no processing is done
70
+	 * on them by the model's fields)
71
+	 */
72
+	const prepared_for_use_in_db = 2;
73
+
74
+
75
+	protected $singular_item = 'Item';
76
+
77
+	protected $plural_item   = 'Items';
78
+
79
+	/**
80
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
+	 */
82
+	protected $_tables;
83
+
84
+	/**
85
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
+	 *
89
+	 * @var EE_Model_Field_Base[][] $_fields
90
+	 */
91
+	protected $_fields;
92
+
93
+	/**
94
+	 * array of different kinds of relations
95
+	 *
96
+	 * @var EE_Model_Relation_Base[] $_model_relations
97
+	 */
98
+	protected $_model_relations = [];
99
+
100
+	/**
101
+	 * @var EE_Index[] $_indexes
102
+	 */
103
+	protected $_indexes = array();
104
+
105
+	/**
106
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
107
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
+	 * by setting the same columns as used in these queries in the query yourself.
109
+	 *
110
+	 * @var EE_Default_Where_Conditions
111
+	 */
112
+	protected $_default_where_conditions_strategy;
113
+
114
+	/**
115
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
+	 * This is particularly useful when you want something between 'none' and 'default'
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_minimum_where_conditions_strategy;
121
+
122
+	/**
123
+	 * String describing how to find the "owner" of this model's objects.
124
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
+	 * But when there isn't, this indicates which related model, or transiently-related model,
126
+	 * has the foreign key to the wp_users table.
127
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
+	 * related to events, and events have a foreign key to wp_users.
129
+	 * On EEM_Transaction, this would be 'Transaction.Event'
130
+	 *
131
+	 * @var string
132
+	 */
133
+	protected $_model_chain_to_wp_user = '';
134
+
135
+	/**
136
+	 * String describing how to find the model with a password controlling access to this model. This property has the
137
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
+	 * This value is the path of models to follow to arrive at the model with the password field.
139
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
+	 * model with a password that should affect reading this on the front-end.
141
+	 * Eg this is an empty string for the Event model because it has a password.
142
+	 * This is null for the Registration model, because its event's password has no bearing on whether
143
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
+	 * should hide tickets for datetimes for events that have a password set.
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = array(
178
+		self::caps_read       => array(),
179
+		self::caps_read_admin => array(),
180
+		self::caps_edit       => array(),
181
+		self::caps_delete     => array(),
182
+	);
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = array();
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = array(
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	);
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = array();
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 * @var boolean
298
+	 */
299
+	protected $_wp_core_model = false;
300
+
301
+	/**
302
+	 * @var bool stores whether this model has a password field or not.
303
+	 * null until initialized by hasPasswordField()
304
+	 */
305
+	protected $has_password_field;
306
+
307
+	/**
308
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
+	 */
310
+	protected $password_field;
311
+
312
+	/**
313
+	 *    List of valid operators that can be used for querying.
314
+	 * The keys are all operators we'll accept, the values are the real SQL
315
+	 * operators used
316
+	 *
317
+	 * @var array
318
+	 */
319
+	protected $_valid_operators = array(
320
+		'='           => '=',
321
+		'<='          => '<=',
322
+		'<'           => '<',
323
+		'>='          => '>=',
324
+		'>'           => '>',
325
+		'!='          => '!=',
326
+		'LIKE'        => 'LIKE',
327
+		'like'        => 'LIKE',
328
+		'NOT_LIKE'    => 'NOT LIKE',
329
+		'not_like'    => 'NOT LIKE',
330
+		'NOT LIKE'    => 'NOT LIKE',
331
+		'not like'    => 'NOT LIKE',
332
+		'IN'          => 'IN',
333
+		'in'          => 'IN',
334
+		'NOT_IN'      => 'NOT IN',
335
+		'not_in'      => 'NOT IN',
336
+		'NOT IN'      => 'NOT IN',
337
+		'not in'      => 'NOT IN',
338
+		'between'     => 'BETWEEN',
339
+		'BETWEEN'     => 'BETWEEN',
340
+		'IS_NOT_NULL' => 'IS NOT NULL',
341
+		'is_not_null' => 'IS NOT NULL',
342
+		'IS NOT NULL' => 'IS NOT NULL',
343
+		'is not null' => 'IS NOT NULL',
344
+		'IS_NULL'     => 'IS NULL',
345
+		'is_null'     => 'IS NULL',
346
+		'IS NULL'     => 'IS NULL',
347
+		'is null'     => 'IS NULL',
348
+		'REGEXP'      => 'REGEXP',
349
+		'regexp'      => 'REGEXP',
350
+		'NOT_REGEXP'  => 'NOT REGEXP',
351
+		'not_regexp'  => 'NOT REGEXP',
352
+		'NOT REGEXP'  => 'NOT REGEXP',
353
+		'not regexp'  => 'NOT REGEXP',
354
+	);
355
+
356
+	/**
357
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
+	 *
359
+	 * @var array
360
+	 */
361
+	protected $_in_style_operators = array('IN', 'NOT IN');
362
+
363
+	/**
364
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
+	 * '12-31-2012'"
366
+	 *
367
+	 * @var array
368
+	 */
369
+	protected $_between_style_operators = array('BETWEEN');
370
+
371
+	/**
372
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
+	/**
377
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
+	 * on a join table.
379
+	 *
380
+	 * @var array
381
+	 */
382
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
+
384
+	/**
385
+	 * Allowed values for $query_params['order'] for ordering in queries
386
+	 *
387
+	 * @var array
388
+	 */
389
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
+
391
+	/**
392
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
394
+	 *
395
+	 * @var array
396
+	 */
397
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
+
399
+	/**
400
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
402
+	 *
403
+	 * @var array
404
+	 */
405
+	private $_allowed_query_params = array(
406
+		0,
407
+		'limit',
408
+		'order_by',
409
+		'group_by',
410
+		'having',
411
+		'force_join',
412
+		'order',
413
+		'on_join_limit',
414
+		'default_where_conditions',
415
+		'caps',
416
+		'extra_selects',
417
+		'exclude_protected',
418
+	);
419
+
420
+	/**
421
+	 * All the data types that can be used in $wpdb->prepare statements.
422
+	 *
423
+	 * @var array
424
+	 */
425
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
+
427
+	/**
428
+	 * @var EE_Registry $EE
429
+	 */
430
+	protected $EE = null;
431
+
432
+
433
+	/**
434
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
+	 *
436
+	 * @var int
437
+	 */
438
+	protected $_show_next_x_db_queries = 0;
439
+
440
+	/**
441
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
+	 * WHERE, GROUP_BY, etc.
444
+	 *
445
+	 * @var CustomSelects
446
+	 */
447
+	protected $_custom_selections = array();
448
+
449
+	/**
450
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
+	 * caches every model object we've fetched from the DB on this request
452
+	 *
453
+	 * @var array
454
+	 */
455
+	protected $_entity_map;
456
+
457
+	/**
458
+	 * @var LoaderInterface
459
+	 */
460
+	private static $loader;
461
+
462
+	/**
463
+	 * @var Mirror
464
+	 */
465
+	private static $mirror;
466
+
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+
547
+	/**
548
+	 * About all child constructors:
549
+	 * they should define the _tables, _fields and _model_relations arrays.
550
+	 * Should ALWAYS be called after child constructor.
551
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
552
+	 * finalizes constructing all the object's attributes.
553
+	 * Generally, rather than requiring a child to code
554
+	 * $this->_tables = array(
555
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
+	 *        ...);
557
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
+	 * each EE_Table has a function to set the table's alias after the constructor, using
559
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
+	 * do something similar.
561
+	 *
562
+	 * @param null $timezone
563
+	 * @throws EE_Error
564
+	 */
565
+	protected function __construct($timezone = null)
566
+	{
567
+		// check that the model has not been loaded too soon
568
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
+			throw new EE_Error(
570
+				sprintf(
571
+					__(
572
+						'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.',
573
+						'event_espresso'
574
+					),
575
+					get_class($this)
576
+				)
577
+			);
578
+		}
579
+		/**
580
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
+		 */
582
+		if (empty(EEM_Base::$_model_query_blog_id)) {
583
+			EEM_Base::set_model_query_blog_id();
584
+		}
585
+		/**
586
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
+		 * just use EE_Register_Model_Extension
588
+		 *
589
+		 * @var EE_Table_Base[] $_tables
590
+		 */
591
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
+		foreach ($this->_tables as $table_alias => $table_obj) {
593
+			/** @var $table_obj EE_Table_Base */
594
+			$table_obj->_construct_finalize_with_alias($table_alias);
595
+			if ($table_obj instanceof EE_Secondary_Table) {
596
+				/** @var $table_obj EE_Secondary_Table */
597
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
+			}
599
+		}
600
+		/**
601
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
+		 * EE_Register_Model_Extension
603
+		 *
604
+		 * @param EE_Model_Field_Base[] $_fields
605
+		 */
606
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
+		$this->_invalidate_field_caches();
608
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
609
+			if (! array_key_exists($table_alias, $this->_tables)) {
610
+				throw new EE_Error(sprintf(__(
611
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
+					'event_espresso'
613
+				), $table_alias, implode(",", $this->_fields)));
614
+			}
615
+			foreach ($fields_for_table as $field_name => $field_obj) {
616
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
+				// primary key field base has a slightly different _construct_finalize
618
+				/** @var $field_obj EE_Model_Field_Base */
619
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
+			}
621
+		}
622
+		// everything is related to Extra_Meta
623
+		if (get_class($this) !== 'EEM_Extra_Meta') {
624
+			// make extra meta related to everything, but don't block deleting things just
625
+			// because they have related extra meta info. For now just orphan those extra meta
626
+			// in the future we should automatically delete them
627
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
+		}
629
+		// and change logs
630
+		if (get_class($this) !== 'EEM_Change_Log') {
631
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
+		}
633
+		/**
634
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
+		 * EE_Register_Model_Extension
636
+		 *
637
+		 * @param EE_Model_Relation_Base[] $_model_relations
638
+		 */
639
+		$this->_model_relations = (array) apply_filters(
640
+			'FHEE__' . get_class($this) . '__construct__model_relations',
641
+			$this->_model_relations
642
+		);
643
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
644
+			/** @var $relation_obj EE_Model_Relation_Base */
645
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
+		}
647
+		foreach ($this->_indexes as $index_name => $index_obj) {
648
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
+		}
650
+		$this->set_timezone($timezone);
651
+		// finalize default where condition strategy, or set default
652
+		if (! $this->_default_where_conditions_strategy) {
653
+			// nothing was set during child constructor, so set default
654
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
+		}
656
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
657
+		if (! $this->_minimum_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
663
+		// to indicate to NOT set it, set it to the logical default
664
+		if ($this->_caps_slug === null) {
665
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
+		}
667
+		// initialize the standard cap restriction generators if none were specified by the child constructor
668
+		if (is_array($this->_cap_restriction_generators)) {
669
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
+						new EE_Restriction_Generator_Protected(),
674
+						$cap_context,
675
+						$this
676
+					);
677
+				}
678
+			}
679
+		}
680
+		// if there are cap restriction generators, use them to make the default cap restrictions
681
+		if (is_array($this->_cap_restriction_generators)) {
682
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
+				if (! $generator_object) {
684
+					continue;
685
+				}
686
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
+					throw new EE_Error(
688
+						sprintf(
689
+							__(
690
+								'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.',
691
+								'event_espresso'
692
+							),
693
+							$context,
694
+							$this->get_this_model_name()
695
+						)
696
+					);
697
+				}
698
+				$action = $this->cap_action_for_context($context);
699
+				if (! $generator_object->construction_finalized()) {
700
+					$generator_object->_construct_finalize($this, $action);
701
+				}
702
+			}
703
+		}
704
+		do_action('AHEE__' . get_class($this) . '__construct__end');
705
+	}
706
+
707
+
708
+	/**
709
+	 * @return LoaderInterface
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 */
714
+	protected static function getLoader(): LoaderInterface
715
+	{
716
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
717
+			EEM_Base::$loader = LoaderFactory::getLoader();
718
+		}
719
+		return EEM_Base::$loader;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @return Mirror
725
+	 * @since   $VID:$
726
+	 */
727
+	private static function getMirror(): Mirror
728
+	{
729
+		if (! EEM_Base::$mirror instanceof Mirror) {
730
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
+		}
732
+		return EEM_Base::$mirror;
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param string $model_class_Name
738
+	 * @param string $timezone
739
+	 * @return array
740
+	 * @throws ReflectionException
741
+	 * @since   $VID:$
742
+	 */
743
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
744
+	{
745
+		$arguments = [$timezone];
746
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
+		if (count($params) > 1) {
748
+			if ($params[1]->getName() === 'model_field_factory') {
749
+				$arguments = [
750
+					$timezone,
751
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
+				];
753
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
754
+				$arguments = [
755
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
756
+					$timezone
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Input') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
761
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
+					$timezone
763
+				];
764
+			}
765
+		}
766
+		return $arguments;
767
+	}
768
+
769
+
770
+	/**
771
+	 * This function is a singleton method used to instantiate the Espresso_model object
772
+	 *
773
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
+	 *                                (and any incoming timezone data that gets saved).
775
+	 *                                Note this just sends the timezone info to the date time model field objects.
776
+	 *                                Default is NULL
777
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
+	 * @return static (as in the concrete child class)
779
+	 * @throws EE_Error
780
+	 * @throws ReflectionException
781
+	 */
782
+	public static function instance($timezone = null)
783
+	{
784
+		// check if instance of Espresso_model already exists
785
+		if (! static::$_instance instanceof static) {
786
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
+			$model = new static(...$arguments);
788
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
+			static::$_instance = $model;
790
+		}
791
+		// we might have a timezone set, let set_timezone decide what to do with it
792
+		if ($timezone){
793
+			static::$_instance->set_timezone($timezone);
794
+		}
795
+		// Espresso_model object
796
+		return static::$_instance;
797
+	}
798
+
799
+
800
+
801
+	/**
802
+	 * resets the model and returns it
803
+	 *
804
+	 * @param string|null $timezone
805
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
+	 * all its properties reset; if it wasn't instantiated, returns null)
807
+	 * @throws EE_Error
808
+	 * @throws ReflectionException
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws InvalidInterfaceException
812
+	 */
813
+	public static function reset($timezone = null)
814
+	{
815
+		if (! static::$_instance instanceof EEM_Base) {
816
+			return null;
817
+		}
818
+		// Let's NOT swap out the current instance for a new one
819
+		// because if someone has a reference to it, we can't remove their reference.
820
+		// It's best to keep using the same reference but change the original object instead,
821
+		// so reset all its properties to their original values as defined in the class.
822
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
+			// don't set instance to null like it was originally,
825
+			// but it's static anyways, and we're ignoring static properties (for now at least)
826
+			if (! isset($static_properties[ $property ])) {
827
+				static::$_instance->{$property} = $value;
828
+			}
829
+		}
830
+		// and then directly call its constructor again, like we would if we were creating a new one
831
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
+		static::$_instance->__construct(...$arguments);
833
+		return self::instance();
834
+	}
835
+
836
+
837
+	/**
838
+	 * Used to set the $_model_query_blog_id static property.
839
+	 *
840
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
+	 *                      value for get_current_blog_id() will be used.
842
+	 */
843
+	public static function set_model_query_blog_id($blog_id = 0)
844
+	{
845
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
846
+			? (int) $blog_id
847
+			: get_current_blog_id();
848
+	}
849
+
850
+
851
+	/**
852
+	 * Returns whatever is set as the internal $model_query_blog_id.
853
+	 *
854
+	 * @return int
855
+	 */
856
+	public static function get_model_query_blog_id()
857
+	{
858
+		return EEM_Base::$_model_query_blog_id;
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
+	 *
866
+	 * @param  boolean $translated return localized strings or JUST the array.
867
+	 * @return array
868
+	 * @throws EE_Error
869
+	 * @throws InvalidArgumentException
870
+	 * @throws InvalidDataTypeException
871
+	 * @throws InvalidInterfaceException
872
+	 */
873
+	public function status_array($translated = false)
874
+	{
875
+		if (! array_key_exists('Status', $this->_model_relations)) {
876
+			return array();
877
+		}
878
+		$model_name = $this->get_this_model_name();
879
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
+		$status_array = array();
882
+		foreach ($stati as $status) {
883
+			$status_array[ $status->ID() ] = $status->get('STS_code');
884
+		}
885
+		return $translated
886
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
+			: $status_array;
888
+	}
889
+
890
+
891
+
892
+	/**
893
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
+	 *
895
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
+	 *                             or if you have the development copy of EE you can view this at the path:
897
+	 *                             /docs/G--Model-System/model-query-params.md
898
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
+	 *                                        array( array(
903
+	 *                                        'OR'=>array(
904
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
+	 *                                        )
907
+	 *                                        ),
908
+	 *                                        'limit'=>10,
909
+	 *                                        'group_by'=>'TXN_ID'
910
+	 *                                        ));
911
+	 *                                        get all the answers to the question titled "shirt size" for event with id
912
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
+	 *                                        'Question.QST_display_text'=>'shirt size',
914
+	 *                                        'Registration.Event.EVT_ID'=>12
915
+	 *                                        ),
916
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
917
+	 *                                        ));
918
+	 * @throws EE_Error
919
+	 */
920
+	public function get_all($query_params = array())
921
+	{
922
+		if (
923
+			isset($query_params['limit'])
924
+			&& ! isset($query_params['group_by'])
925
+		) {
926
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
+		}
928
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * Modifies the query parameters so we only get back model objects
935
+	 * that "belong" to the current user
936
+	 *
937
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
+	 */
940
+	public function alter_query_params_to_only_include_mine($query_params = array())
941
+	{
942
+		$wp_user_field_name = $this->wp_user_field_name();
943
+		if ($wp_user_field_name) {
944
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
+		}
946
+		return $query_params;
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Returns the name of the field's name that points to the WP_User table
953
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
+	 * foreign key to the WP_User table)
955
+	 *
956
+	 * @return string|boolean string on success, boolean false when there is no
957
+	 * foreign key to the WP_User table
958
+	 */
959
+	public function wp_user_field_name()
960
+	{
961
+		try {
962
+			if (! empty($this->_model_chain_to_wp_user)) {
963
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
+				$last_model_name = end($models_to_follow_to_wp_users);
965
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
+			} else {
968
+				$model_with_fk_to_wp_users = $this;
969
+				$model_chain_to_wp_user = '';
970
+			}
971
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
973
+		} catch (EE_Error $e) {
974
+			return false;
975
+		}
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
982
+	 * (or transiently-related model) has a foreign key to the wp_users table;
983
+	 * useful for finding if model objects of this type are 'owned' by the current user.
984
+	 * This is an empty string when the foreign key is on this model and when it isn't,
985
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
986
+	 * (or transiently-related model)
987
+	 *
988
+	 * @return string
989
+	 */
990
+	public function model_chain_to_wp_user()
991
+	{
992
+		return $this->_model_chain_to_wp_user;
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
+	 * like how registrations don't have a foreign key to wp_users, but the
1000
+	 * events they are for are), or is unrelated to wp users.
1001
+	 * generally available
1002
+	 *
1003
+	 * @return boolean
1004
+	 */
1005
+	public function is_owned()
1006
+	{
1007
+		if ($this->model_chain_to_wp_user()) {
1008
+			return true;
1009
+		}
1010
+		try {
1011
+			$this->get_foreign_key_to('WP_User');
1012
+			return true;
1013
+		} catch (EE_Error $e) {
1014
+			return false;
1015
+		}
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
+	 * the model)
1023
+	 *
1024
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1028
+	 *                                  override this and set the select to "*", or a specific column name, like
1029
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
+	 *                                  the aliases used to refer to this selection, and values are to be
1032
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
+	 * @throws EE_Error
1036
+	 * @throws InvalidArgumentException
1037
+	 */
1038
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
+	{
1040
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
+		;
1042
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
+		$select_expressions = $columns_to_select === null
1044
+			? $this->_construct_default_select_sql($model_query_info)
1045
+			: '';
1046
+		if ($this->_custom_selections instanceof CustomSelects) {
1047
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048
+			$select_expressions .= $select_expressions
1049
+				? ', ' . $custom_expressions
1050
+				: $custom_expressions;
1051
+		}
1052
+
1053
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1054
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1060
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1061
+	 * method of including extra select information.
1062
+	 *
1063
+	 * @param array             $query_params
1064
+	 * @param null|array|string $columns_to_select
1065
+	 * @return null|CustomSelects
1066
+	 * @throws InvalidArgumentException
1067
+	 */
1068
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069
+	{
1070
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071
+			return null;
1072
+		}
1073
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1074
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1075
+		return new CustomSelects($selects);
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1082
+	 * but you can use the model query params to more easily
1083
+	 * take care of joins, field preparation etc.
1084
+	 *
1085
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1086
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1087
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1088
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1089
+	 *                                  override this and set the select to "*", or a specific column name, like
1090
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1091
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1092
+	 *                                  the aliases used to refer to this selection, and values are to be
1093
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1094
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1095
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1096
+	 * @throws EE_Error
1097
+	 */
1098
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1099
+	{
1100
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * For creating a custom select statement
1107
+	 *
1108
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
+	 *                                 SQL, and 1=>is the datatype
1111
+	 * @throws EE_Error
1112
+	 * @return string
1113
+	 */
1114
+	private function _construct_select_from_input($columns_to_select)
1115
+	{
1116
+		if (is_array($columns_to_select)) {
1117
+			$select_sql_array = array();
1118
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
+					throw new EE_Error(
1121
+						sprintf(
1122
+							__(
1123
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
+								'event_espresso'
1125
+							),
1126
+							$selection_and_datatype,
1127
+							$alias
1128
+						)
1129
+					);
1130
+				}
1131
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype[1],
1139
+							$selection_and_datatype[0],
1140
+							$alias,
1141
+							implode(', ', $this->_valid_wpdb_data_types)
1142
+						)
1143
+					);
1144
+				}
1145
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
+			}
1147
+			$columns_to_select_string = implode(', ', $select_sql_array);
1148
+		} else {
1149
+			$columns_to_select_string = $columns_to_select;
1150
+		}
1151
+		return $columns_to_select_string;
1152
+	}
1153
+
1154
+
1155
+
1156
+	/**
1157
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1158
+	 *
1159
+	 * @return string
1160
+	 * @throws EE_Error
1161
+	 */
1162
+	public function primary_key_name()
1163
+	{
1164
+		return $this->get_primary_key_field()->get_name();
1165
+	}
1166
+
1167
+
1168
+	/**
1169
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
+	 * If there is no primary key on this model, $id is treated as primary key string
1171
+	 *
1172
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1173
+	 * @return EE_Base_Class
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_one_by_ID($id)
1177
+	{
1178
+		if ($this->get_from_entity_map($id)) {
1179
+			return $this->get_from_entity_map($id);
1180
+		}
1181
+		$model_object = $this->get_one(
1182
+			$this->alter_query_params_to_restrict_by_ID(
1183
+				$id,
1184
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1185
+			)
1186
+		);
1187
+		$className = $this->_get_class_name();
1188
+		if ($model_object instanceof $className) {
1189
+			// make sure valid objects get added to the entity map
1190
+			// so that the next call to this method doesn't trigger another trip to the db
1191
+			$this->add_to_entity_map($model_object);
1192
+		}
1193
+		return $model_object;
1194
+	}
1195
+
1196
+
1197
+
1198
+	/**
1199
+	 * Alters query parameters to only get items with this ID are returned.
1200
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1201
+	 * or could just be a simple primary key ID
1202
+	 *
1203
+	 * @param int   $id
1204
+	 * @param array $query_params
1205
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1206
+	 * @throws EE_Error
1207
+	 */
1208
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209
+	{
1210
+		if (! isset($query_params[0])) {
1211
+			$query_params[0] = array();
1212
+		}
1213
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1214
+		if ($conditions_from_id === null) {
1215
+			$query_params[0][ $this->primary_key_name() ] = $id;
1216
+		} else {
1217
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1218
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1219
+		}
1220
+		return $query_params;
1221
+	}
1222
+
1223
+
1224
+
1225
+	/**
1226
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1227
+	 * array. If no item is found, null is returned.
1228
+	 *
1229
+	 * @param array $query_params like EEM_Base's $query_params variable.
1230
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1231
+	 * @throws EE_Error
1232
+	 */
1233
+	public function get_one($query_params = array())
1234
+	{
1235
+		if (! is_array($query_params)) {
1236
+			EE_Error::doing_it_wrong(
1237
+				'EEM_Base::get_one',
1238
+				sprintf(
1239
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1240
+					gettype($query_params)
1241
+				),
1242
+				'4.6.0'
1243
+			);
1244
+			$query_params = array();
1245
+		}
1246
+		$query_params['limit'] = 1;
1247
+		$items = $this->get_all($query_params);
1248
+		if (empty($items)) {
1249
+			return null;
1250
+		}
1251
+		return array_shift($items);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the next x number of items in sequence from the given value as
1258
+	 * found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function next_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive(
1280
+			$current_field_value,
1281
+			'>',
1282
+			$field_to_order_by,
1283
+			$limit,
1284
+			$query_params,
1285
+			$columns_to_select
1286
+		);
1287
+	}
1288
+
1289
+
1290
+
1291
+	/**
1292
+	 * Returns the previous x number of items in sequence from the given value
1293
+	 * as found in the database matching the given query conditions.
1294
+	 *
1295
+	 * @param mixed $current_field_value    Value used for the reference point.
1296
+	 * @param null  $field_to_order_by      What field is used for the
1297
+	 *                                      reference point.
1298
+	 * @param int   $limit                  How many to return.
1299
+	 * @param array $query_params           Extra conditions on the query.
1300
+	 * @param null  $columns_to_select      If left null, then an array of
1301
+	 *                                      EE_Base_Class objects is returned,
1302
+	 *                                      otherwise you can indicate just the
1303
+	 *                                      columns you want returned.
1304
+	 * @return EE_Base_Class[]|array
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	public function previous_x(
1308
+		$current_field_value,
1309
+		$field_to_order_by = null,
1310
+		$limit = 1,
1311
+		$query_params = array(),
1312
+		$columns_to_select = null
1313
+	) {
1314
+		return $this->_get_consecutive(
1315
+			$current_field_value,
1316
+			'<',
1317
+			$field_to_order_by,
1318
+			$limit,
1319
+			$query_params,
1320
+			$columns_to_select
1321
+		);
1322
+	}
1323
+
1324
+
1325
+
1326
+	/**
1327
+	 * Returns the next item in sequence from the given value as found in the
1328
+	 * database matching the given query conditions.
1329
+	 *
1330
+	 * @param mixed $current_field_value    Value used for the reference point.
1331
+	 * @param null  $field_to_order_by      What field is used for the
1332
+	 *                                      reference point.
1333
+	 * @param array $query_params           Extra conditions on the query.
1334
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1335
+	 *                                      object is returned, otherwise you
1336
+	 *                                      can indicate just the columns you
1337
+	 *                                      want and a single array indexed by
1338
+	 *                                      the columns will be returned.
1339
+	 * @return EE_Base_Class|null|array()
1340
+	 * @throws EE_Error
1341
+	 */
1342
+	public function next(
1343
+		$current_field_value,
1344
+		$field_to_order_by = null,
1345
+		$query_params = array(),
1346
+		$columns_to_select = null
1347
+	) {
1348
+		$results = $this->_get_consecutive(
1349
+			$current_field_value,
1350
+			'>',
1351
+			$field_to_order_by,
1352
+			1,
1353
+			$query_params,
1354
+			$columns_to_select
1355
+		);
1356
+		return empty($results) ? null : reset($results);
1357
+	}
1358
+
1359
+
1360
+
1361
+	/**
1362
+	 * Returns the previous item in sequence from the given value as found in
1363
+	 * the database matching the given query conditions.
1364
+	 *
1365
+	 * @param mixed $current_field_value    Value used for the reference point.
1366
+	 * @param null  $field_to_order_by      What field is used for the
1367
+	 *                                      reference point.
1368
+	 * @param array $query_params           Extra conditions on the query.
1369
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
+	 *                                      object is returned, otherwise you
1371
+	 *                                      can indicate just the columns you
1372
+	 *                                      want and a single array indexed by
1373
+	 *                                      the columns will be returned.
1374
+	 * @return EE_Base_Class|null|array()
1375
+	 * @throws EE_Error
1376
+	 */
1377
+	public function previous(
1378
+		$current_field_value,
1379
+		$field_to_order_by = null,
1380
+		$query_params = array(),
1381
+		$columns_to_select = null
1382
+	) {
1383
+		$results = $this->_get_consecutive(
1384
+			$current_field_value,
1385
+			'<',
1386
+			$field_to_order_by,
1387
+			1,
1388
+			$query_params,
1389
+			$columns_to_select
1390
+		);
1391
+		return empty($results) ? null : reset($results);
1392
+	}
1393
+
1394
+
1395
+
1396
+	/**
1397
+	 * Returns the a consecutive number of items in sequence from the given
1398
+	 * value as found in the database matching the given query conditions.
1399
+	 *
1400
+	 * @param mixed  $current_field_value   Value used for the reference point.
1401
+	 * @param string $operand               What operand is used for the sequence.
1402
+	 * @param string $field_to_order_by     What field is used for the reference point.
1403
+	 * @param int    $limit                 How many to return.
1404
+	 * @param array  $query_params          Extra conditions on the query.
1405
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1406
+	 *                                      otherwise you can indicate just the columns you want returned.
1407
+	 * @return EE_Base_Class[]|array
1408
+	 * @throws EE_Error
1409
+	 */
1410
+	protected function _get_consecutive(
1411
+		$current_field_value,
1412
+		$operand = '>',
1413
+		$field_to_order_by = null,
1414
+		$limit = 1,
1415
+		$query_params = array(),
1416
+		$columns_to_select = null
1417
+	) {
1418
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1419
+		if (empty($field_to_order_by)) {
1420
+			if ($this->has_primary_key_field()) {
1421
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1422
+			} else {
1423
+				if (WP_DEBUG) {
1424
+					throw new EE_Error(__(
1425
+						'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).',
1426
+						'event_espresso'
1427
+					));
1428
+				}
1429
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1430
+				return array();
1431
+			}
1432
+		}
1433
+		if (! is_array($query_params)) {
1434
+			EE_Error::doing_it_wrong(
1435
+				'EEM_Base::_get_consecutive',
1436
+				sprintf(
1437
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1438
+					gettype($query_params)
1439
+				),
1440
+				'4.6.0'
1441
+			);
1442
+			$query_params = array();
1443
+		}
1444
+		// let's add the where query param for consecutive look up.
1445
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1446
+		$query_params['limit'] = $limit;
1447
+		// set direction
1448
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1449
+		$query_params['order_by'] = $operand === '>'
1450
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1451
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1452
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1453
+		if (empty($columns_to_select)) {
1454
+			return $this->get_all($query_params);
1455
+		}
1456
+		// getting just the fields
1457
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This sets the _timezone property after model object has been instantiated.
1464
+	 *
1465
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1466
+	 */
1467
+	public function set_timezone($timezone)
1468
+	{
1469
+		if ($timezone !== null) {
1470
+			$this->_timezone = $timezone;
1471
+		}
1472
+		// note we need to loop through relations and set the timezone on those objects as well.
1473
+		foreach ($this->_model_relations as $relation) {
1474
+			$relation->set_timezone($timezone);
1475
+		}
1476
+		// and finally we do the same for any datetime fields
1477
+		foreach ($this->_fields as $field) {
1478
+			if ($field instanceof EE_Datetime_Field) {
1479
+				$field->set_timezone($timezone);
1480
+			}
1481
+		}
1482
+	}
1483
+
1484
+
1485
+
1486
+	/**
1487
+	 * This just returns whatever is set for the current timezone.
1488
+	 *
1489
+	 * @access public
1490
+	 * @return string
1491
+	 */
1492
+	public function get_timezone()
1493
+	{
1494
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1495
+		if (empty($this->_timezone)) {
1496
+			foreach ($this->_fields as $field) {
1497
+				if ($field instanceof EE_Datetime_Field) {
1498
+					$this->set_timezone($field->get_timezone());
1499
+					break;
1500
+				}
1501
+			}
1502
+		}
1503
+		// if timezone STILL empty then return the default timezone for the site.
1504
+		if (empty($this->_timezone)) {
1505
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1506
+		}
1507
+		return $this->_timezone;
1508
+	}
1509
+
1510
+
1511
+
1512
+	/**
1513
+	 * This returns the date formats set for the given field name and also ensures that
1514
+	 * $this->_timezone property is set correctly.
1515
+	 *
1516
+	 * @since 4.6.x
1517
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1518
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1519
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1520
+	 * @return array formats in an array with the date format first, and the time format last.
1521
+	 */
1522
+	public function get_formats_for($field_name, $pretty = false)
1523
+	{
1524
+		$field_settings = $this->field_settings_for($field_name);
1525
+		// if not a valid EE_Datetime_Field then throw error
1526
+		if (! $field_settings instanceof EE_Datetime_Field) {
1527
+			throw new EE_Error(sprintf(__(
1528
+				'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.',
1529
+				'event_espresso'
1530
+			), $field_name));
1531
+		}
1532
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
+		// the field.
1534
+		$this->_timezone = $field_settings->get_timezone();
1535
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1536
+	}
1537
+
1538
+
1539
+
1540
+	/**
1541
+	 * This returns the current time in a format setup for a query on this model.
1542
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1543
+	 * it will return:
1544
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1545
+	 *  NOW
1546
+	 *  - or a unix timestamp (equivalent to time())
1547
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1548
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1549
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1550
+	 * @since 4.6.x
1551
+	 * @param string $field_name       The field the current time is needed for.
1552
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1553
+	 *                                 formatted string matching the set format for the field in the set timezone will
1554
+	 *                                 be returned.
1555
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1556
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1557
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1558
+	 *                                 exception is triggered.
1559
+	 */
1560
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
+	{
1562
+		$formats = $this->get_formats_for($field_name);
1563
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
+		if ($timestamp) {
1565
+			return $DateTime->format('U');
1566
+		}
1567
+		// not returning timestamp, so return formatted string in timezone.
1568
+		switch ($what) {
1569
+			case 'time':
1570
+				return $DateTime->format($formats[1]);
1571
+				break;
1572
+			case 'date':
1573
+				return $DateTime->format($formats[0]);
1574
+				break;
1575
+			default:
1576
+				return $DateTime->format(implode(' ', $formats));
1577
+				break;
1578
+		}
1579
+	}
1580
+
1581
+
1582
+
1583
+	/**
1584
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1585
+	 * for the model are.  Returns a DateTime object.
1586
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1587
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1588
+	 * ignored.
1589
+	 *
1590
+	 * @param string $field_name      The field being setup.
1591
+	 * @param string $timestring      The date time string being used.
1592
+	 * @param string $incoming_format The format for the time string.
1593
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1594
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1595
+	 *                                format is
1596
+	 *                                'U', this is ignored.
1597
+	 * @return DateTime
1598
+	 * @throws EE_Error
1599
+	 */
1600
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1601
+	{
1602
+		// just using this to ensure the timezone is set correctly internally
1603
+		$this->get_formats_for($field_name);
1604
+		// load EEH_DTT_Helper
1605
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1606
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1607
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1608
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1609
+	}
1610
+
1611
+
1612
+
1613
+	/**
1614
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1615
+	 *
1616
+	 * @return EE_Table_Base[]
1617
+	 */
1618
+	public function get_tables()
1619
+	{
1620
+		return $this->_tables;
1621
+	}
1622
+
1623
+
1624
+
1625
+	/**
1626
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1627
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1628
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1629
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1630
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1631
+	 * model object with EVT_ID = 1
1632
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1633
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1634
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1635
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1636
+	 * are not specified)
1637
+	 *
1638
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1639
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1640
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1641
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1642
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1643
+	 *                                         ID=34, we'd use this method as follows:
1644
+	 *                                         EEM_Transaction::instance()->update(
1645
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1646
+	 *                                         array(array('TXN_ID'=>34)));
1647
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1648
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1649
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
+	 *                                         TRUE, it is assumed that you've already called
1654
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
+	 *                                         malicious javascript. However, if
1656
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
+	 *                                         and every other field, before insertion. We provide this parameter
1659
+	 *                                         because model objects perform their prepare_for_set function on all
1660
+	 *                                         their values, and so don't need to be called again (and in many cases,
1661
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
+	 *                                         prepare_for_set method...)
1663
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
+	 *                                         in this model's entity map according to $fields_n_values that match
1665
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1666
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1667
+	 *                                         could get out-of-sync with the database
1668
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
+	 *                                         bad)
1671
+	 * @throws EE_Error
1672
+	 */
1673
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
+	{
1675
+		if (! is_array($query_params)) {
1676
+			EE_Error::doing_it_wrong(
1677
+				'EEM_Base::update',
1678
+				sprintf(
1679
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1680
+					gettype($query_params)
1681
+				),
1682
+				'4.6.0'
1683
+			);
1684
+			$query_params = array();
1685
+		}
1686
+		/**
1687
+		 * Action called before a model update call has been made.
1688
+		 *
1689
+		 * @param EEM_Base $model
1690
+		 * @param array    $fields_n_values the updated fields and their new values
1691
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1692
+		 */
1693
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1694
+		/**
1695
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1696
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1697
+		 *
1698
+		 * @param array    $fields_n_values fields and their new values
1699
+		 * @param EEM_Base $model           the model being queried
1700
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1701
+		 */
1702
+		$fields_n_values = (array) apply_filters(
1703
+			'FHEE__EEM_Base__update__fields_n_values',
1704
+			$fields_n_values,
1705
+			$this,
1706
+			$query_params
1707
+		);
1708
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1709
+		// to do that, for each table, verify that it's PK isn't null.
1710
+		$tables = $this->get_tables();
1711
+		// 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
1712
+		// NOTE: we should make this code more efficient by NOT querying twice
1713
+		// before the real update, but that needs to first go through ALPHA testing
1714
+		// as it's dangerous. says Mike August 8 2014
1715
+		// we want to make sure the default_where strategy is ignored
1716
+		$this->_ignore_where_strategy = true;
1717
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1718
+		foreach ($wpdb_select_results as $wpdb_result) {
1719
+			// type cast stdClass as array
1720
+			$wpdb_result = (array) $wpdb_result;
1721
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722
+			if ($this->has_primary_key_field()) {
1723
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1724
+			} else {
1725
+				// 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)
1726
+				$main_table_pk_value = null;
1727
+			}
1728
+			// 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
1729
+			// 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
1730
+			if (count($tables) > 1) {
1731
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1732
+				// in that table, and so we'll want to insert one
1733
+				foreach ($tables as $table_obj) {
1734
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1735
+					// if there is no private key for this table on the results, it means there's no entry
1736
+					// in this table, right? so insert a row in the current table, using any fields available
1737
+					if (
1738
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
+						   && $wpdb_result[ $this_table_pk_column ])
1740
+					) {
1741
+						$success = $this->_insert_into_specific_table(
1742
+							$table_obj,
1743
+							$fields_n_values,
1744
+							$main_table_pk_value
1745
+						);
1746
+						// if we died here, report the error
1747
+						if (! $success) {
1748
+							return false;
1749
+						}
1750
+					}
1751
+				}
1752
+			}
1753
+			//              //and now check that if we have cached any models by that ID on the model, that
1754
+			//              //they also get updated properly
1755
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1756
+			//              if( $model_object ){
1757
+			//                  foreach( $fields_n_values as $field => $value ){
1758
+			//                      $model_object->set($field, $value);
1759
+			// let's make sure default_where strategy is followed now
1760
+			$this->_ignore_where_strategy = false;
1761
+		}
1762
+		// if we want to keep model objects in sync, AND
1763
+		// if this wasn't called from a model object (to update itself)
1764
+		// then we want to make sure we keep all the existing
1765
+		// model objects in sync with the db
1766
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1767
+			if ($this->has_primary_key_field()) {
1768
+				$model_objs_affected_ids = $this->get_col($query_params);
1769
+			} else {
1770
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1771
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1772
+				$model_objs_affected_ids = array();
1773
+				foreach ($models_affected_key_columns as $row) {
1774
+					$combined_index_key = $this->get_index_primary_key_string($row);
1775
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1776
+				}
1777
+			}
1778
+			if (! $model_objs_affected_ids) {
1779
+				// wait wait wait- if nothing was affected let's stop here
1780
+				return 0;
1781
+			}
1782
+			foreach ($model_objs_affected_ids as $id) {
1783
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1784
+				if ($model_obj_in_entity_map) {
1785
+					foreach ($fields_n_values as $field => $new_value) {
1786
+						$model_obj_in_entity_map->set($field, $new_value);
1787
+					}
1788
+				}
1789
+			}
1790
+			// if there is a primary key on this model, we can now do a slight optimization
1791
+			if ($this->has_primary_key_field()) {
1792
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1793
+				$query_params = array(
1794
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1795
+					'limit'                    => count($model_objs_affected_ids),
1796
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1797
+				);
1798
+			}
1799
+		}
1800
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1801
+		$SQL = "UPDATE "
1802
+			   . $model_query_info->get_full_join_sql()
1803
+			   . " SET "
1804
+			   . $this->_construct_update_sql($fields_n_values)
1805
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807
+		/**
1808
+		 * Action called after a model update call has been made.
1809
+		 *
1810
+		 * @param EEM_Base $model
1811
+		 * @param array    $fields_n_values the updated fields and their new values
1812
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1813
+		 * @param int      $rows_affected
1814
+		 */
1815
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
+		return $rows_affected;// how many supposedly got updated
1817
+	}
1818
+
1819
+
1820
+
1821
+	/**
1822
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1823
+	 * are teh values of the field specified (or by default the primary key field)
1824
+	 * that matched the query params. Note that you should pass the name of the
1825
+	 * model FIELD, not the database table's column name.
1826
+	 *
1827
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
+	 * @param string $field_to_select
1829
+	 * @return array just like $wpdb->get_col()
1830
+	 * @throws EE_Error
1831
+	 */
1832
+	public function get_col($query_params = array(), $field_to_select = null)
1833
+	{
1834
+		if ($field_to_select) {
1835
+			$field = $this->field_settings_for($field_to_select);
1836
+		} elseif ($this->has_primary_key_field()) {
1837
+			$field = $this->get_primary_key_field();
1838
+		} else {
1839
+			// no primary key, just grab the first column
1840
+			$field = reset($this->field_settings());
1841
+		}
1842
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1843
+		$select_expressions = $field->get_qualified_column();
1844
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1845
+		return $this->_do_wpdb_query('get_col', array($SQL));
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Returns a single column value for a single row from the database
1852
+	 *
1853
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1854
+	 * @param string $field_to_select @see EEM_Base::get_col()
1855
+	 * @return string
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function get_var($query_params = array(), $field_to_select = null)
1859
+	{
1860
+		$query_params['limit'] = 1;
1861
+		$col = $this->get_col($query_params, $field_to_select);
1862
+		if (! empty($col)) {
1863
+			return reset($col);
1864
+		}
1865
+		return null;
1866
+	}
1867
+
1868
+
1869
+
1870
+	/**
1871
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
+	 * injection, but currently no further filtering is done
1874
+	 *
1875
+	 * @global      $wpdb
1876
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1877
+	 *                               be updated to in the DB
1878
+	 * @return string of SQL
1879
+	 * @throws EE_Error
1880
+	 */
1881
+	public function _construct_update_sql($fields_n_values)
1882
+	{
1883
+		/** @type WPDB $wpdb */
1884
+		global $wpdb;
1885
+		$cols_n_values = array();
1886
+		foreach ($fields_n_values as $field_name => $value) {
1887
+			$field_obj = $this->field_settings_for($field_name);
1888
+			// if the value is NULL, we want to assign the value to that.
1889
+			// wpdb->prepare doesn't really handle that properly
1890
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
+			$value_sql = $prepared_value === null ? 'NULL'
1892
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
+		}
1895
+		return implode(",", $cols_n_values);
1896
+	}
1897
+
1898
+
1899
+
1900
+	/**
1901
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
+	 * Performs a HARD delete, meaning the database row should always be removed,
1903
+	 * not just have a flag field on it switched
1904
+	 * Wrapper for EEM_Base::delete_permanently()
1905
+	 *
1906
+	 * @param mixed $id
1907
+	 * @param boolean $allow_blocking
1908
+	 * @return int the number of rows deleted
1909
+	 * @throws EE_Error
1910
+	 */
1911
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1912
+	{
1913
+		return $this->delete_permanently(
1914
+			array(
1915
+				array($this->get_primary_key_field()->get_name() => $id),
1916
+				'limit' => 1,
1917
+			),
1918
+			$allow_blocking
1919
+		);
1920
+	}
1921
+
1922
+
1923
+
1924
+	/**
1925
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1926
+	 * Wrapper for EEM_Base::delete()
1927
+	 *
1928
+	 * @param mixed $id
1929
+	 * @param boolean $allow_blocking
1930
+	 * @return int the number of rows deleted
1931
+	 * @throws EE_Error
1932
+	 */
1933
+	public function delete_by_ID($id, $allow_blocking = true)
1934
+	{
1935
+		return $this->delete(
1936
+			array(
1937
+				array($this->get_primary_key_field()->get_name() => $id),
1938
+				'limit' => 1,
1939
+			),
1940
+			$allow_blocking
1941
+		);
1942
+	}
1943
+
1944
+
1945
+
1946
+	/**
1947
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1948
+	 * meaning if the model has a field that indicates its been "trashed" or
1949
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1950
+	 *
1951
+	 * @see EEM_Base::delete_permanently
1952
+	 * @param array   $query_params
1953
+	 * @param boolean $allow_blocking
1954
+	 * @return int how many rows got deleted
1955
+	 * @throws EE_Error
1956
+	 */
1957
+	public function delete($query_params, $allow_blocking = true)
1958
+	{
1959
+		return $this->delete_permanently($query_params, $allow_blocking);
1960
+	}
1961
+
1962
+
1963
+
1964
+	/**
1965
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1966
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1967
+	 * as archived, not actually deleted
1968
+	 *
1969
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1970
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1971
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1972
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1973
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1974
+	 *                                DB
1975
+	 * @return int how many rows got deleted
1976
+	 * @throws EE_Error
1977
+	 */
1978
+	public function delete_permanently($query_params, $allow_blocking = true)
1979
+	{
1980
+		/**
1981
+		 * Action called just before performing a real deletion query. You can use the
1982
+		 * model and its $query_params to find exactly which items will be deleted
1983
+		 *
1984
+		 * @param EEM_Base $model
1985
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1986
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1987
+		 *                                 to block (prevent) this deletion
1988
+		 */
1989
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1990
+		// some MySQL databases may be running safe mode, which may restrict
1991
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1992
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1993
+		// to delete them
1994
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1995
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1996
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1997
+			$columns_and_ids_for_deleting
1998
+		);
1999
+		/**
2000
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2001
+		 *
2002
+		 * @param EEM_Base $this  The model instance being acted on.
2003
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2004
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
2005
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2006
+		 *                                                  derived from the incoming query parameters.
2007
+		 *                                                  @see details on the structure of this array in the phpdocs
2008
+		 *                                                  for the `_get_ids_for_delete_method`
2009
+		 *
2010
+		 */
2011
+		do_action(
2012
+			'AHEE__EEM_Base__delete__before_query',
2013
+			$this,
2014
+			$query_params,
2015
+			$allow_blocking,
2016
+			$columns_and_ids_for_deleting
2017
+		);
2018
+		if ($deletion_where_query_part) {
2019
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2020
+			$table_aliases = array_keys($this->_tables);
2021
+			$SQL = "DELETE "
2022
+				   . implode(", ", $table_aliases)
2023
+				   . " FROM "
2024
+				   . $model_query_info->get_full_join_sql()
2025
+				   . " WHERE "
2026
+				   . $deletion_where_query_part;
2027
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2028
+		} else {
2029
+			$rows_deleted = 0;
2030
+		}
2031
+
2032
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2033
+		// there was no error with the delete query.
2034
+		if (
2035
+			$this->has_primary_key_field()
2036
+			&& $rows_deleted !== false
2037
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2038
+		) {
2039
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2040
+			foreach ($ids_for_removal as $id) {
2041
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2043
+				}
2044
+			}
2045
+
2046
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2047
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2048
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2049
+			// (although it is possible).
2050
+			// Note this can be skipped by using the provided filter and returning false.
2051
+			if (
2052
+				apply_filters(
2053
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2054
+					! $this instanceof EEM_Extra_Meta,
2055
+					$this
2056
+				)
2057
+			) {
2058
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2059
+					0 => array(
2060
+						'EXM_type' => $this->get_this_model_name(),
2061
+						'OBJ_ID'   => array(
2062
+							'IN',
2063
+							$ids_for_removal
2064
+						)
2065
+					)
2066
+				));
2067
+			}
2068
+		}
2069
+
2070
+		/**
2071
+		 * Action called just after performing a real deletion query. Although at this point the
2072
+		 * items should have been deleted
2073
+		 *
2074
+		 * @param EEM_Base $model
2075
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2076
+		 * @param int      $rows_deleted
2077
+		 */
2078
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
+		return $rows_deleted;// how many supposedly got deleted
2080
+	}
2081
+
2082
+
2083
+
2084
+	/**
2085
+	 * Checks all the relations that throw error messages when there are blocking related objects
2086
+	 * for related model objects. If there are any related model objects on those relations,
2087
+	 * adds an EE_Error, and return true
2088
+	 *
2089
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2090
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2091
+	 *                                                 should be ignored when determining whether there are related
2092
+	 *                                                 model objects which block this model object's deletion. Useful
2093
+	 *                                                 if you know A is related to B and are considering deleting A,
2094
+	 *                                                 but want to see if A has any other objects blocking its deletion
2095
+	 *                                                 before removing the relation between A and B
2096
+	 * @return boolean
2097
+	 * @throws EE_Error
2098
+	 */
2099
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2100
+	{
2101
+		// first, if $ignore_this_model_obj was supplied, get its model
2102
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2103
+			$ignored_model = $ignore_this_model_obj->get_model();
2104
+		} else {
2105
+			$ignored_model = null;
2106
+		}
2107
+		// now check all the relations of $this_model_obj_or_id and see if there
2108
+		// are any related model objects blocking it?
2109
+		$is_blocked = false;
2110
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2111
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2112
+				// if $ignore_this_model_obj was supplied, then for the query
2113
+				// on that model needs to be told to ignore $ignore_this_model_obj
2114
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2115
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2116
+						array(
2117
+							$ignored_model->get_primary_key_field()->get_name() => array(
2118
+								'!=',
2119
+								$ignore_this_model_obj->ID(),
2120
+							),
2121
+						),
2122
+					));
2123
+				} else {
2124
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2125
+				}
2126
+				if ($related_model_objects) {
2127
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2128
+					$is_blocked = true;
2129
+				}
2130
+			}
2131
+		}
2132
+		return $is_blocked;
2133
+	}
2134
+
2135
+
2136
+	/**
2137
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2138
+	 * @param array $row_results_for_deleting
2139
+	 * @param bool  $allow_blocking
2140
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2141
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2142
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2143
+	 *                 deleted. Example:
2144
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2145
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2146
+	 *                 where each element is a group of columns and values that get deleted. Example:
2147
+	 *                      array(
2148
+	 *                          0 => array(
2149
+	 *                              'Term_Relationship.object_id' => 1
2150
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2151
+	 *                          ),
2152
+	 *                          1 => array(
2153
+	 *                              'Term_Relationship.object_id' => 1
2154
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2155
+	 *                          )
2156
+	 *                      )
2157
+	 * @throws EE_Error
2158
+	 */
2159
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2160
+	{
2161
+		$ids_to_delete_indexed_by_column = array();
2162
+		if ($this->has_primary_key_field()) {
2163
+			$primary_table = $this->_get_main_table();
2164
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2165
+			$other_tables = $this->_get_other_tables();
2166
+			$ids_to_delete_indexed_by_column = $query = array();
2167
+			foreach ($row_results_for_deleting as $item_to_delete) {
2168
+				// before we mark this item for deletion,
2169
+				// make sure there's no related entities blocking its deletion (if we're checking)
2170
+				if (
2171
+					$allow_blocking
2172
+					&& $this->delete_is_blocked_by_related_models(
2173
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2174
+					)
2175
+				) {
2176
+					continue;
2177
+				}
2178
+				// primary table deletes
2179
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2182
+				}
2183
+			}
2184
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
+			$fields = $this->get_combined_primary_key_fields();
2186
+			foreach ($row_results_for_deleting as $item_to_delete) {
2187
+				$ids_to_delete_indexed_by_column_for_row = array();
2188
+				foreach ($fields as $cpk_field) {
2189
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2190
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2192
+					}
2193
+				}
2194
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2195
+			}
2196
+		} else {
2197
+			// so there's no primary key and no combined key...
2198
+			// sorry, can't help you
2199
+			throw new EE_Error(
2200
+				sprintf(
2201
+					__(
2202
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2203
+						"event_espresso"
2204
+					),
2205
+					get_class($this)
2206
+				)
2207
+			);
2208
+		}
2209
+		return $ids_to_delete_indexed_by_column;
2210
+	}
2211
+
2212
+
2213
+	/**
2214
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2215
+	 * the corresponding query_part for the query performing the delete.
2216
+	 *
2217
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2218
+	 * @return string
2219
+	 * @throws EE_Error
2220
+	 */
2221
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2222
+	{
2223
+		$query_part = '';
2224
+		if (empty($ids_to_delete_indexed_by_column)) {
2225
+			return $query_part;
2226
+		} elseif ($this->has_primary_key_field()) {
2227
+			$query = array();
2228
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229
+				// make sure we have unique $ids
2230
+				$ids = array_unique($ids);
2231
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2232
+			}
2233
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2235
+			$ways_to_identify_a_row = array();
2236
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237
+				$values_for_each_combined_primary_key_for_a_row = array();
2238
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2240
+				}
2241
+				$ways_to_identify_a_row[] = '('
2242
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2243
+											. ')';
2244
+			}
2245
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2246
+		}
2247
+		return $query_part;
2248
+	}
2249
+
2250
+
2251
+
2252
+	/**
2253
+	 * Gets the model field by the fully qualified name
2254
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2255
+	 * @return EE_Model_Field_Base
2256
+	 */
2257
+	public function get_field_by_column($qualified_column_name)
2258
+	{
2259
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2260
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2261
+				return $field_obj;
2262
+			}
2263
+		}
2264
+		throw new EE_Error(
2265
+			sprintf(
2266
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2267
+				$this->get_this_model_name(),
2268
+				$qualified_column_name
2269
+			)
2270
+		);
2271
+	}
2272
+
2273
+
2274
+
2275
+	/**
2276
+	 * Count all the rows that match criteria the model query params.
2277
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2278
+	 * column
2279
+	 *
2280
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2281
+	 * @param string $field_to_count field on model to count by (not column name)
2282
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2283
+	 *                               that by the setting $distinct to TRUE;
2284
+	 * @return int
2285
+	 * @throws EE_Error
2286
+	 */
2287
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2288
+	{
2289
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2290
+		if ($field_to_count) {
2291
+			$field_obj = $this->field_settings_for($field_to_count);
2292
+			$column_to_count = $field_obj->get_qualified_column();
2293
+		} elseif ($this->has_primary_key_field()) {
2294
+			$pk_field_obj = $this->get_primary_key_field();
2295
+			$column_to_count = $pk_field_obj->get_qualified_column();
2296
+		} else {
2297
+			// there's no primary key
2298
+			// if we're counting distinct items, and there's no primary key,
2299
+			// we need to list out the columns for distinction;
2300
+			// otherwise we can just use star
2301
+			if ($distinct) {
2302
+				$columns_to_use = array();
2303
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2304
+					$columns_to_use[] = $field_obj->get_qualified_column();
2305
+				}
2306
+				$column_to_count = implode(',', $columns_to_use);
2307
+			} else {
2308
+				$column_to_count = '*';
2309
+			}
2310
+		}
2311
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314
+	}
2315
+
2316
+
2317
+
2318
+	/**
2319
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2320
+	 *
2321
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2323
+	 * @return float
2324
+	 * @throws EE_Error
2325
+	 */
2326
+	public function sum($query_params, $field_to_sum = null)
2327
+	{
2328
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
+		if ($field_to_sum) {
2330
+			$field_obj = $this->field_settings_for($field_to_sum);
2331
+		} else {
2332
+			$field_obj = $this->get_primary_key_field();
2333
+		}
2334
+		$column_to_count = $field_obj->get_qualified_column();
2335
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2336
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337
+		$data_type = $field_obj->get_wpdb_data_type();
2338
+		if ($data_type === '%d' || $data_type === '%s') {
2339
+			return (float) $return_value;
2340
+		}
2341
+		// must be %f
2342
+		return (float) $return_value;
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Just calls the specified method on $wpdb with the given arguments
2349
+	 * Consolidates a little extra error handling code
2350
+	 *
2351
+	 * @param string $wpdb_method
2352
+	 * @param array  $arguments_to_provide
2353
+	 * @throws EE_Error
2354
+	 * @global wpdb  $wpdb
2355
+	 * @return mixed
2356
+	 */
2357
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
+	{
2359
+		// if we're in maintenance mode level 2, DON'T run any queries
2360
+		// because level 2 indicates the database needs updating and
2361
+		// is probably out of sync with the code
2362
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
+			throw new EE_Error(sprintf(__(
2364
+				"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.",
2365
+				"event_espresso"
2366
+			)));
2367
+		}
2368
+		/** @type WPDB $wpdb */
2369
+		global $wpdb;
2370
+		if (! method_exists($wpdb, $wpdb_method)) {
2371
+			throw new EE_Error(sprintf(__(
2372
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2373
+				'event_espresso'
2374
+			), $wpdb_method));
2375
+		}
2376
+		if (WP_DEBUG) {
2377
+			$old_show_errors_value = $wpdb->show_errors;
2378
+			$wpdb->show_errors(false);
2379
+		}
2380
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2381
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2382
+		if (WP_DEBUG) {
2383
+			$wpdb->show_errors($old_show_errors_value);
2384
+			if (! empty($wpdb->last_error)) {
2385
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386
+			}
2387
+			if ($result === false) {
2388
+				throw new EE_Error(sprintf(__(
2389
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2390
+					'event_espresso'
2391
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2392
+			}
2393
+		} elseif ($result === false) {
2394
+			EE_Error::add_error(
2395
+				sprintf(
2396
+					__(
2397
+						'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"',
2398
+						'event_espresso'
2399
+					),
2400
+					$wpdb_method,
2401
+					var_export($arguments_to_provide, true),
2402
+					$wpdb->last_error
2403
+				),
2404
+				__FILE__,
2405
+				__FUNCTION__,
2406
+				__LINE__
2407
+			);
2408
+		}
2409
+		return $result;
2410
+	}
2411
+
2412
+
2413
+
2414
+	/**
2415
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2416
+	 * and if there's an error tries to verify the DB is correct. Uses
2417
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2418
+	 * we should try to fix the EE core db, the addons, or just give up
2419
+	 *
2420
+	 * @param string $wpdb_method
2421
+	 * @param array  $arguments_to_provide
2422
+	 * @return mixed
2423
+	 */
2424
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2425
+	{
2426
+		/** @type WPDB $wpdb */
2427
+		global $wpdb;
2428
+		$wpdb->last_error = null;
2429
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2430
+		// was there an error running the query? but we don't care on new activations
2431
+		// (we're going to setup the DB anyway on new activations)
2432
+		if (
2433
+			($result === false || ! empty($wpdb->last_error))
2434
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2435
+		) {
2436
+			switch (EEM_Base::$_db_verification_level) {
2437
+				case EEM_Base::db_verified_none:
2438
+					// let's double-check core's DB
2439
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2440
+					break;
2441
+				case EEM_Base::db_verified_core:
2442
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2443
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2444
+					break;
2445
+				case EEM_Base::db_verified_addons:
2446
+					// ummmm... you in trouble
2447
+					return $result;
2448
+					break;
2449
+			}
2450
+			if (! empty($error_message)) {
2451
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452
+				trigger_error($error_message);
2453
+			}
2454
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2455
+		}
2456
+		return $result;
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2463
+	 * EEM_Base::$_db_verification_level
2464
+	 *
2465
+	 * @param string $wpdb_method
2466
+	 * @param array  $arguments_to_provide
2467
+	 * @return string
2468
+	 */
2469
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2470
+	{
2471
+		/** @type WPDB $wpdb */
2472
+		global $wpdb;
2473
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2474
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2475
+		$error_message = sprintf(
2476
+			__(
2477
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2478
+				'event_espresso'
2479
+			),
2480
+			$wpdb->last_error,
2481
+			$wpdb_method,
2482
+			wp_json_encode($arguments_to_provide)
2483
+		);
2484
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2485
+		return $error_message;
2486
+	}
2487
+
2488
+
2489
+
2490
+	/**
2491
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2492
+	 * EEM_Base::$_db_verification_level
2493
+	 *
2494
+	 * @param $wpdb_method
2495
+	 * @param $arguments_to_provide
2496
+	 * @return string
2497
+	 */
2498
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2499
+	{
2500
+		/** @type WPDB $wpdb */
2501
+		global $wpdb;
2502
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2503
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2504
+		$error_message = sprintf(
2505
+			__(
2506
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2507
+				'event_espresso'
2508
+			),
2509
+			$wpdb->last_error,
2510
+			$wpdb_method,
2511
+			wp_json_encode($arguments_to_provide)
2512
+		);
2513
+		EE_System::instance()->initialize_addons();
2514
+		return $error_message;
2515
+	}
2516
+
2517
+
2518
+
2519
+	/**
2520
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2521
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2522
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2523
+	 * ..."
2524
+	 *
2525
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2526
+	 * @return string
2527
+	 */
2528
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529
+	{
2530
+		return " FROM " . $model_query_info->get_full_join_sql() .
2531
+			   $model_query_info->get_where_sql() .
2532
+			   $model_query_info->get_group_by_sql() .
2533
+			   $model_query_info->get_having_sql() .
2534
+			   $model_query_info->get_order_by_sql() .
2535
+			   $model_query_info->get_limit_sql();
2536
+	}
2537
+
2538
+
2539
+
2540
+	/**
2541
+	 * Set to easily debug the next X queries ran from this model.
2542
+	 *
2543
+	 * @param int $count
2544
+	 */
2545
+	public function show_next_x_db_queries($count = 1)
2546
+	{
2547
+		$this->_show_next_x_db_queries = $count;
2548
+	}
2549
+
2550
+
2551
+
2552
+	/**
2553
+	 * @param $sql_query
2554
+	 */
2555
+	public function show_db_query_if_previously_requested($sql_query)
2556
+	{
2557
+		if ($this->_show_next_x_db_queries > 0) {
2558
+			echo $sql_query;
2559
+			$this->_show_next_x_db_queries--;
2560
+		}
2561
+	}
2562
+
2563
+
2564
+
2565
+	/**
2566
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
+	 * There are the 3 cases:
2568
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
+	 * $otherModelObject has no ID, it is first saved.
2570
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
+	 * has no ID, it is first saved.
2572
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
+	 * join table
2575
+	 *
2576
+	 * @param        EE_Base_Class                     /int $thisModelObject
2577
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
+	 * @param string $relationName                     , key in EEM_Base::_relations
2579
+	 *                                                 an attendee to a group, you also want to specify which role they
2580
+	 *                                                 will have in that group. So you would use this parameter to
2581
+	 *                                                 specify array('role-column-name'=>'role-id')
2582
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
+	 *                                                 to for relation to methods that allow you to further specify
2584
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
+	 *                                                 because these will be inserted in any new rows created as well.
2587
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
+	 * @throws EE_Error
2589
+	 */
2590
+	public function add_relationship_to(
2591
+		$id_or_obj,
2592
+		$other_model_id_or_obj,
2593
+		$relationName,
2594
+		$extra_join_model_fields_n_values = array()
2595
+	) {
2596
+		$relation_obj = $this->related_settings_for($relationName);
2597
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
+	}
2599
+
2600
+
2601
+
2602
+	/**
2603
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2604
+	 * There are the 3 cases:
2605
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2606
+	 * error
2607
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2608
+	 * an error
2609
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2610
+	 *
2611
+	 * @param        EE_Base_Class /int $id_or_obj
2612
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2613
+	 * @param string $relationName key in EEM_Base::_relations
2614
+	 * @return boolean of success
2615
+	 * @throws EE_Error
2616
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2617
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2618
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2619
+	 *                             because these will be inserted in any new rows created as well.
2620
+	 */
2621
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2622
+	{
2623
+		$relation_obj = $this->related_settings_for($relationName);
2624
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2625
+	}
2626
+
2627
+
2628
+
2629
+	/**
2630
+	 * @param mixed           $id_or_obj
2631
+	 * @param string          $relationName
2632
+	 * @param array           $where_query_params
2633
+	 * @param EE_Base_Class[] objects to which relations were removed
2634
+	 * @return \EE_Base_Class[]
2635
+	 * @throws EE_Error
2636
+	 */
2637
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2638
+	{
2639
+		$relation_obj = $this->related_settings_for($relationName);
2640
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2641
+	}
2642
+
2643
+
2644
+
2645
+	/**
2646
+	 * Gets all the related items of the specified $model_name, using $query_params.
2647
+	 * Note: by default, we remove the "default query params"
2648
+	 * because we want to get even deleted items etc.
2649
+	 *
2650
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2651
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2652
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2653
+	 * @return EE_Base_Class[]
2654
+	 * @throws EE_Error
2655
+	 */
2656
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2657
+	{
2658
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2659
+		$relation_settings = $this->related_settings_for($model_name);
2660
+		return $relation_settings->get_all_related($model_obj, $query_params);
2661
+	}
2662
+
2663
+
2664
+
2665
+	/**
2666
+	 * Deletes all the model objects across the relation indicated by $model_name
2667
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2668
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2669
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2670
+	 *
2671
+	 * @param EE_Base_Class|int|string $id_or_obj
2672
+	 * @param string                   $model_name
2673
+	 * @param array                    $query_params
2674
+	 * @return int how many deleted
2675
+	 * @throws EE_Error
2676
+	 */
2677
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2678
+	{
2679
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2680
+		$relation_settings = $this->related_settings_for($model_name);
2681
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2688
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2689
+	 * the model objects can't be hard deleted because of blocking related model objects,
2690
+	 * just does a soft-delete on them instead.
2691
+	 *
2692
+	 * @param EE_Base_Class|int|string $id_or_obj
2693
+	 * @param string                   $model_name
2694
+	 * @param array                    $query_params
2695
+	 * @return int how many deleted
2696
+	 * @throws EE_Error
2697
+	 */
2698
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2699
+	{
2700
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2701
+		$relation_settings = $this->related_settings_for($model_name);
2702
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2703
+	}
2704
+
2705
+
2706
+
2707
+	/**
2708
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2709
+	 * unless otherwise specified in the $query_params
2710
+	 *
2711
+	 * @param        int             /EE_Base_Class $id_or_obj
2712
+	 * @param string $model_name     like 'Event', or 'Registration'
2713
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2714
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2715
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2716
+	 *                               that by the setting $distinct to TRUE;
2717
+	 * @return int
2718
+	 * @throws EE_Error
2719
+	 */
2720
+	public function count_related(
2721
+		$id_or_obj,
2722
+		$model_name,
2723
+		$query_params = array(),
2724
+		$field_to_count = null,
2725
+		$distinct = false
2726
+	) {
2727
+		$related_model = $this->get_related_model_obj($model_name);
2728
+		// we're just going to use the query params on the related model's normal get_all query,
2729
+		// except add a condition to say to match the current mod
2730
+		if (! isset($query_params['default_where_conditions'])) {
2731
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732
+		}
2733
+		$this_model_name = $this->get_this_model_name();
2734
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2736
+		return $related_model->count($query_params, $field_to_count, $distinct);
2737
+	}
2738
+
2739
+
2740
+
2741
+	/**
2742
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2743
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2744
+	 *
2745
+	 * @param        int           /EE_Base_Class $id_or_obj
2746
+	 * @param string $model_name   like 'Event', or 'Registration'
2747
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2748
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2749
+	 * @return float
2750
+	 * @throws EE_Error
2751
+	 */
2752
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753
+	{
2754
+		$related_model = $this->get_related_model_obj($model_name);
2755
+		if (! is_array($query_params)) {
2756
+			EE_Error::doing_it_wrong(
2757
+				'EEM_Base::sum_related',
2758
+				sprintf(
2759
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2760
+					gettype($query_params)
2761
+				),
2762
+				'4.6.0'
2763
+			);
2764
+			$query_params = array();
2765
+		}
2766
+		// we're just going to use the query params on the related model's normal get_all query,
2767
+		// except add a condition to say to match the current mod
2768
+		if (! isset($query_params['default_where_conditions'])) {
2769
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770
+		}
2771
+		$this_model_name = $this->get_this_model_name();
2772
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2774
+		return $related_model->sum($query_params, $field_to_sum);
2775
+	}
2776
+
2777
+
2778
+
2779
+	/**
2780
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2781
+	 * $modelObject
2782
+	 *
2783
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2784
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2785
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2786
+	 * @return EE_Base_Class
2787
+	 * @throws EE_Error
2788
+	 */
2789
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2790
+	{
2791
+		$query_params['limit'] = 1;
2792
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2793
+		if ($results) {
2794
+			return array_shift($results);
2795
+		}
2796
+		return null;
2797
+	}
2798
+
2799
+
2800
+
2801
+	/**
2802
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2803
+	 *
2804
+	 * @return string
2805
+	 */
2806
+	public function get_this_model_name()
2807
+	{
2808
+		return str_replace("EEM_", "", get_class($this));
2809
+	}
2810
+
2811
+
2812
+
2813
+	/**
2814
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2815
+	 *
2816
+	 * @return EE_Any_Foreign_Model_Name_Field
2817
+	 * @throws EE_Error
2818
+	 */
2819
+	public function get_field_containing_related_model_name()
2820
+	{
2821
+		foreach ($this->field_settings(true) as $field) {
2822
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2823
+				$field_with_model_name = $field;
2824
+			}
2825
+		}
2826
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2827
+			throw new EE_Error(sprintf(
2828
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829
+				$this->get_this_model_name()
2830
+			));
2831
+		}
2832
+		return $field_with_model_name;
2833
+	}
2834
+
2835
+
2836
+
2837
+	/**
2838
+	 * Inserts a new entry into the database, for each table.
2839
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2840
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2841
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2842
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2843
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2844
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2845
+	 *
2846
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2847
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2848
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2849
+	 *                              of EEM_Base)
2850
+	 * @return int|string new primary key on main table that got inserted
2851
+	 * @throws EE_Error
2852
+	 */
2853
+	public function insert($field_n_values)
2854
+	{
2855
+		/**
2856
+		 * Filters the fields and their values before inserting an item using the models
2857
+		 *
2858
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2859
+		 * @param EEM_Base $model           the model used
2860
+		 */
2861
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2862
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2863
+			$main_table = $this->_get_main_table();
2864
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2865
+			if ($new_id !== false) {
2866
+				foreach ($this->_get_other_tables() as $other_table) {
2867
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2868
+				}
2869
+			}
2870
+			/**
2871
+			 * Done just after attempting to insert a new model object
2872
+			 *
2873
+			 * @param EEM_Base   $model           used
2874
+			 * @param array      $fields_n_values fields and their values
2875
+			 * @param int|string the              ID of the newly-inserted model object
2876
+			 */
2877
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2878
+			return $new_id;
2879
+		}
2880
+		return false;
2881
+	}
2882
+
2883
+
2884
+
2885
+	/**
2886
+	 * Checks that the result would satisfy the unique indexes on this model
2887
+	 *
2888
+	 * @param array  $field_n_values
2889
+	 * @param string $action
2890
+	 * @return boolean
2891
+	 * @throws EE_Error
2892
+	 */
2893
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2894
+	{
2895
+		foreach ($this->unique_indexes() as $index_name => $index) {
2896
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2897
+			if ($this->exists(array($uniqueness_where_params))) {
2898
+				EE_Error::add_error(
2899
+					sprintf(
2900
+						__(
2901
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2902
+							"event_espresso"
2903
+						),
2904
+						$action,
2905
+						$this->_get_class_name(),
2906
+						$index_name,
2907
+						implode(",", $index->field_names()),
2908
+						http_build_query($uniqueness_where_params)
2909
+					),
2910
+					__FILE__,
2911
+					__FUNCTION__,
2912
+					__LINE__
2913
+				);
2914
+				return false;
2915
+			}
2916
+		}
2917
+		return true;
2918
+	}
2919
+
2920
+
2921
+
2922
+	/**
2923
+	 * Checks the database for an item that conflicts (ie, if this item were
2924
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2925
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2926
+	 * can be either an EE_Base_Class or an array of fields n values
2927
+	 *
2928
+	 * @param EE_Base_Class|array $obj_or_fields_array
2929
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2930
+	 *                                                 when looking for conflicts
2931
+	 *                                                 (ie, if false, we ignore the model object's primary key
2932
+	 *                                                 when finding "conflicts". If true, it's also considered).
2933
+	 *                                                 Only works for INT primary key,
2934
+	 *                                                 STRING primary keys cannot be ignored
2935
+	 * @throws EE_Error
2936
+	 * @return EE_Base_Class|array
2937
+	 */
2938
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2939
+	{
2940
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2941
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2942
+		} elseif (is_array($obj_or_fields_array)) {
2943
+			$fields_n_values = $obj_or_fields_array;
2944
+		} else {
2945
+			throw new EE_Error(
2946
+				sprintf(
2947
+					__(
2948
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2949
+						"event_espresso"
2950
+					),
2951
+					get_class($this),
2952
+					$obj_or_fields_array
2953
+				)
2954
+			);
2955
+		}
2956
+		$query_params = array();
2957
+		if (
2958
+			$this->has_primary_key_field()
2959
+			&& ($include_primary_key
2960
+				|| $this->get_primary_key_field()
2961
+				   instanceof
2962
+				   EE_Primary_Key_String_Field)
2963
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2964
+		) {
2965
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2966
+		}
2967
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2970
+		}
2971
+		// if there is nothing to base this search on, then we shouldn't find anything
2972
+		if (empty($query_params)) {
2973
+			return array();
2974
+		}
2975
+		return $this->get_one($query_params);
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * Like count, but is optimized and returns a boolean instead of an int
2982
+	 *
2983
+	 * @param array $query_params
2984
+	 * @return boolean
2985
+	 * @throws EE_Error
2986
+	 */
2987
+	public function exists($query_params)
2988
+	{
2989
+		$query_params['limit'] = 1;
2990
+		return $this->count($query_params) > 0;
2991
+	}
2992
+
2993
+
2994
+
2995
+	/**
2996
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2997
+	 *
2998
+	 * @param int|string $id
2999
+	 * @return boolean
3000
+	 * @throws EE_Error
3001
+	 */
3002
+	public function exists_by_ID($id)
3003
+	{
3004
+		return $this->exists(
3005
+			array(
3006
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3007
+				array(
3008
+					$this->primary_key_name() => $id,
3009
+				),
3010
+			)
3011
+		);
3012
+	}
3013
+
3014
+
3015
+
3016
+	/**
3017
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
+	 * on the main table)
3021
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
+	 * cases where we want to call it directly rather than via insert().
3023
+	 *
3024
+	 * @access   protected
3025
+	 * @param EE_Table_Base $table
3026
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
+	 *                                       float
3028
+	 * @param int           $new_id          for now we assume only int keys
3029
+	 * @throws EE_Error
3030
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3031
+	 * @return int ID of new row inserted, or FALSE on failure
3032
+	 */
3033
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
+	{
3035
+		global $wpdb;
3036
+		$insertion_col_n_values = array();
3037
+		$format_for_insertion = array();
3038
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3039
+		foreach ($fields_on_table as $field_name => $field_obj) {
3040
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
+			if ($field_obj->is_auto_increment()) {
3042
+				continue;
3043
+			}
3044
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
+			if ($prepared_value !== null) {
3047
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049
+			}
3050
+		}
3051
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3052
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3053
+			// so add the fk to the main table as a column
3054
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3056
+		}
3057
+		// insert the new entry
3058
+		$result = $this->_do_wpdb_query(
3059
+			'insert',
3060
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3061
+		);
3062
+		if ($result === false) {
3063
+			return false;
3064
+		}
3065
+		// ok, now what do we return for the ID of the newly-inserted thing?
3066
+		if ($this->has_primary_key_field()) {
3067
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3068
+				return $wpdb->insert_id;
3069
+			}
3070
+			// it's not an auto-increment primary key, so
3071
+			// it must have been supplied
3072
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3073
+		}
3074
+		// we can't return a  primary key because there is none. instead return
3075
+		// a unique string indicating this model
3076
+		return $this->get_index_primary_key_string($fields_n_values);
3077
+	}
3078
+
3079
+
3080
+
3081
+	/**
3082
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3083
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3084
+	 * and there is no default, we pass it along. WPDB will take care of it)
3085
+	 *
3086
+	 * @param EE_Model_Field_Base $field_obj
3087
+	 * @param array               $fields_n_values
3088
+	 * @return mixed string|int|float depending on what the table column will be expecting
3089
+	 * @throws EE_Error
3090
+	 */
3091
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3092
+	{
3093
+		// if this field doesn't allow nullable, don't allow it
3094
+		if (
3095
+			! $field_obj->is_nullable()
3096
+			&& (
3097
+				! isset($fields_n_values[ $field_obj->get_name() ])
3098
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3099
+			)
3100
+		) {
3101
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3102
+		}
3103
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
+			? $fields_n_values[ $field_obj->get_name() ]
3105
+			: null;
3106
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107
+	}
3108
+
3109
+
3110
+
3111
+	/**
3112
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3113
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3114
+	 * the field's prepare_for_set() method.
3115
+	 *
3116
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3117
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3118
+	 *                                   top of file)
3119
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3120
+	 *                                   $value is a custom selection
3121
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3122
+	 */
3123
+	private function _prepare_value_for_use_in_db($value, $field)
3124
+	{
3125
+		if ($field && $field instanceof EE_Model_Field_Base) {
3126
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3127
+			switch ($this->_values_already_prepared_by_model_object) {
3128
+				/** @noinspection PhpMissingBreakStatementInspection */
3129
+				case self::not_prepared_by_model_object:
3130
+					$value = $field->prepare_for_set($value);
3131
+				// purposefully left out "return"
3132
+				case self::prepared_by_model_object:
3133
+					/** @noinspection SuspiciousAssignmentsInspection */
3134
+					$value = $field->prepare_for_use_in_db($value);
3135
+				case self::prepared_for_use_in_db:
3136
+					// leave the value alone
3137
+			}
3138
+			return $value;
3139
+			// phpcs:enable
3140
+		}
3141
+		return $value;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * Returns the main table on this model
3148
+	 *
3149
+	 * @return EE_Primary_Table
3150
+	 * @throws EE_Error
3151
+	 */
3152
+	protected function _get_main_table()
3153
+	{
3154
+		foreach ($this->_tables as $table) {
3155
+			if ($table instanceof EE_Primary_Table) {
3156
+				return $table;
3157
+			}
3158
+		}
3159
+		throw new EE_Error(sprintf(__(
3160
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3161
+			'event_espresso'
3162
+		), get_class($this)));
3163
+	}
3164
+
3165
+
3166
+
3167
+	/**
3168
+	 * table
3169
+	 * returns EE_Primary_Table table name
3170
+	 *
3171
+	 * @return string
3172
+	 * @throws EE_Error
3173
+	 */
3174
+	public function table()
3175
+	{
3176
+		return $this->_get_main_table()->get_table_name();
3177
+	}
3178
+
3179
+
3180
+
3181
+	/**
3182
+	 * table
3183
+	 * returns first EE_Secondary_Table table name
3184
+	 *
3185
+	 * @return string
3186
+	 */
3187
+	public function second_table()
3188
+	{
3189
+		// grab second table from tables array
3190
+		$second_table = end($this->_tables);
3191
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3192
+	}
3193
+
3194
+
3195
+
3196
+	/**
3197
+	 * get_table_obj_by_alias
3198
+	 * returns table name given it's alias
3199
+	 *
3200
+	 * @param string $table_alias
3201
+	 * @return EE_Primary_Table | EE_Secondary_Table
3202
+	 */
3203
+	public function get_table_obj_by_alias($table_alias = '')
3204
+	{
3205
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3206
+	}
3207
+
3208
+
3209
+
3210
+	/**
3211
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3212
+	 *
3213
+	 * @return EE_Secondary_Table[]
3214
+	 */
3215
+	protected function _get_other_tables()
3216
+	{
3217
+		$other_tables = array();
3218
+		foreach ($this->_tables as $table_alias => $table) {
3219
+			if ($table instanceof EE_Secondary_Table) {
3220
+				$other_tables[ $table_alias ] = $table;
3221
+			}
3222
+		}
3223
+		return $other_tables;
3224
+	}
3225
+
3226
+
3227
+
3228
+	/**
3229
+	 * Finds all the fields that correspond to the given table
3230
+	 *
3231
+	 * @param string $table_alias , array key in EEM_Base::_tables
3232
+	 * @return EE_Model_Field_Base[]
3233
+	 */
3234
+	public function _get_fields_for_table($table_alias)
3235
+	{
3236
+		return $this->_fields[ $table_alias ];
3237
+	}
3238
+
3239
+
3240
+
3241
+	/**
3242
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3243
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3244
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3245
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3246
+	 * related Registration, Transaction, and Payment models.
3247
+	 *
3248
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3249
+	 * @return EE_Model_Query_Info_Carrier
3250
+	 * @throws EE_Error
3251
+	 */
3252
+	public function _extract_related_models_from_query($query_params)
3253
+	{
3254
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3255
+		if (array_key_exists(0, $query_params)) {
3256
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3257
+		}
3258
+		if (array_key_exists('group_by', $query_params)) {
3259
+			if (is_array($query_params['group_by'])) {
3260
+				$this->_extract_related_models_from_sub_params_array_values(
3261
+					$query_params['group_by'],
3262
+					$query_info_carrier,
3263
+					'group_by'
3264
+				);
3265
+			} elseif (! empty($query_params['group_by'])) {
3266
+				$this->_extract_related_model_info_from_query_param(
3267
+					$query_params['group_by'],
3268
+					$query_info_carrier,
3269
+					'group_by'
3270
+				);
3271
+			}
3272
+		}
3273
+		if (array_key_exists('having', $query_params)) {
3274
+			$this->_extract_related_models_from_sub_params_array_keys(
3275
+				$query_params[0],
3276
+				$query_info_carrier,
3277
+				'having'
3278
+			);
3279
+		}
3280
+		if (array_key_exists('order_by', $query_params)) {
3281
+			if (is_array($query_params['order_by'])) {
3282
+				$this->_extract_related_models_from_sub_params_array_keys(
3283
+					$query_params['order_by'],
3284
+					$query_info_carrier,
3285
+					'order_by'
3286
+				);
3287
+			} elseif (! empty($query_params['order_by'])) {
3288
+				$this->_extract_related_model_info_from_query_param(
3289
+					$query_params['order_by'],
3290
+					$query_info_carrier,
3291
+					'order_by'
3292
+				);
3293
+			}
3294
+		}
3295
+		if (array_key_exists('force_join', $query_params)) {
3296
+			$this->_extract_related_models_from_sub_params_array_values(
3297
+				$query_params['force_join'],
3298
+				$query_info_carrier,
3299
+				'force_join'
3300
+			);
3301
+		}
3302
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3303
+		return $query_info_carrier;
3304
+	}
3305
+
3306
+
3307
+
3308
+	/**
3309
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3310
+	 *
3311
+	 * @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
3312
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3313
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3314
+	 * @throws EE_Error
3315
+	 * @return \EE_Model_Query_Info_Carrier
3316
+	 */
3317
+	private function _extract_related_models_from_sub_params_array_keys(
3318
+		$sub_query_params,
3319
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320
+		$query_param_type
3321
+	) {
3322
+		if (! empty($sub_query_params)) {
3323
+			$sub_query_params = (array) $sub_query_params;
3324
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3326
+				$this->_extract_related_model_info_from_query_param(
3327
+					$param,
3328
+					$model_query_info_carrier,
3329
+					$query_param_type
3330
+				);
3331
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3332
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3333
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3334
+				// of array('Registration.TXN_ID'=>23)
3335
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
+					if (! is_array($possibly_array_of_params)) {
3338
+						throw new EE_Error(sprintf(
3339
+							__(
3340
+								"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'))",
3341
+								"event_espresso"
3342
+							),
3343
+							$param,
3344
+							$possibly_array_of_params
3345
+						));
3346
+					}
3347
+					$this->_extract_related_models_from_sub_params_array_keys(
3348
+						$possibly_array_of_params,
3349
+						$model_query_info_carrier,
3350
+						$query_param_type
3351
+					);
3352
+				} elseif (
3353
+					$query_param_type === 0 // ie WHERE
3354
+						  && is_array($possibly_array_of_params)
3355
+						  && isset($possibly_array_of_params[2])
3356
+						  && $possibly_array_of_params[2] == true
3357
+				) {
3358
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359
+					// indicating that $possible_array_of_params[1] is actually a field name,
3360
+					// from which we should extract query parameters!
3361
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362
+						throw new EE_Error(sprintf(__(
3363
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364
+							"event_espresso"
3365
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3366
+					}
3367
+					$this->_extract_related_model_info_from_query_param(
3368
+						$possibly_array_of_params[1],
3369
+						$model_query_info_carrier,
3370
+						$query_param_type
3371
+					);
3372
+				}
3373
+			}
3374
+		}
3375
+		return $model_query_info_carrier;
3376
+	}
3377
+
3378
+
3379
+
3380
+	/**
3381
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3382
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3383
+	 *
3384
+	 * @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
3385
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3386
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3387
+	 * @throws EE_Error
3388
+	 * @return \EE_Model_Query_Info_Carrier
3389
+	 */
3390
+	private function _extract_related_models_from_sub_params_array_values(
3391
+		$sub_query_params,
3392
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393
+		$query_param_type
3394
+	) {
3395
+		if (! empty($sub_query_params)) {
3396
+			if (! is_array($sub_query_params)) {
3397
+				throw new EE_Error(sprintf(
3398
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
+					$sub_query_params
3400
+				));
3401
+			}
3402
+			foreach ($sub_query_params as $param) {
3403
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
+				$this->_extract_related_model_info_from_query_param(
3405
+					$param,
3406
+					$model_query_info_carrier,
3407
+					$query_param_type
3408
+				);
3409
+			}
3410
+		}
3411
+		return $model_query_info_carrier;
3412
+	}
3413
+
3414
+
3415
+	/**
3416
+	 * Extract all the query parts from  model query params
3417
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
+	 * but use them in a different order. Eg, we need to know what models we are querying
3420
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
+	 * other models before we can finalize the where clause SQL.
3422
+	 *
3423
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
+	 * @throws EE_Error
3425
+	 * @return EE_Model_Query_Info_Carrier
3426
+	 * @throws ModelConfigurationException
3427
+	 */
3428
+	public function _create_model_query_info_carrier($query_params)
3429
+	{
3430
+		if (! is_array($query_params)) {
3431
+			EE_Error::doing_it_wrong(
3432
+				'EEM_Base::_create_model_query_info_carrier',
3433
+				sprintf(
3434
+					__(
3435
+						'$query_params should be an array, you passed a variable of type %s',
3436
+						'event_espresso'
3437
+					),
3438
+					gettype($query_params)
3439
+				),
3440
+				'4.6.0'
3441
+			);
3442
+			$query_params = array();
3443
+		}
3444
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3445
+		// first check if we should alter the query to account for caps or not
3446
+		// because the caps might require us to do extra joins
3447
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3448
+			$query_params[0] = array_replace_recursive(
3449
+				$query_params[0],
3450
+				$this->caps_where_conditions(
3451
+					$query_params['caps']
3452
+				)
3453
+			);
3454
+		}
3455
+
3456
+		// check if we should alter the query to remove data related to protected
3457
+		// custom post types
3458
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3459
+			$where_param_key_for_password = $this->modelChainAndPassword();
3460
+			// only include if related to a cpt where no password has been set
3461
+			$query_params[0]['OR*nopassword'] = array(
3462
+				$where_param_key_for_password => '',
3463
+				$where_param_key_for_password . '*' => array('IS_NULL')
3464
+			);
3465
+		}
3466
+		$query_object = $this->_extract_related_models_from_query($query_params);
3467
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3468
+		foreach ($query_params[0] as $key => $value) {
3469
+			if (is_int($key)) {
3470
+				throw new EE_Error(
3471
+					sprintf(
3472
+						__(
3473
+							"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.",
3474
+							"event_espresso"
3475
+						),
3476
+						$key,
3477
+						var_export($value, true),
3478
+						var_export($query_params, true),
3479
+						get_class($this)
3480
+					)
3481
+				);
3482
+			}
3483
+		}
3484
+		if (
3485
+			array_key_exists('default_where_conditions', $query_params)
3486
+			&& ! empty($query_params['default_where_conditions'])
3487
+		) {
3488
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3489
+		} else {
3490
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3491
+		}
3492
+		$query_params[0] = array_merge(
3493
+			$this->_get_default_where_conditions_for_models_in_query(
3494
+				$query_object,
3495
+				$use_default_where_conditions,
3496
+				$query_params[0]
3497
+			),
3498
+			$query_params[0]
3499
+		);
3500
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3501
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3502
+		// So we need to setup a subquery and use that for the main join.
3503
+		// Note for now this only works on the primary table for the model.
3504
+		// So for instance, you could set the limit array like this:
3505
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3506
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3507
+			$query_object->set_main_model_join_sql(
3508
+				$this->_construct_limit_join_select(
3509
+					$query_params['on_join_limit'][0],
3510
+					$query_params['on_join_limit'][1]
3511
+				)
3512
+			);
3513
+		}
3514
+		// set limit
3515
+		if (array_key_exists('limit', $query_params)) {
3516
+			if (is_array($query_params['limit'])) {
3517
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
+					$e = sprintf(
3519
+						__(
3520
+							"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)",
3521
+							"event_espresso"
3522
+						),
3523
+						http_build_query($query_params['limit'])
3524
+					);
3525
+					throw new EE_Error($e . "|" . $e);
3526
+				}
3527
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
+			} elseif (! empty($query_params['limit'])) {
3530
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3531
+			}
3532
+		}
3533
+		// set order by
3534
+		if (array_key_exists('order_by', $query_params)) {
3535
+			if (is_array($query_params['order_by'])) {
3536
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3537
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3538
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3539
+				if (array_key_exists('order', $query_params)) {
3540
+					throw new EE_Error(
3541
+						sprintf(
3542
+							__(
3543
+								"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 ",
3544
+								"event_espresso"
3545
+							),
3546
+							get_class($this),
3547
+							implode(", ", array_keys($query_params['order_by'])),
3548
+							implode(", ", $query_params['order_by']),
3549
+							$query_params['order']
3550
+						)
3551
+					);
3552
+				}
3553
+				$this->_extract_related_models_from_sub_params_array_keys(
3554
+					$query_params['order_by'],
3555
+					$query_object,
3556
+					'order_by'
3557
+				);
3558
+				// assume it's an array of fields to order by
3559
+				$order_array = array();
3560
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561
+					$order = $this->_extract_order($order);
3562
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
+				}
3564
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
+			} elseif (! empty($query_params['order_by'])) {
3566
+				$this->_extract_related_model_info_from_query_param(
3567
+					$query_params['order_by'],
3568
+					$query_object,
3569
+					'order',
3570
+					$query_params['order_by']
3571
+				);
3572
+				$order = isset($query_params['order'])
3573
+					? $this->_extract_order($query_params['order'])
3574
+					: 'DESC';
3575
+				$query_object->set_order_by_sql(
3576
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
+				);
3578
+			}
3579
+		}
3580
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3581
+		if (
3582
+			! array_key_exists('order_by', $query_params)
3583
+			&& array_key_exists('order', $query_params)
3584
+			&& ! empty($query_params['order'])
3585
+		) {
3586
+			$pk_field = $this->get_primary_key_field();
3587
+			$order = $this->_extract_order($query_params['order']);
3588
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
+		}
3590
+		// set group by
3591
+		if (array_key_exists('group_by', $query_params)) {
3592
+			if (is_array($query_params['group_by'])) {
3593
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3594
+				$group_by_array = array();
3595
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
+				}
3598
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
+			} elseif (! empty($query_params['group_by'])) {
3600
+				$query_object->set_group_by_sql(
3601
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
+				);
3603
+			}
3604
+		}
3605
+		// set having
3606
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
+		}
3609
+		// now, just verify they didn't pass anything wack
3610
+		foreach ($query_params as $query_key => $query_value) {
3611
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
+				throw new EE_Error(
3613
+					sprintf(
3614
+						__(
3615
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
+							'event_espresso'
3617
+						),
3618
+						$query_key,
3619
+						get_class($this),
3620
+						//                      print_r( $this->_allowed_query_params, TRUE )
3621
+						implode(',', $this->_allowed_query_params)
3622
+					)
3623
+				);
3624
+			}
3625
+		}
3626
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3627
+		if (empty($main_model_join_sql)) {
3628
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
+		}
3630
+		return $query_object;
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Gets the where conditions that should be imposed on the query based on the
3637
+	 * context (eg reading frontend, backend, edit or delete).
3638
+	 *
3639
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3640
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3641
+	 * @throws EE_Error
3642
+	 */
3643
+	public function caps_where_conditions($context = self::caps_read)
3644
+	{
3645
+		EEM_Base::verify_is_valid_cap_context($context);
3646
+		$cap_where_conditions = array();
3647
+		$cap_restrictions = $this->caps_missing($context);
3648
+		/**
3649
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
+		 */
3651
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
+			$cap_where_conditions = array_replace_recursive(
3653
+				$cap_where_conditions,
3654
+				$restriction_if_no_cap->get_default_where_conditions()
3655
+			);
3656
+		}
3657
+		return apply_filters(
3658
+			'FHEE__EEM_Base__caps_where_conditions__return',
3659
+			$cap_where_conditions,
3660
+			$this,
3661
+			$context,
3662
+			$cap_restrictions
3663
+		);
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
+	 * otherwise throws an exception
3671
+	 *
3672
+	 * @param string $should_be_order_string
3673
+	 * @return string either ASC, asc, DESC or desc
3674
+	 * @throws EE_Error
3675
+	 */
3676
+	private function _extract_order($should_be_order_string)
3677
+	{
3678
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
+			return $should_be_order_string;
3680
+		}
3681
+		throw new EE_Error(
3682
+			sprintf(
3683
+				__(
3684
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
+					"event_espresso"
3686
+				),
3687
+				get_class($this),
3688
+				$should_be_order_string
3689
+			)
3690
+		);
3691
+	}
3692
+
3693
+
3694
+
3695
+	/**
3696
+	 * Looks at all the models which are included in this query, and asks each
3697
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
+	 * so they can be merged
3699
+	 *
3700
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
+	 *                                                                  'none' means NO default where conditions will
3703
+	 *                                                                  be used AT ALL during this query.
3704
+	 *                                                                  'other_models_only' means default where
3705
+	 *                                                                  conditions from other models will be used, but
3706
+	 *                                                                  not for this primary model. 'all', the default,
3707
+	 *                                                                  means default where conditions will apply as
3708
+	 *                                                                  normal
3709
+	 * @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
3710
+	 * @throws EE_Error
3711
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
+	 */
3713
+	private function _get_default_where_conditions_for_models_in_query(
3714
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3715
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
+		$where_query_params = array()
3717
+	) {
3718
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
+			throw new EE_Error(sprintf(
3721
+				__(
3722
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
+					"event_espresso"
3724
+				),
3725
+				$use_default_where_conditions,
3726
+				implode(", ", $allowed_used_default_where_conditions_values)
3727
+			));
3728
+		}
3729
+		$universal_query_params = array();
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
+			} else {
3742
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3743
+				continue;
3744
+			}
3745
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3746
+				$related_model_universal_where_params,
3747
+				$where_query_params,
3748
+				$related_model,
3749
+				$model_relation_path
3750
+			);
3751
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
+				$universal_query_params,
3753
+				$overrides
3754
+			);
3755
+		}
3756
+		return $universal_query_params;
3757
+	}
3758
+
3759
+
3760
+
3761
+	/**
3762
+	 * Determines whether or not we should use default where conditions for the model in question
3763
+	 * (this model, or other related models).
3764
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
+	 * We should use default where conditions on related models when they requested to use default where conditions
3767
+	 * on all models, or specifically just on other related models
3768
+	 * @param      $default_where_conditions_value
3769
+	 * @param bool $for_this_model false means this is for OTHER related models
3770
+	 * @return bool
3771
+	 */
3772
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
+	{
3774
+		return (
3775
+				   $for_this_model
3776
+				   && in_array(
3777
+					   $default_where_conditions_value,
3778
+					   array(
3779
+						   EEM_Base::default_where_conditions_all,
3780
+						   EEM_Base::default_where_conditions_this_only,
3781
+						   EEM_Base::default_where_conditions_minimum_others,
3782
+					   ),
3783
+					   true
3784
+				   )
3785
+			   )
3786
+			   || (
3787
+				   ! $for_this_model
3788
+				   && in_array(
3789
+					   $default_where_conditions_value,
3790
+					   array(
3791
+						   EEM_Base::default_where_conditions_all,
3792
+						   EEM_Base::default_where_conditions_others_only,
3793
+					   ),
3794
+					   true
3795
+				   )
3796
+			   );
3797
+	}
3798
+
3799
+	/**
3800
+	 * Determines whether or not we should use default minimum conditions for the model in question
3801
+	 * (this model, or other related models).
3802
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
+	 * where conditions.
3804
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
+	 * on this model or others
3806
+	 * @param      $default_where_conditions_value
3807
+	 * @param bool $for_this_model false means this is for OTHER related models
3808
+	 * @return bool
3809
+	 */
3810
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
+	{
3812
+		return (
3813
+				   $for_this_model
3814
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
+			   )
3816
+			   || (
3817
+				   ! $for_this_model
3818
+				   && in_array(
3819
+					   $default_where_conditions_value,
3820
+					   array(
3821
+						   EEM_Base::default_where_conditions_minimum_others,
3822
+						   EEM_Base::default_where_conditions_minimum_all,
3823
+					   ),
3824
+					   true
3825
+				   )
3826
+			   );
3827
+	}
3828
+
3829
+
3830
+	/**
3831
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
+	 * then we also add a special where condition which allows for that model's primary key
3833
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
+	 *
3836
+	 * @param array    $default_where_conditions
3837
+	 * @param array    $provided_where_conditions
3838
+	 * @param EEM_Base $model
3839
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3840
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
+	 * @throws EE_Error
3842
+	 */
3843
+	private function _override_defaults_or_make_null_friendly(
3844
+		$default_where_conditions,
3845
+		$provided_where_conditions,
3846
+		$model,
3847
+		$model_relation_path
3848
+	) {
3849
+		$null_friendly_where_conditions = array();
3850
+		$none_overridden = true;
3851
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
+		foreach ($default_where_conditions as $key => $val) {
3853
+			if (isset($provided_where_conditions[ $key ])) {
3854
+				$none_overridden = false;
3855
+			} else {
3856
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+			}
3858
+		}
3859
+		if ($none_overridden && $default_where_conditions) {
3860
+			if ($model->has_primary_key_field()) {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+																				. "."
3863
+																				. $model->primary_key_name() ] = array('IS NULL');
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3875
-     * default where conditions on all get_all, update, and delete queries done by this model.
3876
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3878
-     *
3879
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3881
-     */
3882
-    private function _get_default_where_conditions($model_relation_path = '')
3883
-    {
3884
-        if ($this->_ignore_where_strategy) {
3885
-            return array();
3886
-        }
3887
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
-    }
3889
-
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3901
-     */
3902
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3903
-    {
3904
-        if ($this->_ignore_where_strategy) {
3905
-            return array();
3906
-        }
3907
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
-    }
3909
-
3910
-
3911
-
3912
-    /**
3913
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
-     *
3916
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3917
-     * @return string
3918
-     * @throws EE_Error
3919
-     */
3920
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
-    {
3922
-        $selects = $this->_get_columns_to_select_for_this_model();
3923
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3924
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
-            foreach ($other_model_selects as $key => $value) {
3927
-                $selects[] = $value;
3928
-            }
3929
-        }
3930
-        return implode(", ", $selects);
3931
-    }
3932
-
3933
-
3934
-
3935
-    /**
3936
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3937
-     * So that's going to be the columns for all the fields on the model
3938
-     *
3939
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3940
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3941
-     */
3942
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3943
-    {
3944
-        $fields = $this->field_settings();
3945
-        $selects = array();
3946
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
-            $model_relation_chain,
3948
-            $this->get_this_model_name()
3949
-        );
3950
-        foreach ($fields as $field_obj) {
3951
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3952
-                         . $field_obj->get_table_alias()
3953
-                         . "."
3954
-                         . $field_obj->get_table_column()
3955
-                         . " AS '"
3956
-                         . $table_alias_with_model_relation_chain_prefix
3957
-                         . $field_obj->get_table_alias()
3958
-                         . "."
3959
-                         . $field_obj->get_table_column()
3960
-                         . "'";
3961
-        }
3962
-        // make sure we are also getting the PKs of each table
3963
-        $tables = $this->get_tables();
3964
-        if (count($tables) > 1) {
3965
-            foreach ($tables as $table_obj) {
3966
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
-                                       . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3969
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
-                }
3971
-            }
3972
-        }
3973
-        return $selects;
3974
-    }
3975
-
3976
-
3977
-
3978
-    /**
3979
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3980
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3981
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3982
-     * SQL for joining, and the data types
3983
-     *
3984
-     * @param null|string                 $original_query_param
3985
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3986
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3987
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3988
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3989
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3990
-     *                                                          or 'Registration's
3991
-     * @param string                      $original_query_param what it originally was (eg
3992
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3993
-     *                                                          matches $query_param
3994
-     * @throws EE_Error
3995
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
-     */
3997
-    private function _extract_related_model_info_from_query_param(
3998
-        $query_param,
3999
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4000
-        $query_param_type,
4001
-        $original_query_param = null
4002
-    ) {
4003
-        if ($original_query_param === null) {
4004
-            $original_query_param = $query_param;
4005
-        }
4006
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4007
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4008
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4009
-        $allow_fields = in_array(
4010
-            $query_param_type,
4011
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4012
-            true
4013
-        );
4014
-        // check to see if we have a field on this model
4015
-        $this_model_fields = $this->field_settings(true);
4016
-        if (array_key_exists($query_param, $this_model_fields)) {
4017
-            if ($allow_fields) {
4018
-                return;
4019
-            }
4020
-            throw new EE_Error(
4021
-                sprintf(
4022
-                    __(
4023
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
-                        "event_espresso"
4025
-                    ),
4026
-                    $query_param,
4027
-                    get_class($this),
4028
-                    $query_param_type,
4029
-                    $original_query_param
4030
-                )
4031
-            );
4032
-        }
4033
-        // check if this is a special logic query param
4034
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
-            if ($allow_logic_query_params) {
4036
-                return;
4037
-            }
4038
-            throw new EE_Error(
4039
-                sprintf(
4040
-                    __(
4041
-                        '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',
4042
-                        'event_espresso'
4043
-                    ),
4044
-                    implode('", "', $this->_logic_query_param_keys),
4045
-                    $query_param,
4046
-                    get_class($this),
4047
-                    '<br />',
4048
-                    "\t"
4049
-                    . ' $passed_in_query_info = <pre>'
4050
-                    . print_r($passed_in_query_info, true)
4051
-                    . '</pre>'
4052
-                    . "\n\t"
4053
-                    . ' $query_param_type = '
4054
-                    . $query_param_type
4055
-                    . "\n\t"
4056
-                    . ' $original_query_param = '
4057
-                    . $original_query_param
4058
-                )
4059
-            );
4060
-        }
4061
-        // check if it's a custom selection
4062
-        if (
4063
-            $this->_custom_selections instanceof CustomSelects
4064
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
-        ) {
4066
-            return;
4067
-        }
4068
-        // check if has a model name at the beginning
4069
-        // and
4070
-        // check if it's a field on a related model
4071
-        if (
4072
-            $this->extractJoinModelFromQueryParams(
4073
-                $passed_in_query_info,
4074
-                $query_param,
4075
-                $original_query_param,
4076
-                $query_param_type
4077
-            )
4078
-        ) {
4079
-            return;
4080
-        }
4081
-
4082
-        // ok so $query_param didn't start with a model name
4083
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4084
-        // it's wack, that's what it is
4085
-        throw new EE_Error(
4086
-            sprintf(
4087
-                esc_html__(
4088
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4089
-                    "event_espresso"
4090
-                ),
4091
-                $query_param,
4092
-                get_class($this),
4093
-                $query_param_type,
4094
-                $original_query_param
4095
-            )
4096
-        );
4097
-    }
4098
-
4099
-
4100
-    /**
4101
-     * Extracts any possible join model information from the provided possible_join_string.
4102
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4103
-     * parts that should be added to the query.
4104
-     *
4105
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4106
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4107
-     * @param null|string                 $original_query_param
4108
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4109
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4110
-     * @return bool  returns true if a join was added and false if not.
4111
-     * @throws EE_Error
4112
-     */
4113
-    private function extractJoinModelFromQueryParams(
4114
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4115
-        $possible_join_string,
4116
-        $original_query_param,
4117
-        $query_parameter_type
4118
-    ) {
4119
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
-                if ($possible_join_string === '') {
4124
-                    // nothing left to $query_param
4125
-                    // we should actually end in a field name, not a model like this!
4126
-                    throw new EE_Error(
4127
-                        sprintf(
4128
-                            esc_html__(
4129
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
-                                "event_espresso"
4131
-                            ),
4132
-                            $possible_join_string,
4133
-                            $query_parameter_type,
4134
-                            get_class($this),
4135
-                            $valid_related_model_name
4136
-                        )
4137
-                    );
4138
-                }
4139
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
-                $related_model_obj->_extract_related_model_info_from_query_param(
4141
-                    $possible_join_string,
4142
-                    $query_info_carrier,
4143
-                    $query_parameter_type,
4144
-                    $original_query_param
4145
-                );
4146
-                return true;
4147
-            }
4148
-            if ($possible_join_string === $valid_related_model_name) {
4149
-                $this->_add_join_to_model(
4150
-                    $valid_related_model_name,
4151
-                    $query_info_carrier,
4152
-                    $original_query_param
4153
-                );
4154
-                return true;
4155
-            }
4156
-        }
4157
-        return false;
4158
-    }
4159
-
4160
-
4161
-    /**
4162
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4164
-     * @throws EE_Error
4165
-     */
4166
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4167
-    {
4168
-        if (
4169
-            $this->_custom_selections instanceof CustomSelects
4170
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4171
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4172
-            )
4173
-        ) {
4174
-            $original_selects = $this->_custom_selections->originalSelects();
4175
-            foreach ($original_selects as $alias => $select_configuration) {
4176
-                $this->extractJoinModelFromQueryParams(
4177
-                    $query_info_carrier,
4178
-                    $select_configuration[0],
4179
-                    $select_configuration[0],
4180
-                    'custom_selects'
4181
-                );
4182
-            }
4183
-        }
4184
-    }
4185
-
4186
-
4187
-
4188
-    /**
4189
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
-     * and store it on $passed_in_query_info
4191
-     *
4192
-     * @param string                      $model_name
4193
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4195
-     *                                                          model and $model_name. Eg, if we are querying Event,
4196
-     *                                                          and are adding a join to 'Payment' with the original
4197
-     *                                                          query param key
4198
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4200
-     *                                                          Payment wants to add default query params so that it
4201
-     *                                                          will know what models to prepend onto its default query
4202
-     *                                                          params or in case it wants to rename tables (in case
4203
-     *                                                          there are multiple joins to the same table)
4204
-     * @return void
4205
-     * @throws EE_Error
4206
-     */
4207
-    private function _add_join_to_model(
4208
-        $model_name,
4209
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
-        $original_query_param
4211
-    ) {
4212
-        $relation_obj = $this->related_settings_for($model_name);
4213
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
-        // check if the relation is HABTM, because then we're essentially doing two joins
4215
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4217
-            $join_model_obj = $relation_obj->get_join_model();
4218
-            // replace the model specified with the join model for this relation chain, whi
4219
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4220
-                $model_name,
4221
-                $join_model_obj->get_this_model_name(),
4222
-                $model_relation_chain
4223
-            );
4224
-            $passed_in_query_info->merge(
4225
-                new EE_Model_Query_Info_Carrier(
4226
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4227
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4228
-                )
4229
-            );
4230
-        }
4231
-        // now just join to the other table pointed to by the relation object, and add its data types
4232
-        $passed_in_query_info->merge(
4233
-            new EE_Model_Query_Info_Carrier(
4234
-                array($model_relation_chain => $model_name),
4235
-                $relation_obj->get_join_statement($model_relation_chain)
4236
-            )
4237
-        );
4238
-    }
4239
-
4240
-
4241
-
4242
-    /**
4243
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
-     *
4245
-     * @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
4246
-     * @return string of SQL
4247
-     * @throws EE_Error
4248
-     */
4249
-    private function _construct_where_clause($where_params)
4250
-    {
4251
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252
-        if ($SQL) {
4253
-            return " WHERE " . $SQL;
4254
-        }
4255
-        return '';
4256
-    }
4257
-
4258
-
4259
-
4260
-    /**
4261
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
-     * and should be passed HAVING parameters, not WHERE parameters
4263
-     *
4264
-     * @param array $having_params
4265
-     * @return string
4266
-     * @throws EE_Error
4267
-     */
4268
-    private function _construct_having_clause($having_params)
4269
-    {
4270
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
-        if ($SQL) {
4272
-            return " HAVING " . $SQL;
4273
-        }
4274
-        return '';
4275
-    }
4276
-
4277
-
4278
-    /**
4279
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
-     * Event_Meta.meta_value = 'foo'))"
4281
-     *
4282
-     * @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
4283
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4284
-     * @throws EE_Error
4285
-     * @return string of SQL
4286
-     */
4287
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4288
-    {
4289
-        $where_clauses = array();
4290
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4292
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4293
-                switch ($query_param) {
4294
-                    case 'not':
4295
-                    case 'NOT':
4296
-                        $where_clauses[] = "! ("
4297
-                                           . $this->_construct_condition_clause_recursive(
4298
-                                               $op_and_value_or_sub_condition,
4299
-                                               $glue
4300
-                                           )
4301
-                                           . ")";
4302
-                        break;
4303
-                    case 'and':
4304
-                    case 'AND':
4305
-                        $where_clauses[] = " ("
4306
-                                           . $this->_construct_condition_clause_recursive(
4307
-                                               $op_and_value_or_sub_condition,
4308
-                                               ' AND '
4309
-                                           )
4310
-                                           . ")";
4311
-                        break;
4312
-                    case 'or':
4313
-                    case 'OR':
4314
-                        $where_clauses[] = " ("
4315
-                                           . $this->_construct_condition_clause_recursive(
4316
-                                               $op_and_value_or_sub_condition,
4317
-                                               ' OR '
4318
-                                           )
4319
-                                           . ")";
4320
-                        break;
4321
-                }
4322
-            } else {
4323
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4324
-                // if it's not a normal field, maybe it's a custom selection?
4325
-                if (! $field_obj) {
4326
-                    if ($this->_custom_selections instanceof CustomSelects) {
4327
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328
-                    } else {
4329
-                        throw new EE_Error(sprintf(__(
4330
-                            "%s is neither a valid model field name, nor a custom selection",
4331
-                            "event_espresso"
4332
-                        ), $query_param));
4333
-                    }
4334
-                }
4335
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4337
-            }
4338
-        }
4339
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4340
-    }
4341
-
4342
-
4343
-
4344
-    /**
4345
-     * Takes the input parameter and extract the table name (alias) and column name
4346
-     *
4347
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4348
-     * @throws EE_Error
4349
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4350
-     */
4351
-    private function _deduce_column_name_from_query_param($query_param)
4352
-    {
4353
-        $field = $this->_deduce_field_from_query_param($query_param);
4354
-        if ($field) {
4355
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4356
-                $field->get_model_name(),
4357
-                $query_param
4358
-            );
4359
-            return $table_alias_prefix . $field->get_qualified_column();
4360
-        }
4361
-        if (
4362
-            $this->_custom_selections instanceof CustomSelects
4363
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4364
-        ) {
4365
-            // maybe it's custom selection item?
4366
-            // if so, just use it as the "column name"
4367
-            return $query_param;
4368
-        }
4369
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4370
-            ? implode(',', $this->_custom_selections->columnAliases())
4371
-            : '';
4372
-        throw new EE_Error(
4373
-            sprintf(
4374
-                __(
4375
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4376
-                    "event_espresso"
4377
-                ),
4378
-                $query_param,
4379
-                $custom_select_aliases
4380
-            )
4381
-        );
4382
-    }
4383
-
4384
-
4385
-
4386
-    /**
4387
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4388
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4389
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4390
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4391
-     *
4392
-     * @param string $condition_query_param_key
4393
-     * @return string
4394
-     */
4395
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4396
-    {
4397
-        $pos_of_star = strpos($condition_query_param_key, '*');
4398
-        if ($pos_of_star === false) {
4399
-            return $condition_query_param_key;
4400
-        }
4401
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4402
-        return $condition_query_param_sans_star;
4403
-    }
4404
-
4405
-
4406
-
4407
-    /**
4408
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4409
-     *
4410
-     * @param                            mixed      array | string    $op_and_value
4411
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4412
-     * @throws EE_Error
4413
-     * @return string
4414
-     */
4415
-    private function _construct_op_and_value($op_and_value, $field_obj)
4416
-    {
4417
-        if (is_array($op_and_value)) {
4418
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
-            if (! $operator) {
4420
-                $php_array_like_string = array();
4421
-                foreach ($op_and_value as $key => $value) {
4422
-                    $php_array_like_string[] = "$key=>$value";
4423
-                }
4424
-                throw new EE_Error(
4425
-                    sprintf(
4426
-                        __(
4427
-                            "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))",
4428
-                            "event_espresso"
4429
-                        ),
4430
-                        implode(",", $php_array_like_string)
4431
-                    )
4432
-                );
4433
-            }
4434
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4435
-        } else {
4436
-            $operator = '=';
4437
-            $value = $op_and_value;
4438
-        }
4439
-        // check to see if the value is actually another field
4440
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4442
-        }
4443
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444
-            // in this case, the value should be an array, or at least a comma-separated list
4445
-            // it will need to handle a little differently
4446
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4447
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4448
-            return $operator . SP . $cleaned_value;
4449
-        }
4450
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451
-            // the value should be an array with count of two.
4452
-            if (count($value) !== 2) {
4453
-                throw new EE_Error(
4454
-                    sprintf(
4455
-                        __(
4456
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4457
-                            'event_espresso'
4458
-                        ),
4459
-                        "BETWEEN"
4460
-                    )
4461
-                );
4462
-            }
4463
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
-            return $operator . SP . $cleaned_value;
4465
-        }
4466
-        if (in_array($operator, $this->valid_null_style_operators())) {
4467
-            if ($value !== null) {
4468
-                throw new EE_Error(
4469
-                    sprintf(
4470
-                        __(
4471
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4472
-                            "event_espresso"
4473
-                        ),
4474
-                        $value,
4475
-                        $operator
4476
-                    )
4477
-                );
4478
-            }
4479
-            return $operator;
4480
-        }
4481
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4483
-            // remove other junk. So just treat it as a string.
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4485
-        }
4486
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4488
-        }
4489
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490
-            throw new EE_Error(
4491
-                sprintf(
4492
-                    __(
4493
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4494
-                        'event_espresso'
4495
-                    ),
4496
-                    $operator,
4497
-                    $operator
4498
-                )
4499
-            );
4500
-        }
4501
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502
-            throw new EE_Error(
4503
-                sprintf(
4504
-                    __(
4505
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4506
-                        'event_espresso'
4507
-                    ),
4508
-                    $operator,
4509
-                    $operator
4510
-                )
4511
-            );
4512
-        }
4513
-        throw new EE_Error(
4514
-            sprintf(
4515
-                __(
4516
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4517
-                    "event_espresso"
4518
-                ),
4519
-                http_build_query($op_and_value)
4520
-            )
4521
-        );
4522
-    }
4523
-
4524
-
4525
-
4526
-    /**
4527
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4528
-     *
4529
-     * @param array                      $values
4530
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4531
-     *                                              '%s'
4532
-     * @return string
4533
-     * @throws EE_Error
4534
-     */
4535
-    public function _construct_between_value($values, $field_obj)
4536
-    {
4537
-        $cleaned_values = array();
4538
-        foreach ($values as $value) {
4539
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540
-        }
4541
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4542
-    }
4543
-
4544
-
4545
-
4546
-    /**
4547
-     * Takes an array or a comma-separated list of $values and cleans them
4548
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4549
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4550
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4551
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4552
-     *
4553
-     * @param mixed                      $values    array or comma-separated string
4554
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4555
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4556
-     * @throws EE_Error
4557
-     */
4558
-    public function _construct_in_value($values, $field_obj)
4559
-    {
4560
-        // check if the value is a CSV list
4561
-        if (is_string($values)) {
4562
-            // in which case, turn it into an array
4563
-            $values = explode(",", $values);
4564
-        }
4565
-        $cleaned_values = array();
4566
-        foreach ($values as $value) {
4567
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4568
-        }
4569
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4570
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4571
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4572
-        if (empty($cleaned_values)) {
4573
-            $all_fields = $this->field_settings();
4574
-            $a_field = array_shift($all_fields);
4575
-            $main_table = $this->_get_main_table();
4576
-            $cleaned_values[] = "SELECT "
4577
-                                . $a_field->get_table_column()
4578
-                                . " FROM "
4579
-                                . $main_table->get_table_name()
4580
-                                . " WHERE FALSE";
4581
-        }
4582
-        return "(" . implode(",", $cleaned_values) . ")";
4583
-    }
4584
-
4585
-
4586
-
4587
-    /**
4588
-     * @param mixed                      $value
4589
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4590
-     * @throws EE_Error
4591
-     * @return false|null|string
4592
-     */
4593
-    private function _wpdb_prepare_using_field($value, $field_obj)
4594
-    {
4595
-        /** @type WPDB $wpdb */
4596
-        global $wpdb;
4597
-        if ($field_obj instanceof EE_Model_Field_Base) {
4598
-            return $wpdb->prepare(
4599
-                $field_obj->get_wpdb_data_type(),
4600
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4601
-            );
4602
-        } //$field_obj should really just be a data type
4603
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604
-            throw new EE_Error(
4605
-                sprintf(
4606
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4607
-                    $field_obj,
4608
-                    implode(",", $this->_valid_wpdb_data_types)
4609
-                )
4610
-            );
4611
-        }
4612
-        return $wpdb->prepare($field_obj, $value);
4613
-    }
4614
-
4615
-
4616
-
4617
-    /**
4618
-     * Takes the input parameter and finds the model field that it indicates.
4619
-     *
4620
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4621
-     * @throws EE_Error
4622
-     * @return EE_Model_Field_Base
4623
-     */
4624
-    protected function _deduce_field_from_query_param($query_param_name)
4625
-    {
4626
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4627
-        // which will help us find the database table and column
4628
-        $query_param_parts = explode(".", $query_param_name);
4629
-        if (empty($query_param_parts)) {
4630
-            throw new EE_Error(sprintf(__(
4631
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4632
-                'event_espresso'
4633
-            ), $query_param_name));
4634
-        }
4635
-        $number_of_parts = count($query_param_parts);
4636
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4637
-        if ($number_of_parts === 1) {
4638
-            $field_name = $last_query_param_part;
4639
-            $model_obj = $this;
4640
-        } else {// $number_of_parts >= 2
4641
-            // the last part is the column name, and there are only 2parts. therefore...
4642
-            $field_name = $last_query_param_part;
4643
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4644
-        }
4645
-        try {
4646
-            return $model_obj->field_settings_for($field_name);
4647
-        } catch (EE_Error $e) {
4648
-            return null;
4649
-        }
4650
-    }
4651
-
4652
-
4653
-
4654
-    /**
4655
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4656
-     * alias and column which corresponds to it
4657
-     *
4658
-     * @param string $field_name
4659
-     * @throws EE_Error
4660
-     * @return string
4661
-     */
4662
-    public function _get_qualified_column_for_field($field_name)
4663
-    {
4664
-        $all_fields = $this->field_settings();
4665
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4666
-        if ($field) {
4667
-            return $field->get_qualified_column();
4668
-        }
4669
-        throw new EE_Error(
4670
-            sprintf(
4671
-                __(
4672
-                    "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.",
4673
-                    'event_espresso'
4674
-                ),
4675
-                $field_name,
4676
-                get_class($this)
4677
-            )
4678
-        );
4679
-    }
4680
-
4681
-
4682
-
4683
-    /**
4684
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4685
-     * Example usage:
4686
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4687
-     *      array(),
4688
-     *      ARRAY_A,
4689
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4690
-     *  );
4691
-     * is equivalent to
4692
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4693
-     * and
4694
-     *  EEM_Event::instance()->get_all_wpdb_results(
4695
-     *      array(
4696
-     *          array(
4697
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4698
-     *          ),
4699
-     *          ARRAY_A,
4700
-     *          implode(
4701
-     *              ', ',
4702
-     *              array_merge(
4703
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4704
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4705
-     *              )
4706
-     *          )
4707
-     *      )
4708
-     *  );
4709
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4710
-     *
4711
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4712
-     *                                            and the one whose fields you are selecting for example: when querying
4713
-     *                                            tickets model and selecting fields from the tickets model you would
4714
-     *                                            leave this parameter empty, because no models are needed to join
4715
-     *                                            between the queried model and the selected one. Likewise when
4716
-     *                                            querying the datetime model and selecting fields from the tickets
4717
-     *                                            model, it would also be left empty, because there is a direct
4718
-     *                                            relation from datetimes to tickets, so no model is needed to join
4719
-     *                                            them together. However, when querying from the event model and
4720
-     *                                            selecting fields from the ticket model, you should provide the string
4721
-     *                                            'Datetime', indicating that the event model must first join to the
4722
-     *                                            datetime model in order to find its relation to ticket model.
4723
-     *                                            Also, when querying from the venue model and selecting fields from
4724
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4725
-     *                                            indicating you need to join the venue model to the event model,
4726
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4727
-     *                                            This string is used to deduce the prefix that gets added onto the
4728
-     *                                            models' tables qualified columns
4729
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4730
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4731
-     *                                            qualified column names
4732
-     * @return array|string
4733
-     */
4734
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735
-    {
4736
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4737
-        $qualified_columns = array();
4738
-        foreach ($this->field_settings() as $field_name => $field) {
4739
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4740
-        }
4741
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742
-    }
4743
-
4744
-
4745
-
4746
-    /**
4747
-     * constructs the select use on special limit joins
4748
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4749
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4750
-     * (as that is typically where the limits would be set).
4751
-     *
4752
-     * @param  string       $table_alias The table the select is being built for
4753
-     * @param  mixed|string $limit       The limit for this select
4754
-     * @return string                The final select join element for the query.
4755
-     */
4756
-    public function _construct_limit_join_select($table_alias, $limit)
4757
-    {
4758
-        $SQL = '';
4759
-        foreach ($this->_tables as $table_obj) {
4760
-            if ($table_obj instanceof EE_Primary_Table) {
4761
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4762
-                    ? $table_obj->get_select_join_limit($limit)
4763
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4764
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4765
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4766
-                    ? $table_obj->get_select_join_limit_join($limit)
4767
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4768
-            }
4769
-        }
4770
-        return $SQL;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4777
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4778
-     *
4779
-     * @return string SQL
4780
-     * @throws EE_Error
4781
-     */
4782
-    public function _construct_internal_join()
4783
-    {
4784
-        $SQL = $this->_get_main_table()->get_table_sql();
4785
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4786
-        return $SQL;
4787
-    }
4788
-
4789
-
4790
-
4791
-    /**
4792
-     * Constructs the SQL for joining all the tables on this model.
4793
-     * Normally $alias should be the primary table's alias, but in cases where
4794
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4795
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4796
-     * alias, this will construct SQL like:
4797
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4798
-     * With $alias being a secondary table's alias, this will construct SQL like:
4799
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4800
-     *
4801
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4802
-     * @return string
4803
-     */
4804
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4805
-    {
4806
-        $SQL = '';
4807
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4808
-        foreach ($this->_tables as $table_obj) {
4809
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4810
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4811
-                    // so we're joining to this table, meaning the table is already in
4812
-                    // the FROM statement, BUT the primary table isn't. So we want
4813
-                    // to add the inverse join sql
4814
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4815
-                } else {
4816
-                    // just add a regular JOIN to this table from the primary table
4817
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4818
-                }
4819
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4820
-        }
4821
-        return $SQL;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
-     * their data type (eg, '%s', '%d', etc)
4830
-     *
4831
-     * @return array
4832
-     */
4833
-    public function _get_data_types()
4834
-    {
4835
-        $data_types = array();
4836
-        foreach ($this->field_settings() as $field_obj) {
4837
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
-            /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
-        }
4841
-        return $data_types;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4848
-     *
4849
-     * @param string $model_name
4850
-     * @throws EE_Error
4851
-     * @return EEM_Base
4852
-     */
4853
-    public function get_related_model_obj($model_name)
4854
-    {
4855
-        $model_classname = "EEM_" . $model_name;
4856
-        if (! class_exists($model_classname)) {
4857
-            throw new EE_Error(sprintf(__(
4858
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859
-                'event_espresso'
4860
-            ), $model_name, $model_classname));
4861
-        }
4862
-        return call_user_func($model_classname . "::instance");
4863
-    }
4864
-
4865
-
4866
-
4867
-    /**
4868
-     * Returns the array of EE_ModelRelations for this model.
4869
-     *
4870
-     * @return EE_Model_Relation_Base[]
4871
-     */
4872
-    public function relation_settings()
4873
-    {
4874
-        return $this->_model_relations;
4875
-    }
4876
-
4877
-
4878
-
4879
-    /**
4880
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4881
-     * because without THOSE models, this model probably doesn't have much purpose.
4882
-     * (Eg, without an event, datetimes have little purpose.)
4883
-     *
4884
-     * @return EE_Belongs_To_Relation[]
4885
-     */
4886
-    public function belongs_to_relations()
4887
-    {
4888
-        $belongs_to_relations = array();
4889
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4892
-            }
4893
-        }
4894
-        return $belongs_to_relations;
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * Returns the specified EE_Model_Relation, or throws an exception
4901
-     *
4902
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4903
-     * @throws EE_Error
4904
-     * @return EE_Model_Relation_Base
4905
-     */
4906
-    public function related_settings_for($relation_name)
4907
-    {
4908
-        $relatedModels = $this->relation_settings();
4909
-        if (! array_key_exists($relation_name, $relatedModels)) {
4910
-            throw new EE_Error(
4911
-                sprintf(
4912
-                    __(
4913
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4914
-                        'event_espresso'
4915
-                    ),
4916
-                    $relation_name,
4917
-                    $this->_get_class_name(),
4918
-                    implode(', ', array_keys($relatedModels))
4919
-                )
4920
-            );
4921
-        }
4922
-        return $relatedModels[ $relation_name ];
4923
-    }
4924
-
4925
-
4926
-
4927
-    /**
4928
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4929
-     * fields
4930
-     *
4931
-     * @param string $fieldName
4932
-     * @param boolean $include_db_only_fields
4933
-     * @throws EE_Error
4934
-     * @return EE_Model_Field_Base
4935
-     */
4936
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4937
-    {
4938
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4939
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4940
-            throw new EE_Error(sprintf(
4941
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4942
-                $fieldName,
4943
-                get_class($this)
4944
-            ));
4945
-        }
4946
-        return $fieldSettings[ $fieldName ];
4947
-    }
4948
-
4949
-
4950
-
4951
-    /**
4952
-     * Checks if this field exists on this model
4953
-     *
4954
-     * @param string $fieldName a key in the model's _field_settings array
4955
-     * @return boolean
4956
-     */
4957
-    public function has_field($fieldName)
4958
-    {
4959
-        $fieldSettings = $this->field_settings(true);
4960
-        if (isset($fieldSettings[ $fieldName ])) {
4961
-            return true;
4962
-        }
4963
-        return false;
4964
-    }
4965
-
4966
-
4967
-
4968
-    /**
4969
-     * Returns whether or not this model has a relation to the specified model
4970
-     *
4971
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4972
-     * @return boolean
4973
-     */
4974
-    public function has_relation($relation_name)
4975
-    {
4976
-        $relations = $this->relation_settings();
4977
-        if (isset($relations[ $relation_name ])) {
4978
-            return true;
4979
-        }
4980
-        return false;
4981
-    }
4982
-
4983
-
4984
-
4985
-    /**
4986
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
-     * Eg, on EE_Answer that would be ANS_ID field object
4988
-     *
4989
-     * @param $field_obj
4990
-     * @return boolean
4991
-     */
4992
-    public function is_primary_key_field($field_obj)
4993
-    {
4994
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
-    }
4996
-
4997
-
4998
-
4999
-    /**
5000
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5001
-     * Eg, on EE_Answer that would be ANS_ID field object
5002
-     *
5003
-     * @return EE_Model_Field_Base
5004
-     * @throws EE_Error
5005
-     */
5006
-    public function get_primary_key_field()
5007
-    {
5008
-        if ($this->_primary_key_field === null) {
5009
-            foreach ($this->field_settings(true) as $field_obj) {
5010
-                if ($this->is_primary_key_field($field_obj)) {
5011
-                    $this->_primary_key_field = $field_obj;
5012
-                    break;
5013
-                }
5014
-            }
5015
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016
-                throw new EE_Error(sprintf(
5017
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
5018
-                    get_class($this)
5019
-                ));
5020
-            }
5021
-        }
5022
-        return $this->_primary_key_field;
5023
-    }
5024
-
5025
-
5026
-
5027
-    /**
5028
-     * Returns whether or not not there is a primary key on this model.
5029
-     * Internally does some caching.
5030
-     *
5031
-     * @return boolean
5032
-     */
5033
-    public function has_primary_key_field()
5034
-    {
5035
-        if ($this->_has_primary_key_field === null) {
5036
-            try {
5037
-                $this->get_primary_key_field();
5038
-                $this->_has_primary_key_field = true;
5039
-            } catch (EE_Error $e) {
5040
-                $this->_has_primary_key_field = false;
5041
-            }
5042
-        }
5043
-        return $this->_has_primary_key_field;
5044
-    }
5045
-
5046
-
5047
-
5048
-    /**
5049
-     * Finds the first field of type $field_class_name.
5050
-     *
5051
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5052
-     *                                 EE_Foreign_Key_Field, etc
5053
-     * @return EE_Model_Field_Base or null if none is found
5054
-     */
5055
-    public function get_a_field_of_type($field_class_name)
5056
-    {
5057
-        foreach ($this->field_settings() as $field) {
5058
-            if ($field instanceof $field_class_name) {
5059
-                return $field;
5060
-            }
5061
-        }
5062
-        return null;
5063
-    }
5064
-
5065
-
5066
-
5067
-    /**
5068
-     * Gets a foreign key field pointing to model.
5069
-     *
5070
-     * @param string $model_name eg Event, Registration, not EEM_Event
5071
-     * @return EE_Foreign_Key_Field_Base
5072
-     * @throws EE_Error
5073
-     */
5074
-    public function get_foreign_key_to($model_name)
5075
-    {
5076
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5077
-            foreach ($this->field_settings() as $field) {
5078
-                if (
5079
-                    $field instanceof EE_Foreign_Key_Field_Base
5080
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5081
-                ) {
5082
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5083
-                    break;
5084
-                }
5085
-            }
5086
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5087
-                throw new EE_Error(sprintf(__(
5088
-                    "There is no foreign key field pointing to model %s on model %s",
5089
-                    'event_espresso'
5090
-                ), $model_name, get_class($this)));
5091
-            }
5092
-        }
5093
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5094
-    }
5095
-
5096
-
5097
-
5098
-    /**
5099
-     * Gets the table name (including $wpdb->prefix) for the table alias
5100
-     *
5101
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5102
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5103
-     *                            Either one works
5104
-     * @return string
5105
-     */
5106
-    public function get_table_for_alias($table_alias)
5107
-    {
5108
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5110
-    }
5111
-
5112
-
5113
-
5114
-    /**
5115
-     * Returns a flat array of all field son this model, instead of organizing them
5116
-     * by table_alias as they are in the constructor.
5117
-     *
5118
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5119
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5120
-     */
5121
-    public function field_settings($include_db_only_fields = false)
5122
-    {
5123
-        if ($include_db_only_fields) {
5124
-            if ($this->_cached_fields === null) {
5125
-                $this->_cached_fields = array();
5126
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5127
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5129
-                    }
5130
-                }
5131
-            }
5132
-            return $this->_cached_fields;
5133
-        }
5134
-        if ($this->_cached_fields_non_db_only === null) {
5135
-            $this->_cached_fields_non_db_only = array();
5136
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5137
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                    /** @var $field_obj EE_Model_Field_Base */
5139
-                    if (! $field_obj->is_db_only_field()) {
5140
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5141
-                    }
5142
-                }
5143
-            }
5144
-        }
5145
-        return $this->_cached_fields_non_db_only;
5146
-    }
5147
-
5148
-
5149
-
5150
-    /**
5151
-     *        cycle though array of attendees and create objects out of each item
5152
-     *
5153
-     * @access        private
5154
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5155
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5156
-     *                           numerically indexed)
5157
-     * @throws EE_Error
5158
-     */
5159
-    protected function _create_objects($rows = array())
5160
-    {
5161
-        $array_of_objects = array();
5162
-        if (empty($rows)) {
5163
-            return array();
5164
-        }
5165
-        $count_if_model_has_no_primary_key = 0;
5166
-        $has_primary_key = $this->has_primary_key_field();
5167
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5168
-        foreach ((array) $rows as $row) {
5169
-            if (empty($row)) {
5170
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5171
-                return array();
5172
-            }
5173
-            // check if we've already set this object in the results array,
5174
-            // in which case there's no need to process it further (again)
5175
-            if ($has_primary_key) {
5176
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5177
-                    $row,
5178
-                    $primary_key_field->get_qualified_column(),
5179
-                    $primary_key_field->get_table_column()
5180
-                );
5181
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5182
-                    continue;
5183
-                }
5184
-            }
5185
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5186
-            if (! $classInstance) {
5187
-                throw new EE_Error(
5188
-                    sprintf(
5189
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5190
-                        $this->get_this_model_name(),
5191
-                        http_build_query($row)
5192
-                    )
5193
-                );
5194
-            }
5195
-            // set the timezone on the instantiated objects
5196
-            $classInstance->set_timezone($this->_timezone);
5197
-            // make sure if there is any timezone setting present that we set the timezone for the object
5198
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
-            $array_of_objects[ $key ] = $classInstance;
5200
-            // also, for all the relations of type BelongsTo, see if we can cache
5201
-            // those related models
5202
-            // (we could do this for other relations too, but if there are conditions
5203
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5204
-            // so it requires a little more thought than just caching them immediately...)
5205
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5206
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5207
-                    // check if this model's INFO is present. If so, cache it on the model
5208
-                    $other_model = $relation_obj->get_other_model();
5209
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5210
-                    // if we managed to make a model object from the results, cache it on the main model object
5211
-                    if ($other_model_obj_maybe) {
5212
-                        // set timezone on these other model objects if they are present
5213
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5214
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5215
-                    }
5216
-                }
5217
-            }
5218
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5219
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5220
-            // the field in the CustomSelects object
5221
-            if ($this->_custom_selections instanceof CustomSelects) {
5222
-                $classInstance->setCustomSelectsValues(
5223
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5224
-                );
5225
-            }
5226
-        }
5227
-        return $array_of_objects;
5228
-    }
5229
-
5230
-
5231
-    /**
5232
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5233
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5234
-     *
5235
-     * @param array $db_results_row
5236
-     * @return array
5237
-     */
5238
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5239
-    {
5240
-        $results = array();
5241
-        if ($this->_custom_selections instanceof CustomSelects) {
5242
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
-                if (isset($db_results_row[ $alias ])) {
5244
-                    $results[ $alias ] = $this->convertValueToDataType(
5245
-                        $db_results_row[ $alias ],
5246
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5247
-                    );
5248
-                }
5249
-            }
5250
-        }
5251
-        return $results;
5252
-    }
5253
-
5254
-
5255
-    /**
5256
-     * This will set the value for the given alias
5257
-     * @param string $value
5258
-     * @param string $datatype (one of %d, %s, %f)
5259
-     * @return int|string|float (int for %d, string for %s, float for %f)
5260
-     */
5261
-    protected function convertValueToDataType($value, $datatype)
5262
-    {
5263
-        switch ($datatype) {
5264
-            case '%f':
5265
-                return (float) $value;
5266
-            case '%d':
5267
-                return (int) $value;
5268
-            default:
5269
-                return (string) $value;
5270
-        }
5271
-    }
5272
-
5273
-
5274
-    /**
5275
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5276
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5277
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5278
-     * object (as set in the model_field!).
5279
-     *
5280
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5281
-     */
5282
-    public function create_default_object()
5283
-    {
5284
-        $this_model_fields_and_values = array();
5285
-        // setup the row using default values;
5286
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5287
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5288
-        }
5289
-        $className = $this->_get_class_name();
5290
-        $classInstance = EE_Registry::instance()
5291
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5292
-        return $classInstance;
5293
-    }
5294
-
5295
-
5296
-
5297
-    /**
5298
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5299
-     *                             or an stdClass where each property is the name of a column,
5300
-     * @return EE_Base_Class
5301
-     * @throws EE_Error
5302
-     */
5303
-    public function instantiate_class_from_array_or_object($cols_n_values)
5304
-    {
5305
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5306
-            $cols_n_values = get_object_vars($cols_n_values);
5307
-        }
5308
-        $primary_key = null;
5309
-        // make sure the array only has keys that are fields/columns on this model
5310
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5313
-        }
5314
-        $className = $this->_get_class_name();
5315
-        // check we actually found results that we can use to build our model object
5316
-        // if not, return null
5317
-        if ($this->has_primary_key_field()) {
5318
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
-                return null;
5320
-            }
5321
-        } elseif ($this->unique_indexes()) {
5322
-            $first_column = reset($this_model_fields_n_values);
5323
-            if (empty($first_column)) {
5324
-                return null;
5325
-            }
5326
-        }
5327
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328
-        if ($primary_key) {
5329
-            $classInstance = $this->get_from_entity_map($primary_key);
5330
-            if (! $classInstance) {
5331
-                $classInstance = EE_Registry::instance()
5332
-                                            ->load_class(
5333
-                                                $className,
5334
-                                                array($this_model_fields_n_values, $this->_timezone),
5335
-                                                true,
5336
-                                                false
5337
-                                            );
5338
-                // add this new object to the entity map
5339
-                $classInstance = $this->add_to_entity_map($classInstance);
5340
-            }
5341
-        } else {
5342
-            $classInstance = EE_Registry::instance()
5343
-                                        ->load_class(
5344
-                                            $className,
5345
-                                            array($this_model_fields_n_values, $this->_timezone),
5346
-                                            true,
5347
-                                            false
5348
-                                        );
5349
-        }
5350
-        return $classInstance;
5351
-    }
5352
-
5353
-
5354
-
5355
-    /**
5356
-     * Gets the model object from the  entity map if it exists
5357
-     *
5358
-     * @param int|string $id the ID of the model object
5359
-     * @return EE_Base_Class
5360
-     */
5361
-    public function get_from_entity_map($id)
5362
-    {
5363
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5365
-    }
5366
-
5367
-
5368
-
5369
-    /**
5370
-     * add_to_entity_map
5371
-     * Adds the object to the model's entity mappings
5372
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5373
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5374
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5375
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5376
-     *        then this method should be called immediately after the update query
5377
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5378
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5379
-     *
5380
-     * @param    EE_Base_Class $object
5381
-     * @throws EE_Error
5382
-     * @return \EE_Base_Class
5383
-     */
5384
-    public function add_to_entity_map(EE_Base_Class $object)
5385
-    {
5386
-        $className = $this->_get_class_name();
5387
-        if (! $object instanceof $className) {
5388
-            throw new EE_Error(sprintf(
5389
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390
-                is_object($object) ? get_class($object) : $object,
5391
-                $className
5392
-            ));
5393
-        }
5394
-        /** @var $object EE_Base_Class */
5395
-        if (! $object->ID()) {
5396
-            throw new EE_Error(sprintf(__(
5397
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5398
-                "event_espresso"
5399
-            ), get_class($this)));
5400
-        }
5401
-        // double check it's not already there
5402
-        $classInstance = $this->get_from_entity_map($object->ID());
5403
-        if ($classInstance) {
5404
-            return $classInstance;
5405
-        }
5406
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5407
-        return $object;
5408
-    }
5409
-
5410
-
5411
-
5412
-    /**
5413
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5414
-     * if no identifier is provided, then the entire entity map is emptied
5415
-     *
5416
-     * @param int|string $id the ID of the model object
5417
-     * @return boolean
5418
-     */
5419
-    public function clear_entity_map($id = null)
5420
-    {
5421
-        if (empty($id)) {
5422
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5423
-            return true;
5424
-        }
5425
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5427
-            return true;
5428
-        }
5429
-        return false;
5430
-    }
5431
-
5432
-
5433
-
5434
-    /**
5435
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5436
-     * Given an array where keys are column (or column alias) names and values,
5437
-     * returns an array of their corresponding field names and database values
5438
-     *
5439
-     * @param array $cols_n_values
5440
-     * @return array
5441
-     */
5442
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5443
-    {
5444
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5445
-    }
5446
-
5447
-
5448
-
5449
-    /**
5450
-     * _deduce_fields_n_values_from_cols_n_values
5451
-     * Given an array where keys are column (or column alias) names and values,
5452
-     * returns an array of their corresponding field names and database values
5453
-     *
5454
-     * @param string $cols_n_values
5455
-     * @return array
5456
-     */
5457
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
-    {
5459
-        $this_model_fields_n_values = array();
5460
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5461
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5462
-                $cols_n_values,
5463
-                $table_obj->get_fully_qualified_pk_column(),
5464
-                $table_obj->get_pk_column()
5465
-            );
5466
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5467
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
-                    if (! $field_obj->is_db_only_field()) {
5470
-                        // prepare field as if its coming from db
5471
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5473
-                    }
5474
-                }
5475
-            } else {
5476
-                // the table's rows existed. Use their values
5477
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
-                    if (! $field_obj->is_db_only_field()) {
5479
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5480
-                            $cols_n_values,
5481
-                            $field_obj->get_qualified_column(),
5482
-                            $field_obj->get_table_column()
5483
-                        );
5484
-                    }
5485
-                }
5486
-            }
5487
-        }
5488
-        return $this_model_fields_n_values;
5489
-    }
5490
-
5491
-
5492
-    /**
5493
-     * @param $cols_n_values
5494
-     * @param $qualified_column
5495
-     * @param $regular_column
5496
-     * @return null
5497
-     * @throws EE_Error
5498
-     * @throws ReflectionException
5499
-     */
5500
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5501
-    {
5502
-        $value = null;
5503
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504
-        // does the field on the model relate to this column retrieved from the db?
5505
-        // or is it a db-only field? (not relating to the model)
5506
-        if (isset($cols_n_values[ $qualified_column ])) {
5507
-            $value = $cols_n_values[ $qualified_column ];
5508
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5509
-            $value = $cols_n_values[ $regular_column ];
5510
-        } elseif (! empty($this->foreign_key_aliases)) {
5511
-            // no PK?  ok check if there is a foreign key alias set for this table
5512
-            // then check if that alias exists in the incoming data
5513
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
-                    $value = $cols_n_values[ $FK_alias ];
5517
-                    [$pk_class] = explode('.', $PK_column);
5518
-                    $pk_model_name = "EEM_{$pk_class}";
5519
-                    /** @var EEM_Base $pk_model */
5520
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5521
-                    if ($pk_model instanceof EEM_Base) {
5522
-                        // make sure object is pulled from db and added to entity map
5523
-                        $pk_model->get_one_by_ID($value);
5524
-                    }
5525
-                    break;
5526
-                }
5527
-            }
5528
-        }
5529
-        return $value;
5530
-    }
5531
-
5532
-
5533
-
5534
-    /**
5535
-     * refresh_entity_map_from_db
5536
-     * Makes sure the model object in the entity map at $id assumes the values
5537
-     * of the database (opposite of EE_base_Class::save())
5538
-     *
5539
-     * @param int|string $id
5540
-     * @return EE_Base_Class
5541
-     * @throws EE_Error
5542
-     */
5543
-    public function refresh_entity_map_from_db($id)
5544
-    {
5545
-        $obj_in_map = $this->get_from_entity_map($id);
5546
-        if ($obj_in_map) {
5547
-            $wpdb_results = $this->_get_all_wpdb_results(
5548
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5549
-            );
5550
-            if ($wpdb_results && is_array($wpdb_results)) {
5551
-                $one_row = reset($wpdb_results);
5552
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5553
-                    $obj_in_map->set_from_db($field_name, $db_value);
5554
-                }
5555
-                // clear the cache of related model objects
5556
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5557
-                    $obj_in_map->clear_cache($relation_name, null, true);
5558
-                }
5559
-            }
5560
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5561
-            return $obj_in_map;
5562
-        }
5563
-        return $this->get_one_by_ID($id);
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * refresh_entity_map_with
5570
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5571
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5572
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5573
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5574
-     *
5575
-     * @param int|string    $id
5576
-     * @param EE_Base_Class $replacing_model_obj
5577
-     * @return \EE_Base_Class
5578
-     * @throws EE_Error
5579
-     */
5580
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5581
-    {
5582
-        $obj_in_map = $this->get_from_entity_map($id);
5583
-        if ($obj_in_map) {
5584
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5585
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5586
-                    $obj_in_map->set($field_name, $value);
5587
-                }
5588
-                // make the model object in the entity map's cache match the $replacing_model_obj
5589
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5590
-                    $obj_in_map->clear_cache($relation_name, null, true);
5591
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5592
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5593
-                    }
5594
-                }
5595
-            }
5596
-            return $obj_in_map;
5597
-        }
5598
-        $this->add_to_entity_map($replacing_model_obj);
5599
-        return $replacing_model_obj;
5600
-    }
5601
-
5602
-
5603
-
5604
-    /**
5605
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5606
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5607
-     * require_once($this->_getClassName().".class.php");
5608
-     *
5609
-     * @return string
5610
-     */
5611
-    private function _get_class_name()
5612
-    {
5613
-        return "EE_" . $this->get_this_model_name();
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5620
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5621
-     * it would be 'Events'.
5622
-     *
5623
-     * @param int $quantity
5624
-     * @return string
5625
-     */
5626
-    public function item_name($quantity = 1)
5627
-    {
5628
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5629
-    }
5630
-
5631
-
5632
-
5633
-    /**
5634
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5635
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5636
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5637
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5638
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5639
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5640
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5641
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5642
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5643
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5644
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5645
-     *        return $previousReturnValue.$returnString;
5646
-     * }
5647
-     * require('EEM_Answer.model.php');
5648
-     * $answer=EEM_Answer::instance();
5649
-     * echo $answer->my_callback('monkeys',100);
5650
-     * //will output "you called my_callback! and passed args:monkeys,100"
5651
-     *
5652
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5653
-     * @param array  $args       array of original arguments passed to the function
5654
-     * @throws EE_Error
5655
-     * @return mixed whatever the plugin which calls add_filter decides
5656
-     */
5657
-    public function __call($methodName, $args)
5658
-    {
5659
-        $className = get_class($this);
5660
-        $tagName = "FHEE__{$className}__{$methodName}";
5661
-        if (! has_filter($tagName)) {
5662
-            throw new EE_Error(
5663
-                sprintf(
5664
-                    __(
5665
-                        '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 );',
5666
-                        'event_espresso'
5667
-                    ),
5668
-                    $methodName,
5669
-                    $className,
5670
-                    $tagName,
5671
-                    '<br />'
5672
-                )
5673
-            );
5674
-        }
5675
-        return apply_filters($tagName, null, $this, $args);
5676
-    }
5677
-
5678
-
5679
-
5680
-    /**
5681
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
-     *
5684
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5686
-     *                                                       the object's class name
5687
-     *                                                       or object's ID
5688
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
-     *                                                       exists in the database. If it does not, we add it
5690
-     * @throws EE_Error
5691
-     * @return EE_Base_Class
5692
-     */
5693
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5694
-    {
5695
-        $className = $this->_get_class_name();
5696
-        if ($base_class_obj_or_id instanceof $className) {
5697
-            $model_object = $base_class_obj_or_id;
5698
-        } else {
5699
-            $primary_key_field = $this->get_primary_key_field();
5700
-            if (
5701
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5702
-                && (
5703
-                    is_int($base_class_obj_or_id)
5704
-                    || is_string($base_class_obj_or_id)
5705
-                )
5706
-            ) {
5707
-                // assume it's an ID.
5708
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5709
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
-            } elseif (
5711
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5712
-                && is_string($base_class_obj_or_id)
5713
-            ) {
5714
-                // assume its a string representation of the object
5715
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5716
-            } else {
5717
-                throw new EE_Error(
5718
-                    sprintf(
5719
-                        __(
5720
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5721
-                            'event_espresso'
5722
-                        ),
5723
-                        $base_class_obj_or_id,
5724
-                        $this->_get_class_name(),
5725
-                        print_r($base_class_obj_or_id, true)
5726
-                    )
5727
-                );
5728
-            }
5729
-        }
5730
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5731
-            $model_object->save();
5732
-        }
5733
-        return $model_object;
5734
-    }
5735
-
5736
-
5737
-
5738
-    /**
5739
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
-     * returns it ID.
5742
-     *
5743
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
-     * @return int|string depending on the type of this model object's ID
5745
-     * @throws EE_Error
5746
-     */
5747
-    public function ensure_is_ID($base_class_obj_or_id)
5748
-    {
5749
-        $className = $this->_get_class_name();
5750
-        if ($base_class_obj_or_id instanceof $className) {
5751
-            /** @var $base_class_obj_or_id EE_Base_Class */
5752
-            $id = $base_class_obj_or_id->ID();
5753
-        } elseif (is_int($base_class_obj_or_id)) {
5754
-            // assume it's an ID
5755
-            $id = $base_class_obj_or_id;
5756
-        } elseif (is_string($base_class_obj_or_id)) {
5757
-            // assume its a string representation of the object
5758
-            $id = $base_class_obj_or_id;
5759
-        } else {
5760
-            throw new EE_Error(sprintf(
5761
-                __(
5762
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
-                    'event_espresso'
5764
-                ),
5765
-                $base_class_obj_or_id,
5766
-                $this->_get_class_name(),
5767
-                print_r($base_class_obj_or_id, true)
5768
-            ));
5769
-        }
5770
-        return $id;
5771
-    }
5772
-
5773
-
5774
-
5775
-    /**
5776
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
-     * been sanitized and converted into the appropriate domain.
5779
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
-     * $EVT = EEM_Event::instance(); $old_setting =
5784
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5786
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
-     *
5789
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5790
-     * @return void
5791
-     */
5792
-    public function assume_values_already_prepared_by_model_object(
5793
-        $values_already_prepared = self::not_prepared_by_model_object
5794
-    ) {
5795
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
-    }
5797
-
5798
-
5799
-
5800
-    /**
5801
-     * Read comments for assume_values_already_prepared_by_model_object()
5802
-     *
5803
-     * @return int
5804
-     */
5805
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
-    {
5807
-        return $this->_values_already_prepared_by_model_object;
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Gets all the indexes on this model
5814
-     *
5815
-     * @return EE_Index[]
5816
-     */
5817
-    public function indexes()
5818
-    {
5819
-        return $this->_indexes;
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * Gets all the Unique Indexes on this model
5826
-     *
5827
-     * @return EE_Unique_Index[]
5828
-     */
5829
-    public function unique_indexes()
5830
-    {
5831
-        $unique_indexes = array();
5832
-        foreach ($this->_indexes as $name => $index) {
5833
-            if ($index instanceof EE_Unique_Index) {
5834
-                $unique_indexes [ $name ] = $index;
5835
-            }
5836
-        }
5837
-        return $unique_indexes;
5838
-    }
5839
-
5840
-
5841
-
5842
-    /**
5843
-     * Gets all the fields which, when combined, make the primary key.
5844
-     * This is usually just an array with 1 element (the primary key), but in cases
5845
-     * where there is no primary key, it's a combination of fields as defined
5846
-     * on a primary index
5847
-     *
5848
-     * @return EE_Model_Field_Base[] indexed by the field's name
5849
-     * @throws EE_Error
5850
-     */
5851
-    public function get_combined_primary_key_fields()
5852
-    {
5853
-        foreach ($this->indexes() as $index) {
5854
-            if ($index instanceof EE_Primary_Key_Index) {
5855
-                return $index->fields();
5856
-            }
5857
-        }
5858
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5859
-    }
5860
-
5861
-
5862
-
5863
-    /**
5864
-     * Used to build a primary key string (when the model has no primary key),
5865
-     * which can be used a unique string to identify this model object.
5866
-     *
5867
-     * @param array $fields_n_values keys are field names, values are their values.
5868
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5869
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5870
-     *                               before passing it to this function (that will convert it from columns-n-values
5871
-     *                               to field-names-n-values).
5872
-     * @return string
5873
-     * @throws EE_Error
5874
-     */
5875
-    public function get_index_primary_key_string($fields_n_values)
5876
-    {
5877
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5878
-            $fields_n_values,
5879
-            $this->get_combined_primary_key_fields()
5880
-        );
5881
-        return http_build_query($cols_n_values_for_primary_key_index);
5882
-    }
5883
-
5884
-
5885
-
5886
-    /**
5887
-     * Gets the field values from the primary key string
5888
-     *
5889
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5890
-     * @param string $index_primary_key_string
5891
-     * @return null|array
5892
-     * @throws EE_Error
5893
-     */
5894
-    public function parse_index_primary_key_string($index_primary_key_string)
5895
-    {
5896
-        $key_fields = $this->get_combined_primary_key_fields();
5897
-        // check all of them are in the $id
5898
-        $key_vals_in_combined_pk = array();
5899
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900
-        foreach ($key_fields as $key_field_name => $field_obj) {
5901
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5902
-                return null;
5903
-            }
5904
-        }
5905
-        return $key_vals_in_combined_pk;
5906
-    }
5907
-
5908
-
5909
-
5910
-    /**
5911
-     * verifies that an array of key-value pairs for model fields has a key
5912
-     * for each field comprising the primary key index
5913
-     *
5914
-     * @param array $key_vals
5915
-     * @return boolean
5916
-     * @throws EE_Error
5917
-     */
5918
-    public function has_all_combined_primary_key_fields($key_vals)
5919
-    {
5920
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921
-        foreach ($keys_it_should_have as $key) {
5922
-            if (! isset($key_vals[ $key ])) {
5923
-                return false;
5924
-            }
5925
-        }
5926
-        return true;
5927
-    }
5928
-
5929
-
5930
-
5931
-    /**
5932
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5933
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5934
-     *
5935
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5936
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5937
-     * @throws EE_Error
5938
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5939
-     *                                                              indexed)
5940
-     */
5941
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5942
-    {
5943
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5944
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5945
-        } elseif (is_array($model_object_or_attributes_array)) {
5946
-            $attributes_array = $model_object_or_attributes_array;
5947
-        } else {
5948
-            throw new EE_Error(sprintf(__(
5949
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5950
-                "event_espresso"
5951
-            ), $model_object_or_attributes_array));
5952
-        }
5953
-        // even copies obviously won't have the same ID, so remove the primary key
5954
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5957
-        }
5958
-        if (isset($query_params[0])) {
5959
-            $query_params[0] = array_merge($attributes_array, $query_params);
5960
-        } else {
5961
-            $query_params[0] = $attributes_array;
5962
-        }
5963
-        return $this->get_all($query_params);
5964
-    }
5965
-
5966
-
5967
-
5968
-    /**
5969
-     * Gets the first copy we find. See get_all_copies for more details
5970
-     *
5971
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5972
-     * @param array $query_params
5973
-     * @return EE_Base_Class
5974
-     * @throws EE_Error
5975
-     */
5976
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977
-    {
5978
-        if (! is_array($query_params)) {
5979
-            EE_Error::doing_it_wrong(
5980
-                'EEM_Base::get_one_copy',
5981
-                sprintf(
5982
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
-                    gettype($query_params)
5984
-                ),
5985
-                '4.6.0'
5986
-            );
5987
-            $query_params = array();
5988
-        }
5989
-        $query_params['limit'] = 1;
5990
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
-        if (is_array($copies)) {
5992
-            return array_shift($copies);
5993
-        }
5994
-        return null;
5995
-    }
5996
-
5997
-
5998
-
5999
-    /**
6000
-     * Updates the item with the specified id. Ignores default query parameters because
6001
-     * we have specified the ID, and its assumed we KNOW what we're doing
6002
-     *
6003
-     * @param array      $fields_n_values keys are field names, values are their new values
6004
-     * @param int|string $id              the value of the primary key to update
6005
-     * @return int number of rows updated
6006
-     * @throws EE_Error
6007
-     */
6008
-    public function update_by_ID($fields_n_values, $id)
6009
-    {
6010
-        $query_params = array(
6011
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
6012
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
-        );
6014
-        return $this->update($fields_n_values, $query_params);
6015
-    }
6016
-
6017
-
6018
-
6019
-    /**
6020
-     * Changes an operator which was supplied to the models into one usable in SQL
6021
-     *
6022
-     * @param string $operator_supplied
6023
-     * @return string an operator which can be used in SQL
6024
-     * @throws EE_Error
6025
-     */
6026
-    private function _prepare_operator_for_sql($operator_supplied)
6027
-    {
6028
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
-            : null;
6030
-        if ($sql_operator) {
6031
-            return $sql_operator;
6032
-        }
6033
-        throw new EE_Error(
6034
-            sprintf(
6035
-                __(
6036
-                    "The operator '%s' is not in the list of valid operators: %s",
6037
-                    "event_espresso"
6038
-                ),
6039
-                $operator_supplied,
6040
-                implode(",", array_keys($this->_valid_operators))
6041
-            )
6042
-        );
6043
-    }
6044
-
6045
-
6046
-
6047
-    /**
6048
-     * Gets the valid operators
6049
-     * @return array keys are accepted strings, values are the SQL they are converted to
6050
-     */
6051
-    public function valid_operators()
6052
-    {
6053
-        return $this->_valid_operators;
6054
-    }
6055
-
6056
-
6057
-
6058
-    /**
6059
-     * Gets the between-style operators (take 2 arguments).
6060
-     * @return array keys are accepted strings, values are the SQL they are converted to
6061
-     */
6062
-    public function valid_between_style_operators()
6063
-    {
6064
-        return array_intersect(
6065
-            $this->valid_operators(),
6066
-            $this->_between_style_operators
6067
-        );
6068
-    }
6069
-
6070
-    /**
6071
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
-     * @return array keys are accepted strings, values are the SQL they are converted to
6073
-     */
6074
-    public function valid_like_style_operators()
6075
-    {
6076
-        return array_intersect(
6077
-            $this->valid_operators(),
6078
-            $this->_like_style_operators
6079
-        );
6080
-    }
6081
-
6082
-    /**
6083
-     * Gets the "in"-style operators
6084
-     * @return array keys are accepted strings, values are the SQL they are converted to
6085
-     */
6086
-    public function valid_in_style_operators()
6087
-    {
6088
-        return array_intersect(
6089
-            $this->valid_operators(),
6090
-            $this->_in_style_operators
6091
-        );
6092
-    }
6093
-
6094
-    /**
6095
-     * Gets the "null"-style operators (accept no arguments)
6096
-     * @return array keys are accepted strings, values are the SQL they are converted to
6097
-     */
6098
-    public function valid_null_style_operators()
6099
-    {
6100
-        return array_intersect(
6101
-            $this->valid_operators(),
6102
-            $this->_null_style_operators
6103
-        );
6104
-    }
6105
-
6106
-    /**
6107
-     * Gets an array where keys are the primary keys and values are their 'names'
6108
-     * (as determined by the model object's name() function, which is often overridden)
6109
-     *
6110
-     * @param array $query_params like get_all's
6111
-     * @return string[]
6112
-     * @throws EE_Error
6113
-     */
6114
-    public function get_all_names($query_params = array())
6115
-    {
6116
-        $objs = $this->get_all($query_params);
6117
-        $names = array();
6118
-        foreach ($objs as $obj) {
6119
-            $names[ $obj->ID() ] = $obj->name();
6120
-        }
6121
-        return $names;
6122
-    }
6123
-
6124
-
6125
-
6126
-    /**
6127
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6128
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6129
-     * this is duplicated effort and reduces efficiency) you would be better to use
6130
-     * array_keys() on $model_objects.
6131
-     *
6132
-     * @param \EE_Base_Class[] $model_objects
6133
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6134
-     *                                               in the returned array
6135
-     * @return array
6136
-     * @throws EE_Error
6137
-     */
6138
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139
-    {
6140
-        if (! $this->has_primary_key_field()) {
6141
-            if (WP_DEBUG) {
6142
-                EE_Error::add_error(
6143
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6144
-                    __FILE__,
6145
-                    __FUNCTION__,
6146
-                    __LINE__
6147
-                );
6148
-            }
6149
-        }
6150
-        $IDs = array();
6151
-        foreach ($model_objects as $model_object) {
6152
-            $id = $model_object->ID();
6153
-            if (! $id) {
6154
-                if ($filter_out_empty_ids) {
6155
-                    continue;
6156
-                }
6157
-                if (WP_DEBUG) {
6158
-                    EE_Error::add_error(
6159
-                        __(
6160
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6161
-                            'event_espresso'
6162
-                        ),
6163
-                        __FILE__,
6164
-                        __FUNCTION__,
6165
-                        __LINE__
6166
-                    );
6167
-                }
6168
-            }
6169
-            $IDs[] = $id;
6170
-        }
6171
-        return $IDs;
6172
-    }
6173
-
6174
-
6175
-
6176
-    /**
6177
-     * Returns the string used in capabilities relating to this model. If there
6178
-     * are no capabilities that relate to this model returns false
6179
-     *
6180
-     * @return string|false
6181
-     */
6182
-    public function cap_slug()
6183
-    {
6184
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6185
-    }
6186
-
6187
-
6188
-
6189
-    /**
6190
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6191
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6192
-     * only returns the cap restrictions array in that context (ie, the array
6193
-     * at that key)
6194
-     *
6195
-     * @param string $context
6196
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
-     * @throws EE_Error
6198
-     */
6199
-    public function cap_restrictions($context = EEM_Base::caps_read)
6200
-    {
6201
-        EEM_Base::verify_is_valid_cap_context($context);
6202
-        // check if we ought to run the restriction generator first
6203
-        if (
6204
-            isset($this->_cap_restriction_generators[ $context ])
6205
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6207
-        ) {
6208
-            $this->_cap_restrictions[ $context ] = array_merge(
6209
-                $this->_cap_restrictions[ $context ],
6210
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6211
-            );
6212
-        }
6213
-        // and make sure we've finalized the construction of each restriction
6214
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6215
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216
-                $where_conditions_obj->_finalize_construct($this);
6217
-            }
6218
-        }
6219
-        return $this->_cap_restrictions[ $context ];
6220
-    }
6221
-
6222
-
6223
-
6224
-    /**
6225
-     * Indicating whether or not this model thinks its a wp core model
6226
-     *
6227
-     * @return boolean
6228
-     */
6229
-    public function is_wp_core_model()
6230
-    {
6231
-        return $this->_wp_core_model;
6232
-    }
6233
-
6234
-
6235
-
6236
-    /**
6237
-     * Gets all the caps that are missing which impose a restriction on
6238
-     * queries made in this context
6239
-     *
6240
-     * @param string $context one of EEM_Base::caps_ constants
6241
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6242
-     * @throws EE_Error
6243
-     */
6244
-    public function caps_missing($context = EEM_Base::caps_read)
6245
-    {
6246
-        $missing_caps = array();
6247
-        $cap_restrictions = $this->cap_restrictions($context);
6248
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249
-            if (
6250
-                ! EE_Capabilities::instance()
6251
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6252
-            ) {
6253
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6254
-            }
6255
-        }
6256
-        return $missing_caps;
6257
-    }
6258
-
6259
-
6260
-
6261
-    /**
6262
-     * Gets the mapping from capability contexts to action strings used in capability names
6263
-     *
6264
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6265
-     * one of 'read', 'edit', or 'delete'
6266
-     */
6267
-    public function cap_contexts_to_cap_action_map()
6268
-    {
6269
-        return apply_filters(
6270
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6271
-            $this->_cap_contexts_to_cap_action_map,
6272
-            $this
6273
-        );
6274
-    }
6275
-
6276
-
6277
-
6278
-    /**
6279
-     * Gets the action string for the specified capability context
6280
-     *
6281
-     * @param string $context
6282
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6283
-     * @throws EE_Error
6284
-     */
6285
-    public function cap_action_for_context($context)
6286
-    {
6287
-        $mapping = $this->cap_contexts_to_cap_action_map();
6288
-        if (isset($mapping[ $context ])) {
6289
-            return $mapping[ $context ];
6290
-        }
6291
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292
-            return $action;
6293
-        }
6294
-        throw new EE_Error(
6295
-            sprintf(
6296
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6297
-                $context,
6298
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6299
-            )
6300
-        );
6301
-    }
6302
-
6303
-
6304
-
6305
-    /**
6306
-     * Returns all the capability contexts which are valid when querying models
6307
-     *
6308
-     * @return array
6309
-     */
6310
-    public static function valid_cap_contexts()
6311
-    {
6312
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6313
-            self::caps_read,
6314
-            self::caps_read_admin,
6315
-            self::caps_edit,
6316
-            self::caps_delete,
6317
-        ));
6318
-    }
6319
-
6320
-
6321
-
6322
-    /**
6323
-     * Returns all valid options for 'default_where_conditions'
6324
-     *
6325
-     * @return array
6326
-     */
6327
-    public static function valid_default_where_conditions()
6328
-    {
6329
-        return array(
6330
-            EEM_Base::default_where_conditions_all,
6331
-            EEM_Base::default_where_conditions_this_only,
6332
-            EEM_Base::default_where_conditions_others_only,
6333
-            EEM_Base::default_where_conditions_minimum_all,
6334
-            EEM_Base::default_where_conditions_minimum_others,
6335
-            EEM_Base::default_where_conditions_none
6336
-        );
6337
-    }
6338
-
6339
-    // public static function default_where_conditions_full
6340
-    /**
6341
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
-     *
6343
-     * @param string $context
6344
-     * @return bool
6345
-     * @throws EE_Error
6346
-     */
6347
-    public static function verify_is_valid_cap_context($context)
6348
-    {
6349
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
-        if (in_array($context, $valid_cap_contexts)) {
6351
-            return true;
6352
-        }
6353
-        throw new EE_Error(
6354
-            sprintf(
6355
-                __(
6356
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
-                    'event_espresso'
6358
-                ),
6359
-                $context,
6360
-                'EEM_Base',
6361
-                implode(',', $valid_cap_contexts)
6362
-            )
6363
-        );
6364
-    }
6365
-
6366
-
6367
-
6368
-    /**
6369
-     * Clears all the models field caches. This is only useful when a sub-class
6370
-     * might have added a field or something and these caches might be invalidated
6371
-     */
6372
-    protected function _invalidate_field_caches()
6373
-    {
6374
-        $this->_cache_foreign_key_to_fields = array();
6375
-        $this->_cached_fields = null;
6376
-        $this->_cached_fields_non_db_only = null;
6377
-    }
6378
-
6379
-
6380
-
6381
-    /**
6382
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6383
-     * (eg "and", "or", "not").
6384
-     *
6385
-     * @return array
6386
-     */
6387
-    public function logic_query_param_keys()
6388
-    {
6389
-        return $this->_logic_query_param_keys;
6390
-    }
6391
-
6392
-
6393
-
6394
-    /**
6395
-     * Determines whether or not the where query param array key is for a logic query param.
6396
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6397
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6398
-     *
6399
-     * @param $query_param_key
6400
-     * @return bool
6401
-     */
6402
-    public function is_logic_query_param_key($query_param_key)
6403
-    {
6404
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405
-            if (
6406
-                $query_param_key === $logic_query_param_key
6407
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6408
-            ) {
6409
-                return true;
6410
-            }
6411
-        }
6412
-        return false;
6413
-    }
6414
-
6415
-    /**
6416
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6417
-     * @since 4.9.74.p
6418
-     * @return boolean
6419
-     */
6420
-    public function hasPassword()
6421
-    {
6422
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6423
-        if ($this->has_password_field === null) {
6424
-            $password_field = $this->getPasswordField();
6425
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6426
-        }
6427
-        return $this->has_password_field;
6428
-    }
6429
-
6430
-    /**
6431
-     * Returns the password field on this model, if there is one
6432
-     * @since 4.9.74.p
6433
-     * @return EE_Password_Field|null
6434
-     */
6435
-    public function getPasswordField()
6436
-    {
6437
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6438
-        // there's no need to search for it. If we don't know yet, then find out
6439
-        if ($this->has_password_field === null && $this->password_field === null) {
6440
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6441
-        }
6442
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6443
-        return $this->password_field;
6444
-    }
6445
-
6446
-
6447
-    /**
6448
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6449
-     * @since 4.9.74.p
6450
-     * @return EE_Model_Field_Base[]
6451
-     * @throws EE_Error
6452
-     */
6453
-    public function getPasswordProtectedFields()
6454
-    {
6455
-        $password_field = $this->getPasswordField();
6456
-        $fields = array();
6457
-        if ($password_field instanceof EE_Password_Field) {
6458
-            $field_names = $password_field->protectedFields();
6459
-            foreach ($field_names as $field_name) {
6460
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6461
-            }
6462
-        }
6463
-        return $fields;
6464
-    }
6465
-
6466
-
6467
-    /**
6468
-     * Checks if the current user can perform the requested action on this model
6469
-     * @since 4.9.74.p
6470
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6471
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6472
-     * @return bool
6473
-     * @throws EE_Error
6474
-     * @throws InvalidArgumentException
6475
-     * @throws InvalidDataTypeException
6476
-     * @throws InvalidInterfaceException
6477
-     * @throws ReflectionException
6478
-     * @throws UnexpectedEntityException
6479
-     */
6480
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6481
-    {
6482
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484
-        }
6485
-        if (!is_array($model_obj_or_fields_n_values)) {
6486
-            throw new UnexpectedEntityException(
6487
-                $model_obj_or_fields_n_values,
6488
-                'EE_Base_Class',
6489
-                sprintf(
6490
-                    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'),
6491
-                    __FUNCTION__
6492
-                )
6493
-            );
6494
-        }
6495
-        return $this->exists(
6496
-            $this->alter_query_params_to_restrict_by_ID(
6497
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6498
-                array(
6499
-                    'default_where_conditions' => 'none',
6500
-                    'caps'                     => $cap_to_check,
6501
-                )
6502
-            )
6503
-        );
6504
-    }
6505
-
6506
-    /**
6507
-     * Returns the query param where conditions key to the password affecting this model.
6508
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6509
-     * @since 4.9.74.p
6510
-     * @return null|string
6511
-     * @throws EE_Error
6512
-     * @throws InvalidArgumentException
6513
-     * @throws InvalidDataTypeException
6514
-     * @throws InvalidInterfaceException
6515
-     * @throws ModelConfigurationException
6516
-     * @throws ReflectionException
6517
-     */
6518
-    public function modelChainAndPassword()
6519
-    {
6520
-        if ($this->model_chain_to_password === null) {
6521
-            throw new ModelConfigurationException(
6522
-                $this,
6523
-                esc_html_x(
6524
-                // @codingStandardsIgnoreStart
6525
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6526
-                    // @codingStandardsIgnoreEnd
6527
-                    '1: model name',
6528
-                    'event_espresso'
6529
-                )
6530
-            );
6531
-        }
6532
-        if ($this->model_chain_to_password === '') {
6533
-            $model_with_password = $this;
6534
-        } else {
6535
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6536
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6537
-            } else {
6538
-                $last_model_in_chain = $this->model_chain_to_password;
6539
-            }
6540
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6541
-        }
6542
-
6543
-        $password_field = $model_with_password->getPasswordField();
6544
-        if ($password_field instanceof EE_Password_Field) {
6545
-            $password_field_name = $password_field->get_name();
6546
-        } else {
6547
-            throw new ModelConfigurationException(
6548
-                $this,
6549
-                sprintf(
6550
-                    esc_html_x(
6551
-                        '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"',
6552
-                        '1: model name, 2: special string',
6553
-                        'event_espresso'
6554
-                    ),
6555
-                    $model_with_password->get_this_model_name(),
6556
-                    $this->model_chain_to_password
6557
-                )
6558
-            );
6559
-        }
6560
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6561
-    }
6562
-
6563
-    /**
6564
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6565
-     * or if this model itself has a password affecting access to some of its other fields.
6566
-     * @since 4.9.74.p
6567
-     * @return boolean
6568
-     */
6569
-    public function restrictedByRelatedModelPassword()
6570
-    {
6571
-        return $this->model_chain_to_password !== null;
6572
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3875
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3876
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3878
+	 *
3879
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3881
+	 */
3882
+	private function _get_default_where_conditions($model_relation_path = '')
3883
+	{
3884
+		if ($this->_ignore_where_strategy) {
3885
+			return array();
3886
+		}
3887
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
+	}
3889
+
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3901
+	 */
3902
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3903
+	{
3904
+		if ($this->_ignore_where_strategy) {
3905
+			return array();
3906
+		}
3907
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
+	}
3909
+
3910
+
3911
+
3912
+	/**
3913
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
+	 *
3916
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3917
+	 * @return string
3918
+	 * @throws EE_Error
3919
+	 */
3920
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
+	{
3922
+		$selects = $this->_get_columns_to_select_for_this_model();
3923
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3924
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
+			foreach ($other_model_selects as $key => $value) {
3927
+				$selects[] = $value;
3928
+			}
3929
+		}
3930
+		return implode(", ", $selects);
3931
+	}
3932
+
3933
+
3934
+
3935
+	/**
3936
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3937
+	 * So that's going to be the columns for all the fields on the model
3938
+	 *
3939
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3940
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3941
+	 */
3942
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3943
+	{
3944
+		$fields = $this->field_settings();
3945
+		$selects = array();
3946
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
+			$model_relation_chain,
3948
+			$this->get_this_model_name()
3949
+		);
3950
+		foreach ($fields as $field_obj) {
3951
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3952
+						 . $field_obj->get_table_alias()
3953
+						 . "."
3954
+						 . $field_obj->get_table_column()
3955
+						 . " AS '"
3956
+						 . $table_alias_with_model_relation_chain_prefix
3957
+						 . $field_obj->get_table_alias()
3958
+						 . "."
3959
+						 . $field_obj->get_table_column()
3960
+						 . "'";
3961
+		}
3962
+		// make sure we are also getting the PKs of each table
3963
+		$tables = $this->get_tables();
3964
+		if (count($tables) > 1) {
3965
+			foreach ($tables as $table_obj) {
3966
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
+									   . $table_obj->get_fully_qualified_pk_column();
3968
+				if (! in_array($qualified_pk_column, $selects)) {
3969
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
+				}
3971
+			}
3972
+		}
3973
+		return $selects;
3974
+	}
3975
+
3976
+
3977
+
3978
+	/**
3979
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3980
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3981
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3982
+	 * SQL for joining, and the data types
3983
+	 *
3984
+	 * @param null|string                 $original_query_param
3985
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3986
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3987
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3988
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3989
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3990
+	 *                                                          or 'Registration's
3991
+	 * @param string                      $original_query_param what it originally was (eg
3992
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3993
+	 *                                                          matches $query_param
3994
+	 * @throws EE_Error
3995
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
+	 */
3997
+	private function _extract_related_model_info_from_query_param(
3998
+		$query_param,
3999
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4000
+		$query_param_type,
4001
+		$original_query_param = null
4002
+	) {
4003
+		if ($original_query_param === null) {
4004
+			$original_query_param = $query_param;
4005
+		}
4006
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4007
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4008
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4009
+		$allow_fields = in_array(
4010
+			$query_param_type,
4011
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4012
+			true
4013
+		);
4014
+		// check to see if we have a field on this model
4015
+		$this_model_fields = $this->field_settings(true);
4016
+		if (array_key_exists($query_param, $this_model_fields)) {
4017
+			if ($allow_fields) {
4018
+				return;
4019
+			}
4020
+			throw new EE_Error(
4021
+				sprintf(
4022
+					__(
4023
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
+						"event_espresso"
4025
+					),
4026
+					$query_param,
4027
+					get_class($this),
4028
+					$query_param_type,
4029
+					$original_query_param
4030
+				)
4031
+			);
4032
+		}
4033
+		// check if this is a special logic query param
4034
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
+			if ($allow_logic_query_params) {
4036
+				return;
4037
+			}
4038
+			throw new EE_Error(
4039
+				sprintf(
4040
+					__(
4041
+						'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',
4042
+						'event_espresso'
4043
+					),
4044
+					implode('", "', $this->_logic_query_param_keys),
4045
+					$query_param,
4046
+					get_class($this),
4047
+					'<br />',
4048
+					"\t"
4049
+					. ' $passed_in_query_info = <pre>'
4050
+					. print_r($passed_in_query_info, true)
4051
+					. '</pre>'
4052
+					. "\n\t"
4053
+					. ' $query_param_type = '
4054
+					. $query_param_type
4055
+					. "\n\t"
4056
+					. ' $original_query_param = '
4057
+					. $original_query_param
4058
+				)
4059
+			);
4060
+		}
4061
+		// check if it's a custom selection
4062
+		if (
4063
+			$this->_custom_selections instanceof CustomSelects
4064
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
+		) {
4066
+			return;
4067
+		}
4068
+		// check if has a model name at the beginning
4069
+		// and
4070
+		// check if it's a field on a related model
4071
+		if (
4072
+			$this->extractJoinModelFromQueryParams(
4073
+				$passed_in_query_info,
4074
+				$query_param,
4075
+				$original_query_param,
4076
+				$query_param_type
4077
+			)
4078
+		) {
4079
+			return;
4080
+		}
4081
+
4082
+		// ok so $query_param didn't start with a model name
4083
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4084
+		// it's wack, that's what it is
4085
+		throw new EE_Error(
4086
+			sprintf(
4087
+				esc_html__(
4088
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4089
+					"event_espresso"
4090
+				),
4091
+				$query_param,
4092
+				get_class($this),
4093
+				$query_param_type,
4094
+				$original_query_param
4095
+			)
4096
+		);
4097
+	}
4098
+
4099
+
4100
+	/**
4101
+	 * Extracts any possible join model information from the provided possible_join_string.
4102
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4103
+	 * parts that should be added to the query.
4104
+	 *
4105
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4106
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4107
+	 * @param null|string                 $original_query_param
4108
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4109
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4110
+	 * @return bool  returns true if a join was added and false if not.
4111
+	 * @throws EE_Error
4112
+	 */
4113
+	private function extractJoinModelFromQueryParams(
4114
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4115
+		$possible_join_string,
4116
+		$original_query_param,
4117
+		$query_parameter_type
4118
+	) {
4119
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
+				if ($possible_join_string === '') {
4124
+					// nothing left to $query_param
4125
+					// we should actually end in a field name, not a model like this!
4126
+					throw new EE_Error(
4127
+						sprintf(
4128
+							esc_html__(
4129
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
+								"event_espresso"
4131
+							),
4132
+							$possible_join_string,
4133
+							$query_parameter_type,
4134
+							get_class($this),
4135
+							$valid_related_model_name
4136
+						)
4137
+					);
4138
+				}
4139
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
+				$related_model_obj->_extract_related_model_info_from_query_param(
4141
+					$possible_join_string,
4142
+					$query_info_carrier,
4143
+					$query_parameter_type,
4144
+					$original_query_param
4145
+				);
4146
+				return true;
4147
+			}
4148
+			if ($possible_join_string === $valid_related_model_name) {
4149
+				$this->_add_join_to_model(
4150
+					$valid_related_model_name,
4151
+					$query_info_carrier,
4152
+					$original_query_param
4153
+				);
4154
+				return true;
4155
+			}
4156
+		}
4157
+		return false;
4158
+	}
4159
+
4160
+
4161
+	/**
4162
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4164
+	 * @throws EE_Error
4165
+	 */
4166
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4167
+	{
4168
+		if (
4169
+			$this->_custom_selections instanceof CustomSelects
4170
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4171
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4172
+			)
4173
+		) {
4174
+			$original_selects = $this->_custom_selections->originalSelects();
4175
+			foreach ($original_selects as $alias => $select_configuration) {
4176
+				$this->extractJoinModelFromQueryParams(
4177
+					$query_info_carrier,
4178
+					$select_configuration[0],
4179
+					$select_configuration[0],
4180
+					'custom_selects'
4181
+				);
4182
+			}
4183
+		}
4184
+	}
4185
+
4186
+
4187
+
4188
+	/**
4189
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
+	 * and store it on $passed_in_query_info
4191
+	 *
4192
+	 * @param string                      $model_name
4193
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4195
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4196
+	 *                                                          and are adding a join to 'Payment' with the original
4197
+	 *                                                          query param key
4198
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4200
+	 *                                                          Payment wants to add default query params so that it
4201
+	 *                                                          will know what models to prepend onto its default query
4202
+	 *                                                          params or in case it wants to rename tables (in case
4203
+	 *                                                          there are multiple joins to the same table)
4204
+	 * @return void
4205
+	 * @throws EE_Error
4206
+	 */
4207
+	private function _add_join_to_model(
4208
+		$model_name,
4209
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
+		$original_query_param
4211
+	) {
4212
+		$relation_obj = $this->related_settings_for($model_name);
4213
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
+		// check if the relation is HABTM, because then we're essentially doing two joins
4215
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4217
+			$join_model_obj = $relation_obj->get_join_model();
4218
+			// replace the model specified with the join model for this relation chain, whi
4219
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4220
+				$model_name,
4221
+				$join_model_obj->get_this_model_name(),
4222
+				$model_relation_chain
4223
+			);
4224
+			$passed_in_query_info->merge(
4225
+				new EE_Model_Query_Info_Carrier(
4226
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4227
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4228
+				)
4229
+			);
4230
+		}
4231
+		// now just join to the other table pointed to by the relation object, and add its data types
4232
+		$passed_in_query_info->merge(
4233
+			new EE_Model_Query_Info_Carrier(
4234
+				array($model_relation_chain => $model_name),
4235
+				$relation_obj->get_join_statement($model_relation_chain)
4236
+			)
4237
+		);
4238
+	}
4239
+
4240
+
4241
+
4242
+	/**
4243
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
+	 *
4245
+	 * @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
4246
+	 * @return string of SQL
4247
+	 * @throws EE_Error
4248
+	 */
4249
+	private function _construct_where_clause($where_params)
4250
+	{
4251
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252
+		if ($SQL) {
4253
+			return " WHERE " . $SQL;
4254
+		}
4255
+		return '';
4256
+	}
4257
+
4258
+
4259
+
4260
+	/**
4261
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
+	 * and should be passed HAVING parameters, not WHERE parameters
4263
+	 *
4264
+	 * @param array $having_params
4265
+	 * @return string
4266
+	 * @throws EE_Error
4267
+	 */
4268
+	private function _construct_having_clause($having_params)
4269
+	{
4270
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
+		if ($SQL) {
4272
+			return " HAVING " . $SQL;
4273
+		}
4274
+		return '';
4275
+	}
4276
+
4277
+
4278
+	/**
4279
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
+	 * Event_Meta.meta_value = 'foo'))"
4281
+	 *
4282
+	 * @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
4283
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4284
+	 * @throws EE_Error
4285
+	 * @return string of SQL
4286
+	 */
4287
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4288
+	{
4289
+		$where_clauses = array();
4290
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4292
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4293
+				switch ($query_param) {
4294
+					case 'not':
4295
+					case 'NOT':
4296
+						$where_clauses[] = "! ("
4297
+										   . $this->_construct_condition_clause_recursive(
4298
+											   $op_and_value_or_sub_condition,
4299
+											   $glue
4300
+										   )
4301
+										   . ")";
4302
+						break;
4303
+					case 'and':
4304
+					case 'AND':
4305
+						$where_clauses[] = " ("
4306
+										   . $this->_construct_condition_clause_recursive(
4307
+											   $op_and_value_or_sub_condition,
4308
+											   ' AND '
4309
+										   )
4310
+										   . ")";
4311
+						break;
4312
+					case 'or':
4313
+					case 'OR':
4314
+						$where_clauses[] = " ("
4315
+										   . $this->_construct_condition_clause_recursive(
4316
+											   $op_and_value_or_sub_condition,
4317
+											   ' OR '
4318
+										   )
4319
+										   . ")";
4320
+						break;
4321
+				}
4322
+			} else {
4323
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4324
+				// if it's not a normal field, maybe it's a custom selection?
4325
+				if (! $field_obj) {
4326
+					if ($this->_custom_selections instanceof CustomSelects) {
4327
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328
+					} else {
4329
+						throw new EE_Error(sprintf(__(
4330
+							"%s is neither a valid model field name, nor a custom selection",
4331
+							"event_espresso"
4332
+						), $query_param));
4333
+					}
4334
+				}
4335
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4337
+			}
4338
+		}
4339
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4340
+	}
4341
+
4342
+
4343
+
4344
+	/**
4345
+	 * Takes the input parameter and extract the table name (alias) and column name
4346
+	 *
4347
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4348
+	 * @throws EE_Error
4349
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4350
+	 */
4351
+	private function _deduce_column_name_from_query_param($query_param)
4352
+	{
4353
+		$field = $this->_deduce_field_from_query_param($query_param);
4354
+		if ($field) {
4355
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4356
+				$field->get_model_name(),
4357
+				$query_param
4358
+			);
4359
+			return $table_alias_prefix . $field->get_qualified_column();
4360
+		}
4361
+		if (
4362
+			$this->_custom_selections instanceof CustomSelects
4363
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4364
+		) {
4365
+			// maybe it's custom selection item?
4366
+			// if so, just use it as the "column name"
4367
+			return $query_param;
4368
+		}
4369
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4370
+			? implode(',', $this->_custom_selections->columnAliases())
4371
+			: '';
4372
+		throw new EE_Error(
4373
+			sprintf(
4374
+				__(
4375
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4376
+					"event_espresso"
4377
+				),
4378
+				$query_param,
4379
+				$custom_select_aliases
4380
+			)
4381
+		);
4382
+	}
4383
+
4384
+
4385
+
4386
+	/**
4387
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4388
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4389
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4390
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4391
+	 *
4392
+	 * @param string $condition_query_param_key
4393
+	 * @return string
4394
+	 */
4395
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4396
+	{
4397
+		$pos_of_star = strpos($condition_query_param_key, '*');
4398
+		if ($pos_of_star === false) {
4399
+			return $condition_query_param_key;
4400
+		}
4401
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4402
+		return $condition_query_param_sans_star;
4403
+	}
4404
+
4405
+
4406
+
4407
+	/**
4408
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4409
+	 *
4410
+	 * @param                            mixed      array | string    $op_and_value
4411
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4412
+	 * @throws EE_Error
4413
+	 * @return string
4414
+	 */
4415
+	private function _construct_op_and_value($op_and_value, $field_obj)
4416
+	{
4417
+		if (is_array($op_and_value)) {
4418
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
+			if (! $operator) {
4420
+				$php_array_like_string = array();
4421
+				foreach ($op_and_value as $key => $value) {
4422
+					$php_array_like_string[] = "$key=>$value";
4423
+				}
4424
+				throw new EE_Error(
4425
+					sprintf(
4426
+						__(
4427
+							"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))",
4428
+							"event_espresso"
4429
+						),
4430
+						implode(",", $php_array_like_string)
4431
+					)
4432
+				);
4433
+			}
4434
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4435
+		} else {
4436
+			$operator = '=';
4437
+			$value = $op_and_value;
4438
+		}
4439
+		// check to see if the value is actually another field
4440
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4442
+		}
4443
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444
+			// in this case, the value should be an array, or at least a comma-separated list
4445
+			// it will need to handle a little differently
4446
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4447
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4448
+			return $operator . SP . $cleaned_value;
4449
+		}
4450
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451
+			// the value should be an array with count of two.
4452
+			if (count($value) !== 2) {
4453
+				throw new EE_Error(
4454
+					sprintf(
4455
+						__(
4456
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4457
+							'event_espresso'
4458
+						),
4459
+						"BETWEEN"
4460
+					)
4461
+				);
4462
+			}
4463
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
+			return $operator . SP . $cleaned_value;
4465
+		}
4466
+		if (in_array($operator, $this->valid_null_style_operators())) {
4467
+			if ($value !== null) {
4468
+				throw new EE_Error(
4469
+					sprintf(
4470
+						__(
4471
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4472
+							"event_espresso"
4473
+						),
4474
+						$value,
4475
+						$operator
4476
+					)
4477
+				);
4478
+			}
4479
+			return $operator;
4480
+		}
4481
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4483
+			// remove other junk. So just treat it as a string.
4484
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4485
+		}
4486
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4488
+		}
4489
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490
+			throw new EE_Error(
4491
+				sprintf(
4492
+					__(
4493
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4494
+						'event_espresso'
4495
+					),
4496
+					$operator,
4497
+					$operator
4498
+				)
4499
+			);
4500
+		}
4501
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502
+			throw new EE_Error(
4503
+				sprintf(
4504
+					__(
4505
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4506
+						'event_espresso'
4507
+					),
4508
+					$operator,
4509
+					$operator
4510
+				)
4511
+			);
4512
+		}
4513
+		throw new EE_Error(
4514
+			sprintf(
4515
+				__(
4516
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4517
+					"event_espresso"
4518
+				),
4519
+				http_build_query($op_and_value)
4520
+			)
4521
+		);
4522
+	}
4523
+
4524
+
4525
+
4526
+	/**
4527
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4528
+	 *
4529
+	 * @param array                      $values
4530
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4531
+	 *                                              '%s'
4532
+	 * @return string
4533
+	 * @throws EE_Error
4534
+	 */
4535
+	public function _construct_between_value($values, $field_obj)
4536
+	{
4537
+		$cleaned_values = array();
4538
+		foreach ($values as $value) {
4539
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540
+		}
4541
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4542
+	}
4543
+
4544
+
4545
+
4546
+	/**
4547
+	 * Takes an array or a comma-separated list of $values and cleans them
4548
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4549
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4550
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4551
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4552
+	 *
4553
+	 * @param mixed                      $values    array or comma-separated string
4554
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4555
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4556
+	 * @throws EE_Error
4557
+	 */
4558
+	public function _construct_in_value($values, $field_obj)
4559
+	{
4560
+		// check if the value is a CSV list
4561
+		if (is_string($values)) {
4562
+			// in which case, turn it into an array
4563
+			$values = explode(",", $values);
4564
+		}
4565
+		$cleaned_values = array();
4566
+		foreach ($values as $value) {
4567
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4568
+		}
4569
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4570
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4571
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4572
+		if (empty($cleaned_values)) {
4573
+			$all_fields = $this->field_settings();
4574
+			$a_field = array_shift($all_fields);
4575
+			$main_table = $this->_get_main_table();
4576
+			$cleaned_values[] = "SELECT "
4577
+								. $a_field->get_table_column()
4578
+								. " FROM "
4579
+								. $main_table->get_table_name()
4580
+								. " WHERE FALSE";
4581
+		}
4582
+		return "(" . implode(",", $cleaned_values) . ")";
4583
+	}
4584
+
4585
+
4586
+
4587
+	/**
4588
+	 * @param mixed                      $value
4589
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4590
+	 * @throws EE_Error
4591
+	 * @return false|null|string
4592
+	 */
4593
+	private function _wpdb_prepare_using_field($value, $field_obj)
4594
+	{
4595
+		/** @type WPDB $wpdb */
4596
+		global $wpdb;
4597
+		if ($field_obj instanceof EE_Model_Field_Base) {
4598
+			return $wpdb->prepare(
4599
+				$field_obj->get_wpdb_data_type(),
4600
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4601
+			);
4602
+		} //$field_obj should really just be a data type
4603
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604
+			throw new EE_Error(
4605
+				sprintf(
4606
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4607
+					$field_obj,
4608
+					implode(",", $this->_valid_wpdb_data_types)
4609
+				)
4610
+			);
4611
+		}
4612
+		return $wpdb->prepare($field_obj, $value);
4613
+	}
4614
+
4615
+
4616
+
4617
+	/**
4618
+	 * Takes the input parameter and finds the model field that it indicates.
4619
+	 *
4620
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4621
+	 * @throws EE_Error
4622
+	 * @return EE_Model_Field_Base
4623
+	 */
4624
+	protected function _deduce_field_from_query_param($query_param_name)
4625
+	{
4626
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4627
+		// which will help us find the database table and column
4628
+		$query_param_parts = explode(".", $query_param_name);
4629
+		if (empty($query_param_parts)) {
4630
+			throw new EE_Error(sprintf(__(
4631
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4632
+				'event_espresso'
4633
+			), $query_param_name));
4634
+		}
4635
+		$number_of_parts = count($query_param_parts);
4636
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4637
+		if ($number_of_parts === 1) {
4638
+			$field_name = $last_query_param_part;
4639
+			$model_obj = $this;
4640
+		} else {// $number_of_parts >= 2
4641
+			// the last part is the column name, and there are only 2parts. therefore...
4642
+			$field_name = $last_query_param_part;
4643
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4644
+		}
4645
+		try {
4646
+			return $model_obj->field_settings_for($field_name);
4647
+		} catch (EE_Error $e) {
4648
+			return null;
4649
+		}
4650
+	}
4651
+
4652
+
4653
+
4654
+	/**
4655
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4656
+	 * alias and column which corresponds to it
4657
+	 *
4658
+	 * @param string $field_name
4659
+	 * @throws EE_Error
4660
+	 * @return string
4661
+	 */
4662
+	public function _get_qualified_column_for_field($field_name)
4663
+	{
4664
+		$all_fields = $this->field_settings();
4665
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4666
+		if ($field) {
4667
+			return $field->get_qualified_column();
4668
+		}
4669
+		throw new EE_Error(
4670
+			sprintf(
4671
+				__(
4672
+					"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.",
4673
+					'event_espresso'
4674
+				),
4675
+				$field_name,
4676
+				get_class($this)
4677
+			)
4678
+		);
4679
+	}
4680
+
4681
+
4682
+
4683
+	/**
4684
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4685
+	 * Example usage:
4686
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4687
+	 *      array(),
4688
+	 *      ARRAY_A,
4689
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4690
+	 *  );
4691
+	 * is equivalent to
4692
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4693
+	 * and
4694
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4695
+	 *      array(
4696
+	 *          array(
4697
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4698
+	 *          ),
4699
+	 *          ARRAY_A,
4700
+	 *          implode(
4701
+	 *              ', ',
4702
+	 *              array_merge(
4703
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4704
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4705
+	 *              )
4706
+	 *          )
4707
+	 *      )
4708
+	 *  );
4709
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4710
+	 *
4711
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4712
+	 *                                            and the one whose fields you are selecting for example: when querying
4713
+	 *                                            tickets model and selecting fields from the tickets model you would
4714
+	 *                                            leave this parameter empty, because no models are needed to join
4715
+	 *                                            between the queried model and the selected one. Likewise when
4716
+	 *                                            querying the datetime model and selecting fields from the tickets
4717
+	 *                                            model, it would also be left empty, because there is a direct
4718
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4719
+	 *                                            them together. However, when querying from the event model and
4720
+	 *                                            selecting fields from the ticket model, you should provide the string
4721
+	 *                                            'Datetime', indicating that the event model must first join to the
4722
+	 *                                            datetime model in order to find its relation to ticket model.
4723
+	 *                                            Also, when querying from the venue model and selecting fields from
4724
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4725
+	 *                                            indicating you need to join the venue model to the event model,
4726
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4727
+	 *                                            This string is used to deduce the prefix that gets added onto the
4728
+	 *                                            models' tables qualified columns
4729
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4730
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4731
+	 *                                            qualified column names
4732
+	 * @return array|string
4733
+	 */
4734
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735
+	{
4736
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4737
+		$qualified_columns = array();
4738
+		foreach ($this->field_settings() as $field_name => $field) {
4739
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4740
+		}
4741
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742
+	}
4743
+
4744
+
4745
+
4746
+	/**
4747
+	 * constructs the select use on special limit joins
4748
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4749
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4750
+	 * (as that is typically where the limits would be set).
4751
+	 *
4752
+	 * @param  string       $table_alias The table the select is being built for
4753
+	 * @param  mixed|string $limit       The limit for this select
4754
+	 * @return string                The final select join element for the query.
4755
+	 */
4756
+	public function _construct_limit_join_select($table_alias, $limit)
4757
+	{
4758
+		$SQL = '';
4759
+		foreach ($this->_tables as $table_obj) {
4760
+			if ($table_obj instanceof EE_Primary_Table) {
4761
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4762
+					? $table_obj->get_select_join_limit($limit)
4763
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4764
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4765
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4766
+					? $table_obj->get_select_join_limit_join($limit)
4767
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4768
+			}
4769
+		}
4770
+		return $SQL;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4777
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4778
+	 *
4779
+	 * @return string SQL
4780
+	 * @throws EE_Error
4781
+	 */
4782
+	public function _construct_internal_join()
4783
+	{
4784
+		$SQL = $this->_get_main_table()->get_table_sql();
4785
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4786
+		return $SQL;
4787
+	}
4788
+
4789
+
4790
+
4791
+	/**
4792
+	 * Constructs the SQL for joining all the tables on this model.
4793
+	 * Normally $alias should be the primary table's alias, but in cases where
4794
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4795
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4796
+	 * alias, this will construct SQL like:
4797
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4798
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4799
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4800
+	 *
4801
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4802
+	 * @return string
4803
+	 */
4804
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4805
+	{
4806
+		$SQL = '';
4807
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4808
+		foreach ($this->_tables as $table_obj) {
4809
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4810
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4811
+					// so we're joining to this table, meaning the table is already in
4812
+					// the FROM statement, BUT the primary table isn't. So we want
4813
+					// to add the inverse join sql
4814
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4815
+				} else {
4816
+					// just add a regular JOIN to this table from the primary table
4817
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4818
+				}
4819
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4820
+		}
4821
+		return $SQL;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
+	 * their data type (eg, '%s', '%d', etc)
4830
+	 *
4831
+	 * @return array
4832
+	 */
4833
+	public function _get_data_types()
4834
+	{
4835
+		$data_types = array();
4836
+		foreach ($this->field_settings() as $field_obj) {
4837
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
+			/** @var $field_obj EE_Model_Field_Base */
4839
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
+		}
4841
+		return $data_types;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4848
+	 *
4849
+	 * @param string $model_name
4850
+	 * @throws EE_Error
4851
+	 * @return EEM_Base
4852
+	 */
4853
+	public function get_related_model_obj($model_name)
4854
+	{
4855
+		$model_classname = "EEM_" . $model_name;
4856
+		if (! class_exists($model_classname)) {
4857
+			throw new EE_Error(sprintf(__(
4858
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859
+				'event_espresso'
4860
+			), $model_name, $model_classname));
4861
+		}
4862
+		return call_user_func($model_classname . "::instance");
4863
+	}
4864
+
4865
+
4866
+
4867
+	/**
4868
+	 * Returns the array of EE_ModelRelations for this model.
4869
+	 *
4870
+	 * @return EE_Model_Relation_Base[]
4871
+	 */
4872
+	public function relation_settings()
4873
+	{
4874
+		return $this->_model_relations;
4875
+	}
4876
+
4877
+
4878
+
4879
+	/**
4880
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4881
+	 * because without THOSE models, this model probably doesn't have much purpose.
4882
+	 * (Eg, without an event, datetimes have little purpose.)
4883
+	 *
4884
+	 * @return EE_Belongs_To_Relation[]
4885
+	 */
4886
+	public function belongs_to_relations()
4887
+	{
4888
+		$belongs_to_relations = array();
4889
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4892
+			}
4893
+		}
4894
+		return $belongs_to_relations;
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * Returns the specified EE_Model_Relation, or throws an exception
4901
+	 *
4902
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4903
+	 * @throws EE_Error
4904
+	 * @return EE_Model_Relation_Base
4905
+	 */
4906
+	public function related_settings_for($relation_name)
4907
+	{
4908
+		$relatedModels = $this->relation_settings();
4909
+		if (! array_key_exists($relation_name, $relatedModels)) {
4910
+			throw new EE_Error(
4911
+				sprintf(
4912
+					__(
4913
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4914
+						'event_espresso'
4915
+					),
4916
+					$relation_name,
4917
+					$this->_get_class_name(),
4918
+					implode(', ', array_keys($relatedModels))
4919
+				)
4920
+			);
4921
+		}
4922
+		return $relatedModels[ $relation_name ];
4923
+	}
4924
+
4925
+
4926
+
4927
+	/**
4928
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4929
+	 * fields
4930
+	 *
4931
+	 * @param string $fieldName
4932
+	 * @param boolean $include_db_only_fields
4933
+	 * @throws EE_Error
4934
+	 * @return EE_Model_Field_Base
4935
+	 */
4936
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4937
+	{
4938
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4939
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4940
+			throw new EE_Error(sprintf(
4941
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4942
+				$fieldName,
4943
+				get_class($this)
4944
+			));
4945
+		}
4946
+		return $fieldSettings[ $fieldName ];
4947
+	}
4948
+
4949
+
4950
+
4951
+	/**
4952
+	 * Checks if this field exists on this model
4953
+	 *
4954
+	 * @param string $fieldName a key in the model's _field_settings array
4955
+	 * @return boolean
4956
+	 */
4957
+	public function has_field($fieldName)
4958
+	{
4959
+		$fieldSettings = $this->field_settings(true);
4960
+		if (isset($fieldSettings[ $fieldName ])) {
4961
+			return true;
4962
+		}
4963
+		return false;
4964
+	}
4965
+
4966
+
4967
+
4968
+	/**
4969
+	 * Returns whether or not this model has a relation to the specified model
4970
+	 *
4971
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4972
+	 * @return boolean
4973
+	 */
4974
+	public function has_relation($relation_name)
4975
+	{
4976
+		$relations = $this->relation_settings();
4977
+		if (isset($relations[ $relation_name ])) {
4978
+			return true;
4979
+		}
4980
+		return false;
4981
+	}
4982
+
4983
+
4984
+
4985
+	/**
4986
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
+	 * Eg, on EE_Answer that would be ANS_ID field object
4988
+	 *
4989
+	 * @param $field_obj
4990
+	 * @return boolean
4991
+	 */
4992
+	public function is_primary_key_field($field_obj)
4993
+	{
4994
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
+	}
4996
+
4997
+
4998
+
4999
+	/**
5000
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5001
+	 * Eg, on EE_Answer that would be ANS_ID field object
5002
+	 *
5003
+	 * @return EE_Model_Field_Base
5004
+	 * @throws EE_Error
5005
+	 */
5006
+	public function get_primary_key_field()
5007
+	{
5008
+		if ($this->_primary_key_field === null) {
5009
+			foreach ($this->field_settings(true) as $field_obj) {
5010
+				if ($this->is_primary_key_field($field_obj)) {
5011
+					$this->_primary_key_field = $field_obj;
5012
+					break;
5013
+				}
5014
+			}
5015
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016
+				throw new EE_Error(sprintf(
5017
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
5018
+					get_class($this)
5019
+				));
5020
+			}
5021
+		}
5022
+		return $this->_primary_key_field;
5023
+	}
5024
+
5025
+
5026
+
5027
+	/**
5028
+	 * Returns whether or not not there is a primary key on this model.
5029
+	 * Internally does some caching.
5030
+	 *
5031
+	 * @return boolean
5032
+	 */
5033
+	public function has_primary_key_field()
5034
+	{
5035
+		if ($this->_has_primary_key_field === null) {
5036
+			try {
5037
+				$this->get_primary_key_field();
5038
+				$this->_has_primary_key_field = true;
5039
+			} catch (EE_Error $e) {
5040
+				$this->_has_primary_key_field = false;
5041
+			}
5042
+		}
5043
+		return $this->_has_primary_key_field;
5044
+	}
5045
+
5046
+
5047
+
5048
+	/**
5049
+	 * Finds the first field of type $field_class_name.
5050
+	 *
5051
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5052
+	 *                                 EE_Foreign_Key_Field, etc
5053
+	 * @return EE_Model_Field_Base or null if none is found
5054
+	 */
5055
+	public function get_a_field_of_type($field_class_name)
5056
+	{
5057
+		foreach ($this->field_settings() as $field) {
5058
+			if ($field instanceof $field_class_name) {
5059
+				return $field;
5060
+			}
5061
+		}
5062
+		return null;
5063
+	}
5064
+
5065
+
5066
+
5067
+	/**
5068
+	 * Gets a foreign key field pointing to model.
5069
+	 *
5070
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5071
+	 * @return EE_Foreign_Key_Field_Base
5072
+	 * @throws EE_Error
5073
+	 */
5074
+	public function get_foreign_key_to($model_name)
5075
+	{
5076
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5077
+			foreach ($this->field_settings() as $field) {
5078
+				if (
5079
+					$field instanceof EE_Foreign_Key_Field_Base
5080
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5081
+				) {
5082
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5083
+					break;
5084
+				}
5085
+			}
5086
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5087
+				throw new EE_Error(sprintf(__(
5088
+					"There is no foreign key field pointing to model %s on model %s",
5089
+					'event_espresso'
5090
+				), $model_name, get_class($this)));
5091
+			}
5092
+		}
5093
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5094
+	}
5095
+
5096
+
5097
+
5098
+	/**
5099
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5100
+	 *
5101
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5102
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5103
+	 *                            Either one works
5104
+	 * @return string
5105
+	 */
5106
+	public function get_table_for_alias($table_alias)
5107
+	{
5108
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5110
+	}
5111
+
5112
+
5113
+
5114
+	/**
5115
+	 * Returns a flat array of all field son this model, instead of organizing them
5116
+	 * by table_alias as they are in the constructor.
5117
+	 *
5118
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5119
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5120
+	 */
5121
+	public function field_settings($include_db_only_fields = false)
5122
+	{
5123
+		if ($include_db_only_fields) {
5124
+			if ($this->_cached_fields === null) {
5125
+				$this->_cached_fields = array();
5126
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5127
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
+						$this->_cached_fields[ $field_name ] = $field_obj;
5129
+					}
5130
+				}
5131
+			}
5132
+			return $this->_cached_fields;
5133
+		}
5134
+		if ($this->_cached_fields_non_db_only === null) {
5135
+			$this->_cached_fields_non_db_only = array();
5136
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5137
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
+					/** @var $field_obj EE_Model_Field_Base */
5139
+					if (! $field_obj->is_db_only_field()) {
5140
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5141
+					}
5142
+				}
5143
+			}
5144
+		}
5145
+		return $this->_cached_fields_non_db_only;
5146
+	}
5147
+
5148
+
5149
+
5150
+	/**
5151
+	 *        cycle though array of attendees and create objects out of each item
5152
+	 *
5153
+	 * @access        private
5154
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5155
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5156
+	 *                           numerically indexed)
5157
+	 * @throws EE_Error
5158
+	 */
5159
+	protected function _create_objects($rows = array())
5160
+	{
5161
+		$array_of_objects = array();
5162
+		if (empty($rows)) {
5163
+			return array();
5164
+		}
5165
+		$count_if_model_has_no_primary_key = 0;
5166
+		$has_primary_key = $this->has_primary_key_field();
5167
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5168
+		foreach ((array) $rows as $row) {
5169
+			if (empty($row)) {
5170
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5171
+				return array();
5172
+			}
5173
+			// check if we've already set this object in the results array,
5174
+			// in which case there's no need to process it further (again)
5175
+			if ($has_primary_key) {
5176
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5177
+					$row,
5178
+					$primary_key_field->get_qualified_column(),
5179
+					$primary_key_field->get_table_column()
5180
+				);
5181
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5182
+					continue;
5183
+				}
5184
+			}
5185
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5186
+			if (! $classInstance) {
5187
+				throw new EE_Error(
5188
+					sprintf(
5189
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5190
+						$this->get_this_model_name(),
5191
+						http_build_query($row)
5192
+					)
5193
+				);
5194
+			}
5195
+			// set the timezone on the instantiated objects
5196
+			$classInstance->set_timezone($this->_timezone);
5197
+			// make sure if there is any timezone setting present that we set the timezone for the object
5198
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
+			$array_of_objects[ $key ] = $classInstance;
5200
+			// also, for all the relations of type BelongsTo, see if we can cache
5201
+			// those related models
5202
+			// (we could do this for other relations too, but if there are conditions
5203
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5204
+			// so it requires a little more thought than just caching them immediately...)
5205
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5206
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5207
+					// check if this model's INFO is present. If so, cache it on the model
5208
+					$other_model = $relation_obj->get_other_model();
5209
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5210
+					// if we managed to make a model object from the results, cache it on the main model object
5211
+					if ($other_model_obj_maybe) {
5212
+						// set timezone on these other model objects if they are present
5213
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5214
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5215
+					}
5216
+				}
5217
+			}
5218
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5219
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5220
+			// the field in the CustomSelects object
5221
+			if ($this->_custom_selections instanceof CustomSelects) {
5222
+				$classInstance->setCustomSelectsValues(
5223
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5224
+				);
5225
+			}
5226
+		}
5227
+		return $array_of_objects;
5228
+	}
5229
+
5230
+
5231
+	/**
5232
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5233
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5234
+	 *
5235
+	 * @param array $db_results_row
5236
+	 * @return array
5237
+	 */
5238
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5239
+	{
5240
+		$results = array();
5241
+		if ($this->_custom_selections instanceof CustomSelects) {
5242
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
+				if (isset($db_results_row[ $alias ])) {
5244
+					$results[ $alias ] = $this->convertValueToDataType(
5245
+						$db_results_row[ $alias ],
5246
+						$this->_custom_selections->getDataTypeForAlias($alias)
5247
+					);
5248
+				}
5249
+			}
5250
+		}
5251
+		return $results;
5252
+	}
5253
+
5254
+
5255
+	/**
5256
+	 * This will set the value for the given alias
5257
+	 * @param string $value
5258
+	 * @param string $datatype (one of %d, %s, %f)
5259
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5260
+	 */
5261
+	protected function convertValueToDataType($value, $datatype)
5262
+	{
5263
+		switch ($datatype) {
5264
+			case '%f':
5265
+				return (float) $value;
5266
+			case '%d':
5267
+				return (int) $value;
5268
+			default:
5269
+				return (string) $value;
5270
+		}
5271
+	}
5272
+
5273
+
5274
+	/**
5275
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5276
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5277
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5278
+	 * object (as set in the model_field!).
5279
+	 *
5280
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5281
+	 */
5282
+	public function create_default_object()
5283
+	{
5284
+		$this_model_fields_and_values = array();
5285
+		// setup the row using default values;
5286
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5287
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5288
+		}
5289
+		$className = $this->_get_class_name();
5290
+		$classInstance = EE_Registry::instance()
5291
+									->load_class($className, array($this_model_fields_and_values), false, false);
5292
+		return $classInstance;
5293
+	}
5294
+
5295
+
5296
+
5297
+	/**
5298
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5299
+	 *                             or an stdClass where each property is the name of a column,
5300
+	 * @return EE_Base_Class
5301
+	 * @throws EE_Error
5302
+	 */
5303
+	public function instantiate_class_from_array_or_object($cols_n_values)
5304
+	{
5305
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5306
+			$cols_n_values = get_object_vars($cols_n_values);
5307
+		}
5308
+		$primary_key = null;
5309
+		// make sure the array only has keys that are fields/columns on this model
5310
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5313
+		}
5314
+		$className = $this->_get_class_name();
5315
+		// check we actually found results that we can use to build our model object
5316
+		// if not, return null
5317
+		if ($this->has_primary_key_field()) {
5318
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
+				return null;
5320
+			}
5321
+		} elseif ($this->unique_indexes()) {
5322
+			$first_column = reset($this_model_fields_n_values);
5323
+			if (empty($first_column)) {
5324
+				return null;
5325
+			}
5326
+		}
5327
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328
+		if ($primary_key) {
5329
+			$classInstance = $this->get_from_entity_map($primary_key);
5330
+			if (! $classInstance) {
5331
+				$classInstance = EE_Registry::instance()
5332
+											->load_class(
5333
+												$className,
5334
+												array($this_model_fields_n_values, $this->_timezone),
5335
+												true,
5336
+												false
5337
+											);
5338
+				// add this new object to the entity map
5339
+				$classInstance = $this->add_to_entity_map($classInstance);
5340
+			}
5341
+		} else {
5342
+			$classInstance = EE_Registry::instance()
5343
+										->load_class(
5344
+											$className,
5345
+											array($this_model_fields_n_values, $this->_timezone),
5346
+											true,
5347
+											false
5348
+										);
5349
+		}
5350
+		return $classInstance;
5351
+	}
5352
+
5353
+
5354
+
5355
+	/**
5356
+	 * Gets the model object from the  entity map if it exists
5357
+	 *
5358
+	 * @param int|string $id the ID of the model object
5359
+	 * @return EE_Base_Class
5360
+	 */
5361
+	public function get_from_entity_map($id)
5362
+	{
5363
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5365
+	}
5366
+
5367
+
5368
+
5369
+	/**
5370
+	 * add_to_entity_map
5371
+	 * Adds the object to the model's entity mappings
5372
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5373
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5374
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5375
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5376
+	 *        then this method should be called immediately after the update query
5377
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5378
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5379
+	 *
5380
+	 * @param    EE_Base_Class $object
5381
+	 * @throws EE_Error
5382
+	 * @return \EE_Base_Class
5383
+	 */
5384
+	public function add_to_entity_map(EE_Base_Class $object)
5385
+	{
5386
+		$className = $this->_get_class_name();
5387
+		if (! $object instanceof $className) {
5388
+			throw new EE_Error(sprintf(
5389
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390
+				is_object($object) ? get_class($object) : $object,
5391
+				$className
5392
+			));
5393
+		}
5394
+		/** @var $object EE_Base_Class */
5395
+		if (! $object->ID()) {
5396
+			throw new EE_Error(sprintf(__(
5397
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5398
+				"event_espresso"
5399
+			), get_class($this)));
5400
+		}
5401
+		// double check it's not already there
5402
+		$classInstance = $this->get_from_entity_map($object->ID());
5403
+		if ($classInstance) {
5404
+			return $classInstance;
5405
+		}
5406
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5407
+		return $object;
5408
+	}
5409
+
5410
+
5411
+
5412
+	/**
5413
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5414
+	 * if no identifier is provided, then the entire entity map is emptied
5415
+	 *
5416
+	 * @param int|string $id the ID of the model object
5417
+	 * @return boolean
5418
+	 */
5419
+	public function clear_entity_map($id = null)
5420
+	{
5421
+		if (empty($id)) {
5422
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5423
+			return true;
5424
+		}
5425
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5427
+			return true;
5428
+		}
5429
+		return false;
5430
+	}
5431
+
5432
+
5433
+
5434
+	/**
5435
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5436
+	 * Given an array where keys are column (or column alias) names and values,
5437
+	 * returns an array of their corresponding field names and database values
5438
+	 *
5439
+	 * @param array $cols_n_values
5440
+	 * @return array
5441
+	 */
5442
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5443
+	{
5444
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5445
+	}
5446
+
5447
+
5448
+
5449
+	/**
5450
+	 * _deduce_fields_n_values_from_cols_n_values
5451
+	 * Given an array where keys are column (or column alias) names and values,
5452
+	 * returns an array of their corresponding field names and database values
5453
+	 *
5454
+	 * @param string $cols_n_values
5455
+	 * @return array
5456
+	 */
5457
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
+	{
5459
+		$this_model_fields_n_values = array();
5460
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5461
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5462
+				$cols_n_values,
5463
+				$table_obj->get_fully_qualified_pk_column(),
5464
+				$table_obj->get_pk_column()
5465
+			);
5466
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5467
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
+					if (! $field_obj->is_db_only_field()) {
5470
+						// prepare field as if its coming from db
5471
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5473
+					}
5474
+				}
5475
+			} else {
5476
+				// the table's rows existed. Use their values
5477
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
+					if (! $field_obj->is_db_only_field()) {
5479
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5480
+							$cols_n_values,
5481
+							$field_obj->get_qualified_column(),
5482
+							$field_obj->get_table_column()
5483
+						);
5484
+					}
5485
+				}
5486
+			}
5487
+		}
5488
+		return $this_model_fields_n_values;
5489
+	}
5490
+
5491
+
5492
+	/**
5493
+	 * @param $cols_n_values
5494
+	 * @param $qualified_column
5495
+	 * @param $regular_column
5496
+	 * @return null
5497
+	 * @throws EE_Error
5498
+	 * @throws ReflectionException
5499
+	 */
5500
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5501
+	{
5502
+		$value = null;
5503
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504
+		// does the field on the model relate to this column retrieved from the db?
5505
+		// or is it a db-only field? (not relating to the model)
5506
+		if (isset($cols_n_values[ $qualified_column ])) {
5507
+			$value = $cols_n_values[ $qualified_column ];
5508
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5509
+			$value = $cols_n_values[ $regular_column ];
5510
+		} elseif (! empty($this->foreign_key_aliases)) {
5511
+			// no PK?  ok check if there is a foreign key alias set for this table
5512
+			// then check if that alias exists in the incoming data
5513
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
+					$value = $cols_n_values[ $FK_alias ];
5517
+					[$pk_class] = explode('.', $PK_column);
5518
+					$pk_model_name = "EEM_{$pk_class}";
5519
+					/** @var EEM_Base $pk_model */
5520
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5521
+					if ($pk_model instanceof EEM_Base) {
5522
+						// make sure object is pulled from db and added to entity map
5523
+						$pk_model->get_one_by_ID($value);
5524
+					}
5525
+					break;
5526
+				}
5527
+			}
5528
+		}
5529
+		return $value;
5530
+	}
5531
+
5532
+
5533
+
5534
+	/**
5535
+	 * refresh_entity_map_from_db
5536
+	 * Makes sure the model object in the entity map at $id assumes the values
5537
+	 * of the database (opposite of EE_base_Class::save())
5538
+	 *
5539
+	 * @param int|string $id
5540
+	 * @return EE_Base_Class
5541
+	 * @throws EE_Error
5542
+	 */
5543
+	public function refresh_entity_map_from_db($id)
5544
+	{
5545
+		$obj_in_map = $this->get_from_entity_map($id);
5546
+		if ($obj_in_map) {
5547
+			$wpdb_results = $this->_get_all_wpdb_results(
5548
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5549
+			);
5550
+			if ($wpdb_results && is_array($wpdb_results)) {
5551
+				$one_row = reset($wpdb_results);
5552
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5553
+					$obj_in_map->set_from_db($field_name, $db_value);
5554
+				}
5555
+				// clear the cache of related model objects
5556
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5557
+					$obj_in_map->clear_cache($relation_name, null, true);
5558
+				}
5559
+			}
5560
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5561
+			return $obj_in_map;
5562
+		}
5563
+		return $this->get_one_by_ID($id);
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * refresh_entity_map_with
5570
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5571
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5572
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5573
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5574
+	 *
5575
+	 * @param int|string    $id
5576
+	 * @param EE_Base_Class $replacing_model_obj
5577
+	 * @return \EE_Base_Class
5578
+	 * @throws EE_Error
5579
+	 */
5580
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5581
+	{
5582
+		$obj_in_map = $this->get_from_entity_map($id);
5583
+		if ($obj_in_map) {
5584
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5585
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5586
+					$obj_in_map->set($field_name, $value);
5587
+				}
5588
+				// make the model object in the entity map's cache match the $replacing_model_obj
5589
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5590
+					$obj_in_map->clear_cache($relation_name, null, true);
5591
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5592
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5593
+					}
5594
+				}
5595
+			}
5596
+			return $obj_in_map;
5597
+		}
5598
+		$this->add_to_entity_map($replacing_model_obj);
5599
+		return $replacing_model_obj;
5600
+	}
5601
+
5602
+
5603
+
5604
+	/**
5605
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5606
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5607
+	 * require_once($this->_getClassName().".class.php");
5608
+	 *
5609
+	 * @return string
5610
+	 */
5611
+	private function _get_class_name()
5612
+	{
5613
+		return "EE_" . $this->get_this_model_name();
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5620
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5621
+	 * it would be 'Events'.
5622
+	 *
5623
+	 * @param int $quantity
5624
+	 * @return string
5625
+	 */
5626
+	public function item_name($quantity = 1)
5627
+	{
5628
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5629
+	}
5630
+
5631
+
5632
+
5633
+	/**
5634
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5635
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5636
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5637
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5638
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5639
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5640
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5641
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5642
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5643
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5644
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5645
+	 *        return $previousReturnValue.$returnString;
5646
+	 * }
5647
+	 * require('EEM_Answer.model.php');
5648
+	 * $answer=EEM_Answer::instance();
5649
+	 * echo $answer->my_callback('monkeys',100);
5650
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5651
+	 *
5652
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5653
+	 * @param array  $args       array of original arguments passed to the function
5654
+	 * @throws EE_Error
5655
+	 * @return mixed whatever the plugin which calls add_filter decides
5656
+	 */
5657
+	public function __call($methodName, $args)
5658
+	{
5659
+		$className = get_class($this);
5660
+		$tagName = "FHEE__{$className}__{$methodName}";
5661
+		if (! has_filter($tagName)) {
5662
+			throw new EE_Error(
5663
+				sprintf(
5664
+					__(
5665
+						'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 );',
5666
+						'event_espresso'
5667
+					),
5668
+					$methodName,
5669
+					$className,
5670
+					$tagName,
5671
+					'<br />'
5672
+				)
5673
+			);
5674
+		}
5675
+		return apply_filters($tagName, null, $this, $args);
5676
+	}
5677
+
5678
+
5679
+
5680
+	/**
5681
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
+	 *
5684
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5686
+	 *                                                       the object's class name
5687
+	 *                                                       or object's ID
5688
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
+	 *                                                       exists in the database. If it does not, we add it
5690
+	 * @throws EE_Error
5691
+	 * @return EE_Base_Class
5692
+	 */
5693
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5694
+	{
5695
+		$className = $this->_get_class_name();
5696
+		if ($base_class_obj_or_id instanceof $className) {
5697
+			$model_object = $base_class_obj_or_id;
5698
+		} else {
5699
+			$primary_key_field = $this->get_primary_key_field();
5700
+			if (
5701
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5702
+				&& (
5703
+					is_int($base_class_obj_or_id)
5704
+					|| is_string($base_class_obj_or_id)
5705
+				)
5706
+			) {
5707
+				// assume it's an ID.
5708
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5709
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
+			} elseif (
5711
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5712
+				&& is_string($base_class_obj_or_id)
5713
+			) {
5714
+				// assume its a string representation of the object
5715
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5716
+			} else {
5717
+				throw new EE_Error(
5718
+					sprintf(
5719
+						__(
5720
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5721
+							'event_espresso'
5722
+						),
5723
+						$base_class_obj_or_id,
5724
+						$this->_get_class_name(),
5725
+						print_r($base_class_obj_or_id, true)
5726
+					)
5727
+				);
5728
+			}
5729
+		}
5730
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5731
+			$model_object->save();
5732
+		}
5733
+		return $model_object;
5734
+	}
5735
+
5736
+
5737
+
5738
+	/**
5739
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
+	 * returns it ID.
5742
+	 *
5743
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
+	 * @return int|string depending on the type of this model object's ID
5745
+	 * @throws EE_Error
5746
+	 */
5747
+	public function ensure_is_ID($base_class_obj_or_id)
5748
+	{
5749
+		$className = $this->_get_class_name();
5750
+		if ($base_class_obj_or_id instanceof $className) {
5751
+			/** @var $base_class_obj_or_id EE_Base_Class */
5752
+			$id = $base_class_obj_or_id->ID();
5753
+		} elseif (is_int($base_class_obj_or_id)) {
5754
+			// assume it's an ID
5755
+			$id = $base_class_obj_or_id;
5756
+		} elseif (is_string($base_class_obj_or_id)) {
5757
+			// assume its a string representation of the object
5758
+			$id = $base_class_obj_or_id;
5759
+		} else {
5760
+			throw new EE_Error(sprintf(
5761
+				__(
5762
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
+					'event_espresso'
5764
+				),
5765
+				$base_class_obj_or_id,
5766
+				$this->_get_class_name(),
5767
+				print_r($base_class_obj_or_id, true)
5768
+			));
5769
+		}
5770
+		return $id;
5771
+	}
5772
+
5773
+
5774
+
5775
+	/**
5776
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
+	 * been sanitized and converted into the appropriate domain.
5779
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
+	 * $EVT = EEM_Event::instance(); $old_setting =
5784
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5786
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
+	 *
5789
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5790
+	 * @return void
5791
+	 */
5792
+	public function assume_values_already_prepared_by_model_object(
5793
+		$values_already_prepared = self::not_prepared_by_model_object
5794
+	) {
5795
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
+	}
5797
+
5798
+
5799
+
5800
+	/**
5801
+	 * Read comments for assume_values_already_prepared_by_model_object()
5802
+	 *
5803
+	 * @return int
5804
+	 */
5805
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
+	{
5807
+		return $this->_values_already_prepared_by_model_object;
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Gets all the indexes on this model
5814
+	 *
5815
+	 * @return EE_Index[]
5816
+	 */
5817
+	public function indexes()
5818
+	{
5819
+		return $this->_indexes;
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * Gets all the Unique Indexes on this model
5826
+	 *
5827
+	 * @return EE_Unique_Index[]
5828
+	 */
5829
+	public function unique_indexes()
5830
+	{
5831
+		$unique_indexes = array();
5832
+		foreach ($this->_indexes as $name => $index) {
5833
+			if ($index instanceof EE_Unique_Index) {
5834
+				$unique_indexes [ $name ] = $index;
5835
+			}
5836
+		}
5837
+		return $unique_indexes;
5838
+	}
5839
+
5840
+
5841
+
5842
+	/**
5843
+	 * Gets all the fields which, when combined, make the primary key.
5844
+	 * This is usually just an array with 1 element (the primary key), but in cases
5845
+	 * where there is no primary key, it's a combination of fields as defined
5846
+	 * on a primary index
5847
+	 *
5848
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5849
+	 * @throws EE_Error
5850
+	 */
5851
+	public function get_combined_primary_key_fields()
5852
+	{
5853
+		foreach ($this->indexes() as $index) {
5854
+			if ($index instanceof EE_Primary_Key_Index) {
5855
+				return $index->fields();
5856
+			}
5857
+		}
5858
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5859
+	}
5860
+
5861
+
5862
+
5863
+	/**
5864
+	 * Used to build a primary key string (when the model has no primary key),
5865
+	 * which can be used a unique string to identify this model object.
5866
+	 *
5867
+	 * @param array $fields_n_values keys are field names, values are their values.
5868
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5869
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5870
+	 *                               before passing it to this function (that will convert it from columns-n-values
5871
+	 *                               to field-names-n-values).
5872
+	 * @return string
5873
+	 * @throws EE_Error
5874
+	 */
5875
+	public function get_index_primary_key_string($fields_n_values)
5876
+	{
5877
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5878
+			$fields_n_values,
5879
+			$this->get_combined_primary_key_fields()
5880
+		);
5881
+		return http_build_query($cols_n_values_for_primary_key_index);
5882
+	}
5883
+
5884
+
5885
+
5886
+	/**
5887
+	 * Gets the field values from the primary key string
5888
+	 *
5889
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5890
+	 * @param string $index_primary_key_string
5891
+	 * @return null|array
5892
+	 * @throws EE_Error
5893
+	 */
5894
+	public function parse_index_primary_key_string($index_primary_key_string)
5895
+	{
5896
+		$key_fields = $this->get_combined_primary_key_fields();
5897
+		// check all of them are in the $id
5898
+		$key_vals_in_combined_pk = array();
5899
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900
+		foreach ($key_fields as $key_field_name => $field_obj) {
5901
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5902
+				return null;
5903
+			}
5904
+		}
5905
+		return $key_vals_in_combined_pk;
5906
+	}
5907
+
5908
+
5909
+
5910
+	/**
5911
+	 * verifies that an array of key-value pairs for model fields has a key
5912
+	 * for each field comprising the primary key index
5913
+	 *
5914
+	 * @param array $key_vals
5915
+	 * @return boolean
5916
+	 * @throws EE_Error
5917
+	 */
5918
+	public function has_all_combined_primary_key_fields($key_vals)
5919
+	{
5920
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921
+		foreach ($keys_it_should_have as $key) {
5922
+			if (! isset($key_vals[ $key ])) {
5923
+				return false;
5924
+			}
5925
+		}
5926
+		return true;
5927
+	}
5928
+
5929
+
5930
+
5931
+	/**
5932
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5933
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5934
+	 *
5935
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5936
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5937
+	 * @throws EE_Error
5938
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5939
+	 *                                                              indexed)
5940
+	 */
5941
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5942
+	{
5943
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5944
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5945
+		} elseif (is_array($model_object_or_attributes_array)) {
5946
+			$attributes_array = $model_object_or_attributes_array;
5947
+		} else {
5948
+			throw new EE_Error(sprintf(__(
5949
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5950
+				"event_espresso"
5951
+			), $model_object_or_attributes_array));
5952
+		}
5953
+		// even copies obviously won't have the same ID, so remove the primary key
5954
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
+			unset($attributes_array[ $this->primary_key_name() ]);
5957
+		}
5958
+		if (isset($query_params[0])) {
5959
+			$query_params[0] = array_merge($attributes_array, $query_params);
5960
+		} else {
5961
+			$query_params[0] = $attributes_array;
5962
+		}
5963
+		return $this->get_all($query_params);
5964
+	}
5965
+
5966
+
5967
+
5968
+	/**
5969
+	 * Gets the first copy we find. See get_all_copies for more details
5970
+	 *
5971
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5972
+	 * @param array $query_params
5973
+	 * @return EE_Base_Class
5974
+	 * @throws EE_Error
5975
+	 */
5976
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977
+	{
5978
+		if (! is_array($query_params)) {
5979
+			EE_Error::doing_it_wrong(
5980
+				'EEM_Base::get_one_copy',
5981
+				sprintf(
5982
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
+					gettype($query_params)
5984
+				),
5985
+				'4.6.0'
5986
+			);
5987
+			$query_params = array();
5988
+		}
5989
+		$query_params['limit'] = 1;
5990
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
+		if (is_array($copies)) {
5992
+			return array_shift($copies);
5993
+		}
5994
+		return null;
5995
+	}
5996
+
5997
+
5998
+
5999
+	/**
6000
+	 * Updates the item with the specified id. Ignores default query parameters because
6001
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6002
+	 *
6003
+	 * @param array      $fields_n_values keys are field names, values are their new values
6004
+	 * @param int|string $id              the value of the primary key to update
6005
+	 * @return int number of rows updated
6006
+	 * @throws EE_Error
6007
+	 */
6008
+	public function update_by_ID($fields_n_values, $id)
6009
+	{
6010
+		$query_params = array(
6011
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
6012
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
+		);
6014
+		return $this->update($fields_n_values, $query_params);
6015
+	}
6016
+
6017
+
6018
+
6019
+	/**
6020
+	 * Changes an operator which was supplied to the models into one usable in SQL
6021
+	 *
6022
+	 * @param string $operator_supplied
6023
+	 * @return string an operator which can be used in SQL
6024
+	 * @throws EE_Error
6025
+	 */
6026
+	private function _prepare_operator_for_sql($operator_supplied)
6027
+	{
6028
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
+			: null;
6030
+		if ($sql_operator) {
6031
+			return $sql_operator;
6032
+		}
6033
+		throw new EE_Error(
6034
+			sprintf(
6035
+				__(
6036
+					"The operator '%s' is not in the list of valid operators: %s",
6037
+					"event_espresso"
6038
+				),
6039
+				$operator_supplied,
6040
+				implode(",", array_keys($this->_valid_operators))
6041
+			)
6042
+		);
6043
+	}
6044
+
6045
+
6046
+
6047
+	/**
6048
+	 * Gets the valid operators
6049
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6050
+	 */
6051
+	public function valid_operators()
6052
+	{
6053
+		return $this->_valid_operators;
6054
+	}
6055
+
6056
+
6057
+
6058
+	/**
6059
+	 * Gets the between-style operators (take 2 arguments).
6060
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6061
+	 */
6062
+	public function valid_between_style_operators()
6063
+	{
6064
+		return array_intersect(
6065
+			$this->valid_operators(),
6066
+			$this->_between_style_operators
6067
+		);
6068
+	}
6069
+
6070
+	/**
6071
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6073
+	 */
6074
+	public function valid_like_style_operators()
6075
+	{
6076
+		return array_intersect(
6077
+			$this->valid_operators(),
6078
+			$this->_like_style_operators
6079
+		);
6080
+	}
6081
+
6082
+	/**
6083
+	 * Gets the "in"-style operators
6084
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6085
+	 */
6086
+	public function valid_in_style_operators()
6087
+	{
6088
+		return array_intersect(
6089
+			$this->valid_operators(),
6090
+			$this->_in_style_operators
6091
+		);
6092
+	}
6093
+
6094
+	/**
6095
+	 * Gets the "null"-style operators (accept no arguments)
6096
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6097
+	 */
6098
+	public function valid_null_style_operators()
6099
+	{
6100
+		return array_intersect(
6101
+			$this->valid_operators(),
6102
+			$this->_null_style_operators
6103
+		);
6104
+	}
6105
+
6106
+	/**
6107
+	 * Gets an array where keys are the primary keys and values are their 'names'
6108
+	 * (as determined by the model object's name() function, which is often overridden)
6109
+	 *
6110
+	 * @param array $query_params like get_all's
6111
+	 * @return string[]
6112
+	 * @throws EE_Error
6113
+	 */
6114
+	public function get_all_names($query_params = array())
6115
+	{
6116
+		$objs = $this->get_all($query_params);
6117
+		$names = array();
6118
+		foreach ($objs as $obj) {
6119
+			$names[ $obj->ID() ] = $obj->name();
6120
+		}
6121
+		return $names;
6122
+	}
6123
+
6124
+
6125
+
6126
+	/**
6127
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6128
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6129
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6130
+	 * array_keys() on $model_objects.
6131
+	 *
6132
+	 * @param \EE_Base_Class[] $model_objects
6133
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6134
+	 *                                               in the returned array
6135
+	 * @return array
6136
+	 * @throws EE_Error
6137
+	 */
6138
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139
+	{
6140
+		if (! $this->has_primary_key_field()) {
6141
+			if (WP_DEBUG) {
6142
+				EE_Error::add_error(
6143
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6144
+					__FILE__,
6145
+					__FUNCTION__,
6146
+					__LINE__
6147
+				);
6148
+			}
6149
+		}
6150
+		$IDs = array();
6151
+		foreach ($model_objects as $model_object) {
6152
+			$id = $model_object->ID();
6153
+			if (! $id) {
6154
+				if ($filter_out_empty_ids) {
6155
+					continue;
6156
+				}
6157
+				if (WP_DEBUG) {
6158
+					EE_Error::add_error(
6159
+						__(
6160
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6161
+							'event_espresso'
6162
+						),
6163
+						__FILE__,
6164
+						__FUNCTION__,
6165
+						__LINE__
6166
+					);
6167
+				}
6168
+			}
6169
+			$IDs[] = $id;
6170
+		}
6171
+		return $IDs;
6172
+	}
6173
+
6174
+
6175
+
6176
+	/**
6177
+	 * Returns the string used in capabilities relating to this model. If there
6178
+	 * are no capabilities that relate to this model returns false
6179
+	 *
6180
+	 * @return string|false
6181
+	 */
6182
+	public function cap_slug()
6183
+	{
6184
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6185
+	}
6186
+
6187
+
6188
+
6189
+	/**
6190
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6191
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6192
+	 * only returns the cap restrictions array in that context (ie, the array
6193
+	 * at that key)
6194
+	 *
6195
+	 * @param string $context
6196
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
+	 * @throws EE_Error
6198
+	 */
6199
+	public function cap_restrictions($context = EEM_Base::caps_read)
6200
+	{
6201
+		EEM_Base::verify_is_valid_cap_context($context);
6202
+		// check if we ought to run the restriction generator first
6203
+		if (
6204
+			isset($this->_cap_restriction_generators[ $context ])
6205
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6207
+		) {
6208
+			$this->_cap_restrictions[ $context ] = array_merge(
6209
+				$this->_cap_restrictions[ $context ],
6210
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6211
+			);
6212
+		}
6213
+		// and make sure we've finalized the construction of each restriction
6214
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6215
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216
+				$where_conditions_obj->_finalize_construct($this);
6217
+			}
6218
+		}
6219
+		return $this->_cap_restrictions[ $context ];
6220
+	}
6221
+
6222
+
6223
+
6224
+	/**
6225
+	 * Indicating whether or not this model thinks its a wp core model
6226
+	 *
6227
+	 * @return boolean
6228
+	 */
6229
+	public function is_wp_core_model()
6230
+	{
6231
+		return $this->_wp_core_model;
6232
+	}
6233
+
6234
+
6235
+
6236
+	/**
6237
+	 * Gets all the caps that are missing which impose a restriction on
6238
+	 * queries made in this context
6239
+	 *
6240
+	 * @param string $context one of EEM_Base::caps_ constants
6241
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6242
+	 * @throws EE_Error
6243
+	 */
6244
+	public function caps_missing($context = EEM_Base::caps_read)
6245
+	{
6246
+		$missing_caps = array();
6247
+		$cap_restrictions = $this->cap_restrictions($context);
6248
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249
+			if (
6250
+				! EE_Capabilities::instance()
6251
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6252
+			) {
6253
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6254
+			}
6255
+		}
6256
+		return $missing_caps;
6257
+	}
6258
+
6259
+
6260
+
6261
+	/**
6262
+	 * Gets the mapping from capability contexts to action strings used in capability names
6263
+	 *
6264
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6265
+	 * one of 'read', 'edit', or 'delete'
6266
+	 */
6267
+	public function cap_contexts_to_cap_action_map()
6268
+	{
6269
+		return apply_filters(
6270
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6271
+			$this->_cap_contexts_to_cap_action_map,
6272
+			$this
6273
+		);
6274
+	}
6275
+
6276
+
6277
+
6278
+	/**
6279
+	 * Gets the action string for the specified capability context
6280
+	 *
6281
+	 * @param string $context
6282
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6283
+	 * @throws EE_Error
6284
+	 */
6285
+	public function cap_action_for_context($context)
6286
+	{
6287
+		$mapping = $this->cap_contexts_to_cap_action_map();
6288
+		if (isset($mapping[ $context ])) {
6289
+			return $mapping[ $context ];
6290
+		}
6291
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292
+			return $action;
6293
+		}
6294
+		throw new EE_Error(
6295
+			sprintf(
6296
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6297
+				$context,
6298
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6299
+			)
6300
+		);
6301
+	}
6302
+
6303
+
6304
+
6305
+	/**
6306
+	 * Returns all the capability contexts which are valid when querying models
6307
+	 *
6308
+	 * @return array
6309
+	 */
6310
+	public static function valid_cap_contexts()
6311
+	{
6312
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6313
+			self::caps_read,
6314
+			self::caps_read_admin,
6315
+			self::caps_edit,
6316
+			self::caps_delete,
6317
+		));
6318
+	}
6319
+
6320
+
6321
+
6322
+	/**
6323
+	 * Returns all valid options for 'default_where_conditions'
6324
+	 *
6325
+	 * @return array
6326
+	 */
6327
+	public static function valid_default_where_conditions()
6328
+	{
6329
+		return array(
6330
+			EEM_Base::default_where_conditions_all,
6331
+			EEM_Base::default_where_conditions_this_only,
6332
+			EEM_Base::default_where_conditions_others_only,
6333
+			EEM_Base::default_where_conditions_minimum_all,
6334
+			EEM_Base::default_where_conditions_minimum_others,
6335
+			EEM_Base::default_where_conditions_none
6336
+		);
6337
+	}
6338
+
6339
+	// public static function default_where_conditions_full
6340
+	/**
6341
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
+	 *
6343
+	 * @param string $context
6344
+	 * @return bool
6345
+	 * @throws EE_Error
6346
+	 */
6347
+	public static function verify_is_valid_cap_context($context)
6348
+	{
6349
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
+		if (in_array($context, $valid_cap_contexts)) {
6351
+			return true;
6352
+		}
6353
+		throw new EE_Error(
6354
+			sprintf(
6355
+				__(
6356
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
+					'event_espresso'
6358
+				),
6359
+				$context,
6360
+				'EEM_Base',
6361
+				implode(',', $valid_cap_contexts)
6362
+			)
6363
+		);
6364
+	}
6365
+
6366
+
6367
+
6368
+	/**
6369
+	 * Clears all the models field caches. This is only useful when a sub-class
6370
+	 * might have added a field or something and these caches might be invalidated
6371
+	 */
6372
+	protected function _invalidate_field_caches()
6373
+	{
6374
+		$this->_cache_foreign_key_to_fields = array();
6375
+		$this->_cached_fields = null;
6376
+		$this->_cached_fields_non_db_only = null;
6377
+	}
6378
+
6379
+
6380
+
6381
+	/**
6382
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6383
+	 * (eg "and", "or", "not").
6384
+	 *
6385
+	 * @return array
6386
+	 */
6387
+	public function logic_query_param_keys()
6388
+	{
6389
+		return $this->_logic_query_param_keys;
6390
+	}
6391
+
6392
+
6393
+
6394
+	/**
6395
+	 * Determines whether or not the where query param array key is for a logic query param.
6396
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6397
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6398
+	 *
6399
+	 * @param $query_param_key
6400
+	 * @return bool
6401
+	 */
6402
+	public function is_logic_query_param_key($query_param_key)
6403
+	{
6404
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405
+			if (
6406
+				$query_param_key === $logic_query_param_key
6407
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6408
+			) {
6409
+				return true;
6410
+			}
6411
+		}
6412
+		return false;
6413
+	}
6414
+
6415
+	/**
6416
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6417
+	 * @since 4.9.74.p
6418
+	 * @return boolean
6419
+	 */
6420
+	public function hasPassword()
6421
+	{
6422
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6423
+		if ($this->has_password_field === null) {
6424
+			$password_field = $this->getPasswordField();
6425
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6426
+		}
6427
+		return $this->has_password_field;
6428
+	}
6429
+
6430
+	/**
6431
+	 * Returns the password field on this model, if there is one
6432
+	 * @since 4.9.74.p
6433
+	 * @return EE_Password_Field|null
6434
+	 */
6435
+	public function getPasswordField()
6436
+	{
6437
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6438
+		// there's no need to search for it. If we don't know yet, then find out
6439
+		if ($this->has_password_field === null && $this->password_field === null) {
6440
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6441
+		}
6442
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6443
+		return $this->password_field;
6444
+	}
6445
+
6446
+
6447
+	/**
6448
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6449
+	 * @since 4.9.74.p
6450
+	 * @return EE_Model_Field_Base[]
6451
+	 * @throws EE_Error
6452
+	 */
6453
+	public function getPasswordProtectedFields()
6454
+	{
6455
+		$password_field = $this->getPasswordField();
6456
+		$fields = array();
6457
+		if ($password_field instanceof EE_Password_Field) {
6458
+			$field_names = $password_field->protectedFields();
6459
+			foreach ($field_names as $field_name) {
6460
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6461
+			}
6462
+		}
6463
+		return $fields;
6464
+	}
6465
+
6466
+
6467
+	/**
6468
+	 * Checks if the current user can perform the requested action on this model
6469
+	 * @since 4.9.74.p
6470
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6471
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6472
+	 * @return bool
6473
+	 * @throws EE_Error
6474
+	 * @throws InvalidArgumentException
6475
+	 * @throws InvalidDataTypeException
6476
+	 * @throws InvalidInterfaceException
6477
+	 * @throws ReflectionException
6478
+	 * @throws UnexpectedEntityException
6479
+	 */
6480
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6481
+	{
6482
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484
+		}
6485
+		if (!is_array($model_obj_or_fields_n_values)) {
6486
+			throw new UnexpectedEntityException(
6487
+				$model_obj_or_fields_n_values,
6488
+				'EE_Base_Class',
6489
+				sprintf(
6490
+					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'),
6491
+					__FUNCTION__
6492
+				)
6493
+			);
6494
+		}
6495
+		return $this->exists(
6496
+			$this->alter_query_params_to_restrict_by_ID(
6497
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6498
+				array(
6499
+					'default_where_conditions' => 'none',
6500
+					'caps'                     => $cap_to_check,
6501
+				)
6502
+			)
6503
+		);
6504
+	}
6505
+
6506
+	/**
6507
+	 * Returns the query param where conditions key to the password affecting this model.
6508
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6509
+	 * @since 4.9.74.p
6510
+	 * @return null|string
6511
+	 * @throws EE_Error
6512
+	 * @throws InvalidArgumentException
6513
+	 * @throws InvalidDataTypeException
6514
+	 * @throws InvalidInterfaceException
6515
+	 * @throws ModelConfigurationException
6516
+	 * @throws ReflectionException
6517
+	 */
6518
+	public function modelChainAndPassword()
6519
+	{
6520
+		if ($this->model_chain_to_password === null) {
6521
+			throw new ModelConfigurationException(
6522
+				$this,
6523
+				esc_html_x(
6524
+				// @codingStandardsIgnoreStart
6525
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6526
+					// @codingStandardsIgnoreEnd
6527
+					'1: model name',
6528
+					'event_espresso'
6529
+				)
6530
+			);
6531
+		}
6532
+		if ($this->model_chain_to_password === '') {
6533
+			$model_with_password = $this;
6534
+		} else {
6535
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6536
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6537
+			} else {
6538
+				$last_model_in_chain = $this->model_chain_to_password;
6539
+			}
6540
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6541
+		}
6542
+
6543
+		$password_field = $model_with_password->getPasswordField();
6544
+		if ($password_field instanceof EE_Password_Field) {
6545
+			$password_field_name = $password_field->get_name();
6546
+		} else {
6547
+			throw new ModelConfigurationException(
6548
+				$this,
6549
+				sprintf(
6550
+					esc_html_x(
6551
+						'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"',
6552
+						'1: model name, 2: special string',
6553
+						'event_espresso'
6554
+					),
6555
+					$model_with_password->get_this_model_name(),
6556
+					$this->model_chain_to_password
6557
+				)
6558
+			);
6559
+		}
6560
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6561
+	}
6562
+
6563
+	/**
6564
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6565
+	 * or if this model itself has a password affecting access to some of its other fields.
6566
+	 * @since 4.9.74.p
6567
+	 * @return boolean
6568
+	 */
6569
+	public function restrictedByRelatedModelPassword()
6570
+	{
6571
+		return $this->model_chain_to_password !== null;
6572
+	}
6573 6573
 }
Please login to merge, or discard this patch.
Spacing   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
     protected function __construct($timezone = null)
566 566
     {
567 567
         // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
569 569
             throw new EE_Error(
570 570
                 sprintf(
571 571
                     __(
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
          *
589 589
          * @var EE_Table_Base[] $_tables
590 590
          */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
592 592
         foreach ($this->_tables as $table_alias => $table_obj) {
593 593
             /** @var $table_obj EE_Table_Base */
594 594
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -603,10 +603,10 @@  discard block
 block discarded – undo
603 603
          *
604 604
          * @param EE_Model_Field_Base[] $_fields
605 605
          */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
607 607
         $this->_invalidate_field_caches();
608 608
         foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
610 610
                 throw new EE_Error(sprintf(__(
611 611
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612 612
                     'event_espresso'
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
          * @param EE_Model_Relation_Base[] $_model_relations
638 638
          */
639 639
         $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
640
+            'FHEE__'.get_class($this).'__construct__model_relations',
641 641
             $this->_model_relations
642 642
         );
643 643
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -649,12 +649,12 @@  discard block
 block discarded – undo
649 649
         }
650 650
         $this->set_timezone($timezone);
651 651
         // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
652
+        if ( ! $this->_default_where_conditions_strategy) {
653 653
             // nothing was set during child constructor, so set default
654 654
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655 655
         }
656 656
         $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
657
+        if ( ! $this->_minimum_where_conditions_strategy) {
658 658
             // nothing was set during child constructor, so set default
659 659
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660 660
         }
@@ -667,8 +667,8 @@  discard block
 block discarded – undo
667 667
         // initialize the standard cap restriction generators if none were specified by the child constructor
668 668
         if (is_array($this->_cap_restriction_generators)) {
669 669
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
670
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
671
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
672 672
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673 673
                         new EE_Restriction_Generator_Protected(),
674 674
                         $cap_context,
@@ -680,10 +680,10 @@  discard block
 block discarded – undo
680 680
         // if there are cap restriction generators, use them to make the default cap restrictions
681 681
         if (is_array($this->_cap_restriction_generators)) {
682 682
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
683
+                if ( ! $generator_object) {
684 684
                     continue;
685 685
                 }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
686
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
687 687
                     throw new EE_Error(
688 688
                         sprintf(
689 689
                             __(
@@ -696,12 +696,12 @@  discard block
 block discarded – undo
696 696
                     );
697 697
                 }
698 698
                 $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
699
+                if ( ! $generator_object->construction_finalized()) {
700 700
                     $generator_object->_construct_finalize($this, $action);
701 701
                 }
702 702
             }
703 703
         }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
704
+        do_action('AHEE__'.get_class($this).'__construct__end');
705 705
     }
706 706
 
707 707
 
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
      */
714 714
     protected static function getLoader(): LoaderInterface
715 715
     {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
716
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
717 717
             EEM_Base::$loader = LoaderFactory::getLoader();
718 718
         }
719 719
         return EEM_Base::$loader;
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
      */
727 727
     private static function getMirror(): Mirror
728 728
     {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
729
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
730 730
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731 731
         }
732 732
         return EEM_Base::$mirror;
@@ -782,14 +782,14 @@  discard block
 block discarded – undo
782 782
     public static function instance($timezone = null)
783 783
     {
784 784
         // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
785
+        if ( ! static::$_instance instanceof static) {
786 786
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787 787
             $model = new static(...$arguments);
788 788
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
789 789
             static::$_instance = $model;
790 790
         }
791 791
         // we might have a timezone set, let set_timezone decide what to do with it
792
-        if ($timezone){
792
+        if ($timezone) {
793 793
             static::$_instance->set_timezone($timezone);
794 794
         }
795 795
         // Espresso_model object
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
      */
813 813
     public static function reset($timezone = null)
814 814
     {
815
-        if (! static::$_instance instanceof EEM_Base) {
815
+        if ( ! static::$_instance instanceof EEM_Base) {
816 816
             return null;
817 817
         }
818 818
         // Let's NOT swap out the current instance for a new one
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824 824
             // don't set instance to null like it was originally,
825 825
             // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
826
+            if ( ! isset($static_properties[$property])) {
827 827
                 static::$_instance->{$property} = $value;
828 828
             }
829 829
         }
@@ -872,7 +872,7 @@  discard block
 block discarded – undo
872 872
      */
873 873
     public function status_array($translated = false)
874 874
     {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
875
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
876 876
             return array();
877 877
         }
878 878
         $model_name = $this->get_this_model_name();
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881 881
         $status_array = array();
882 882
         foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
883
+            $status_array[$status->ID()] = $status->get('STS_code');
884 884
         }
885 885
         return $translated
886 886
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -941,7 +941,7 @@  discard block
 block discarded – undo
941 941
     {
942 942
         $wp_user_field_name = $this->wp_user_field_name();
943 943
         if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
944
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
945 945
         }
946 946
         return $query_params;
947 947
     }
@@ -959,17 +959,17 @@  discard block
 block discarded – undo
959 959
     public function wp_user_field_name()
960 960
     {
961 961
         try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
962
+            if ( ! empty($this->_model_chain_to_wp_user)) {
963 963
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964 964
                 $last_model_name = end($models_to_follow_to_wp_users);
965 965
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
966
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
967 967
             } else {
968 968
                 $model_with_fk_to_wp_users = $this;
969 969
                 $model_chain_to_wp_user = '';
970 970
             }
971 971
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
972
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
973 973
         } catch (EE_Error $e) {
974 974
             return false;
975 975
         }
@@ -1046,11 +1046,11 @@  discard block
 block discarded – undo
1046 1046
         if ($this->_custom_selections instanceof CustomSelects) {
1047 1047
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048 1048
             $select_expressions .= $select_expressions
1049
-                ? ', ' . $custom_expressions
1049
+                ? ', '.$custom_expressions
1050 1050
                 : $custom_expressions;
1051 1051
         }
1052 1052
 
1053
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1053
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1054 1054
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055 1055
     }
1056 1056
 
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      */
1068 1068
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069 1069
     {
1070
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1070
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071 1071
             return null;
1072 1072
         }
1073 1073
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1116,7 +1116,7 @@  discard block
 block discarded – undo
1116 1116
         if (is_array($columns_to_select)) {
1117 1117
             $select_sql_array = array();
1118 1118
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120 1120
                     throw new EE_Error(
1121 1121
                         sprintf(
1122 1122
                             __(
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
                         )
1129 1129
                     );
1130 1130
                 }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132 1132
                     throw new EE_Error(
1133 1133
                         sprintf(
1134 1134
                             esc_html__(
@@ -1207,12 +1207,12 @@  discard block
 block discarded – undo
1207 1207
      */
1208 1208
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209 1209
     {
1210
-        if (! isset($query_params[0])) {
1210
+        if ( ! isset($query_params[0])) {
1211 1211
             $query_params[0] = array();
1212 1212
         }
1213 1213
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1214 1214
         if ($conditions_from_id === null) {
1215
-            $query_params[0][ $this->primary_key_name() ] = $id;
1215
+            $query_params[0][$this->primary_key_name()] = $id;
1216 1216
         } else {
1217 1217
             // no primary key, so the $id must be from the get_index_primary_key_string()
1218 1218
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
      */
1233 1233
     public function get_one($query_params = array())
1234 1234
     {
1235
-        if (! is_array($query_params)) {
1235
+        if ( ! is_array($query_params)) {
1236 1236
             EE_Error::doing_it_wrong(
1237 1237
                 'EEM_Base::get_one',
1238 1238
                 sprintf(
@@ -1430,7 +1430,7 @@  discard block
 block discarded – undo
1430 1430
                 return array();
1431 1431
             }
1432 1432
         }
1433
-        if (! is_array($query_params)) {
1433
+        if ( ! is_array($query_params)) {
1434 1434
             EE_Error::doing_it_wrong(
1435 1435
                 'EEM_Base::_get_consecutive',
1436 1436
                 sprintf(
@@ -1442,7 +1442,7 @@  discard block
 block discarded – undo
1442 1442
             $query_params = array();
1443 1443
         }
1444 1444
         // let's add the where query param for consecutive look up.
1445
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1445
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1446 1446
         $query_params['limit'] = $limit;
1447 1447
         // set direction
1448 1448
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1523,7 +1523,7 @@  discard block
 block discarded – undo
1523 1523
     {
1524 1524
         $field_settings = $this->field_settings_for($field_name);
1525 1525
         // if not a valid EE_Datetime_Field then throw error
1526
-        if (! $field_settings instanceof EE_Datetime_Field) {
1526
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1527 1527
             throw new EE_Error(sprintf(__(
1528 1528
                 '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.',
1529 1529
                 'event_espresso'
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
      */
1673 1673
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674 1674
     {
1675
-        if (! is_array($query_params)) {
1675
+        if ( ! is_array($query_params)) {
1676 1676
             EE_Error::doing_it_wrong(
1677 1677
                 'EEM_Base::update',
1678 1678
                 sprintf(
@@ -1720,7 +1720,7 @@  discard block
 block discarded – undo
1720 1720
             $wpdb_result = (array) $wpdb_result;
1721 1721
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722 1722
             if ($this->has_primary_key_field()) {
1723
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1724 1724
             } else {
1725 1725
                 // 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)
1726 1726
                 $main_table_pk_value = null;
@@ -1736,7 +1736,7 @@  discard block
 block discarded – undo
1736 1736
                     // in this table, right? so insert a row in the current table, using any fields available
1737 1737
                     if (
1738 1738
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
-                           && $wpdb_result[ $this_table_pk_column ])
1739
+                           && $wpdb_result[$this_table_pk_column])
1740 1740
                     ) {
1741 1741
                         $success = $this->_insert_into_specific_table(
1742 1742
                             $table_obj,
@@ -1744,7 +1744,7 @@  discard block
 block discarded – undo
1744 1744
                             $main_table_pk_value
1745 1745
                         );
1746 1746
                         // if we died here, report the error
1747
-                        if (! $success) {
1747
+                        if ( ! $success) {
1748 1748
                             return false;
1749 1749
                         }
1750 1750
                     }
@@ -1772,10 +1772,10 @@  discard block
 block discarded – undo
1772 1772
                 $model_objs_affected_ids = array();
1773 1773
                 foreach ($models_affected_key_columns as $row) {
1774 1774
                     $combined_index_key = $this->get_index_primary_key_string($row);
1775
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1776 1776
                 }
1777 1777
             }
1778
-            if (! $model_objs_affected_ids) {
1778
+            if ( ! $model_objs_affected_ids) {
1779 1779
                 // wait wait wait- if nothing was affected let's stop here
1780 1780
                 return 0;
1781 1781
             }
@@ -1802,7 +1802,7 @@  discard block
 block discarded – undo
1802 1802
                . $model_query_info->get_full_join_sql()
1803 1803
                . " SET "
1804 1804
                . $this->_construct_update_sql($fields_n_values)
1805
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806 1806
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807 1807
         /**
1808 1808
          * Action called after a model update call has been made.
@@ -1813,7 +1813,7 @@  discard block
 block discarded – undo
1813 1813
          * @param int      $rows_affected
1814 1814
          */
1815 1815
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
-        return $rows_affected;// how many supposedly got updated
1816
+        return $rows_affected; // how many supposedly got updated
1817 1817
     }
1818 1818
 
1819 1819
 
@@ -1841,7 +1841,7 @@  discard block
 block discarded – undo
1841 1841
         }
1842 1842
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1843 1843
         $select_expressions = $field->get_qualified_column();
1844
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1844
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1845 1845
         return $this->_do_wpdb_query('get_col', array($SQL));
1846 1846
     }
1847 1847
 
@@ -1859,7 +1859,7 @@  discard block
 block discarded – undo
1859 1859
     {
1860 1860
         $query_params['limit'] = 1;
1861 1861
         $col = $this->get_col($query_params, $field_to_select);
1862
-        if (! empty($col)) {
1862
+        if ( ! empty($col)) {
1863 1863
             return reset($col);
1864 1864
         }
1865 1865
         return null;
@@ -1890,7 +1890,7 @@  discard block
 block discarded – undo
1890 1890
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891 1891
             $value_sql = $prepared_value === null ? 'NULL'
1892 1892
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1893
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1894 1894
         }
1895 1895
         return implode(",", $cols_n_values);
1896 1896
     }
@@ -2034,12 +2034,12 @@  discard block
 block discarded – undo
2034 2034
         if (
2035 2035
             $this->has_primary_key_field()
2036 2036
             && $rows_deleted !== false
2037
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2037
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2038 2038
         ) {
2039
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2039
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2040 2040
             foreach ($ids_for_removal as $id) {
2041
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2041
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2042
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2043 2043
                 }
2044 2044
             }
2045 2045
 
@@ -2076,7 +2076,7 @@  discard block
 block discarded – undo
2076 2076
          * @param int      $rows_deleted
2077 2077
          */
2078 2078
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
-        return $rows_deleted;// how many supposedly got deleted
2079
+        return $rows_deleted; // how many supposedly got deleted
2080 2080
     }
2081 2081
 
2082 2082
 
@@ -2170,15 +2170,15 @@  discard block
 block discarded – undo
2170 2170
                 if (
2171 2171
                     $allow_blocking
2172 2172
                     && $this->delete_is_blocked_by_related_models(
2173
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2174 2174
                     )
2175 2175
                 ) {
2176 2176
                     continue;
2177 2177
                 }
2178 2178
                 // primary table deletes
2179
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2179
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2180
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2181
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2182 2182
                 }
2183 2183
             }
2184 2184
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2187,8 +2187,8 @@  discard block
 block discarded – undo
2187 2187
                 $ids_to_delete_indexed_by_column_for_row = array();
2188 2188
                 foreach ($fields as $cpk_field) {
2189 2189
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2190
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2190
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2191
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2192 2192
                     }
2193 2193
                 }
2194 2194
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2228,7 +2228,7 @@  discard block
 block discarded – undo
2228 2228
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229 2229
                 // make sure we have unique $ids
2230 2230
                 $ids = array_unique($ids);
2231
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2231
+                $query[] = $column.' IN('.implode(',', $ids).')';
2232 2232
             }
2233 2233
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234 2234
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2236,7 +2236,7 @@  discard block
 block discarded – undo
2236 2236
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237 2237
                 $values_for_each_combined_primary_key_for_a_row = array();
2238 2238
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2239
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2240 2240
                 }
2241 2241
                 $ways_to_identify_a_row[] = '('
2242 2242
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2308,8 +2308,8 @@  discard block
 block discarded – undo
2308 2308
                 $column_to_count = '*';
2309 2309
             }
2310 2310
         }
2311
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2311
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2312
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2313 2313
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314 2314
     }
2315 2315
 
@@ -2332,7 +2332,7 @@  discard block
 block discarded – undo
2332 2332
             $field_obj = $this->get_primary_key_field();
2333 2333
         }
2334 2334
         $column_to_count = $field_obj->get_qualified_column();
2335
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2335
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2336 2336
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337 2337
         $data_type = $field_obj->get_wpdb_data_type();
2338 2338
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2359,7 +2359,7 @@  discard block
 block discarded – undo
2359 2359
         // if we're in maintenance mode level 2, DON'T run any queries
2360 2360
         // because level 2 indicates the database needs updating and
2361 2361
         // is probably out of sync with the code
2362
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2362
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2363 2363
             throw new EE_Error(sprintf(__(
2364 2364
                 "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.",
2365 2365
                 "event_espresso"
@@ -2367,7 +2367,7 @@  discard block
 block discarded – undo
2367 2367
         }
2368 2368
         /** @type WPDB $wpdb */
2369 2369
         global $wpdb;
2370
-        if (! method_exists($wpdb, $wpdb_method)) {
2370
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2371 2371
             throw new EE_Error(sprintf(__(
2372 2372
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2373 2373
                 'event_espresso'
@@ -2381,7 +2381,7 @@  discard block
 block discarded – undo
2381 2381
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2382 2382
         if (WP_DEBUG) {
2383 2383
             $wpdb->show_errors($old_show_errors_value);
2384
-            if (! empty($wpdb->last_error)) {
2384
+            if ( ! empty($wpdb->last_error)) {
2385 2385
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386 2386
             }
2387 2387
             if ($result === false) {
@@ -2447,7 +2447,7 @@  discard block
 block discarded – undo
2447 2447
                     return $result;
2448 2448
                     break;
2449 2449
             }
2450
-            if (! empty($error_message)) {
2450
+            if ( ! empty($error_message)) {
2451 2451
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452 2452
                 trigger_error($error_message);
2453 2453
             }
@@ -2527,11 +2527,11 @@  discard block
 block discarded – undo
2527 2527
      */
2528 2528
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529 2529
     {
2530
-        return " FROM " . $model_query_info->get_full_join_sql() .
2531
-               $model_query_info->get_where_sql() .
2532
-               $model_query_info->get_group_by_sql() .
2533
-               $model_query_info->get_having_sql() .
2534
-               $model_query_info->get_order_by_sql() .
2530
+        return " FROM ".$model_query_info->get_full_join_sql().
2531
+               $model_query_info->get_where_sql().
2532
+               $model_query_info->get_group_by_sql().
2533
+               $model_query_info->get_having_sql().
2534
+               $model_query_info->get_order_by_sql().
2535 2535
                $model_query_info->get_limit_sql();
2536 2536
     }
2537 2537
 
@@ -2727,12 +2727,12 @@  discard block
 block discarded – undo
2727 2727
         $related_model = $this->get_related_model_obj($model_name);
2728 2728
         // we're just going to use the query params on the related model's normal get_all query,
2729 2729
         // except add a condition to say to match the current mod
2730
-        if (! isset($query_params['default_where_conditions'])) {
2730
+        if ( ! isset($query_params['default_where_conditions'])) {
2731 2731
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732 2732
         }
2733 2733
         $this_model_name = $this->get_this_model_name();
2734 2734
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2735
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2736 2736
         return $related_model->count($query_params, $field_to_count, $distinct);
2737 2737
     }
2738 2738
 
@@ -2752,7 +2752,7 @@  discard block
 block discarded – undo
2752 2752
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753 2753
     {
2754 2754
         $related_model = $this->get_related_model_obj($model_name);
2755
-        if (! is_array($query_params)) {
2755
+        if ( ! is_array($query_params)) {
2756 2756
             EE_Error::doing_it_wrong(
2757 2757
                 'EEM_Base::sum_related',
2758 2758
                 sprintf(
@@ -2765,12 +2765,12 @@  discard block
 block discarded – undo
2765 2765
         }
2766 2766
         // we're just going to use the query params on the related model's normal get_all query,
2767 2767
         // except add a condition to say to match the current mod
2768
-        if (! isset($query_params['default_where_conditions'])) {
2768
+        if ( ! isset($query_params['default_where_conditions'])) {
2769 2769
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770 2770
         }
2771 2771
         $this_model_name = $this->get_this_model_name();
2772 2772
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2773
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2774 2774
         return $related_model->sum($query_params, $field_to_sum);
2775 2775
     }
2776 2776
 
@@ -2823,7 +2823,7 @@  discard block
 block discarded – undo
2823 2823
                 $field_with_model_name = $field;
2824 2824
             }
2825 2825
         }
2826
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2826
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2827 2827
             throw new EE_Error(sprintf(
2828 2828
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829 2829
                 $this->get_this_model_name()
@@ -2960,13 +2960,13 @@  discard block
 block discarded – undo
2960 2960
                 || $this->get_primary_key_field()
2961 2961
                    instanceof
2962 2962
                    EE_Primary_Key_String_Field)
2963
-            && isset($fields_n_values[ $this->primary_key_name() ])
2963
+            && isset($fields_n_values[$this->primary_key_name()])
2964 2964
         ) {
2965
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2965
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2966 2966
         }
2967 2967
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968 2968
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2969
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2970 2970
         }
2971 2971
         // if there is nothing to base this search on, then we shouldn't find anything
2972 2972
         if (empty($query_params)) {
@@ -3044,15 +3044,15 @@  discard block
 block discarded – undo
3044 3044
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045 3045
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3046 3046
             if ($prepared_value !== null) {
3047
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3047
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3048 3048
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049 3049
             }
3050 3050
         }
3051 3051
         if ($table instanceof EE_Secondary_Table && $new_id) {
3052 3052
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3053 3053
             // so add the fk to the main table as a column
3054
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3054
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3055
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3056 3056
         }
3057 3057
         // insert the new entry
3058 3058
         $result = $this->_do_wpdb_query(
@@ -3069,7 +3069,7 @@  discard block
 block discarded – undo
3069 3069
             }
3070 3070
             // it's not an auto-increment primary key, so
3071 3071
             // it must have been supplied
3072
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3072
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3073 3073
         }
3074 3074
         // we can't return a  primary key because there is none. instead return
3075 3075
         // a unique string indicating this model
@@ -3094,14 +3094,14 @@  discard block
 block discarded – undo
3094 3094
         if (
3095 3095
             ! $field_obj->is_nullable()
3096 3096
             && (
3097
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3098
-                || $fields_n_values[ $field_obj->get_name() ] === null
3097
+                ! isset($fields_n_values[$field_obj->get_name()])
3098
+                || $fields_n_values[$field_obj->get_name()] === null
3099 3099
             )
3100 3100
         ) {
3101
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3101
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3102 3102
         }
3103
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
-            ? $fields_n_values[ $field_obj->get_name() ]
3103
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3104
+            ? $fields_n_values[$field_obj->get_name()]
3105 3105
             : null;
3106 3106
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107 3107
     }
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
      */
3203 3203
     public function get_table_obj_by_alias($table_alias = '')
3204 3204
     {
3205
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3205
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3206 3206
     }
3207 3207
 
3208 3208
 
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
         $other_tables = array();
3218 3218
         foreach ($this->_tables as $table_alias => $table) {
3219 3219
             if ($table instanceof EE_Secondary_Table) {
3220
-                $other_tables[ $table_alias ] = $table;
3220
+                $other_tables[$table_alias] = $table;
3221 3221
             }
3222 3222
         }
3223 3223
         return $other_tables;
@@ -3233,7 +3233,7 @@  discard block
 block discarded – undo
3233 3233
      */
3234 3234
     public function _get_fields_for_table($table_alias)
3235 3235
     {
3236
-        return $this->_fields[ $table_alias ];
3236
+        return $this->_fields[$table_alias];
3237 3237
     }
3238 3238
 
3239 3239
 
@@ -3262,7 +3262,7 @@  discard block
 block discarded – undo
3262 3262
                     $query_info_carrier,
3263 3263
                     'group_by'
3264 3264
                 );
3265
-            } elseif (! empty($query_params['group_by'])) {
3265
+            } elseif ( ! empty($query_params['group_by'])) {
3266 3266
                 $this->_extract_related_model_info_from_query_param(
3267 3267
                     $query_params['group_by'],
3268 3268
                     $query_info_carrier,
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                     $query_info_carrier,
3285 3285
                     'order_by'
3286 3286
                 );
3287
-            } elseif (! empty($query_params['order_by'])) {
3287
+            } elseif ( ! empty($query_params['order_by'])) {
3288 3288
                 $this->_extract_related_model_info_from_query_param(
3289 3289
                     $query_params['order_by'],
3290 3290
                     $query_info_carrier,
@@ -3319,7 +3319,7 @@  discard block
 block discarded – undo
3319 3319
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320 3320
         $query_param_type
3321 3321
     ) {
3322
-        if (! empty($sub_query_params)) {
3322
+        if ( ! empty($sub_query_params)) {
3323 3323
             $sub_query_params = (array) $sub_query_params;
3324 3324
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325 3325
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3334,7 +3334,7 @@  discard block
 block discarded – undo
3334 3334
                 // of array('Registration.TXN_ID'=>23)
3335 3335
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336 3336
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
-                    if (! is_array($possibly_array_of_params)) {
3337
+                    if ( ! is_array($possibly_array_of_params)) {
3338 3338
                         throw new EE_Error(sprintf(
3339 3339
                             __(
3340 3340
                                 "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'))",
@@ -3358,7 +3358,7 @@  discard block
 block discarded – undo
3358 3358
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359 3359
                     // indicating that $possible_array_of_params[1] is actually a field name,
3360 3360
                     // from which we should extract query parameters!
3361
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3361
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362 3362
                         throw new EE_Error(sprintf(__(
3363 3363
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364 3364
                             "event_espresso"
@@ -3392,8 +3392,8 @@  discard block
 block discarded – undo
3392 3392
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393 3393
         $query_param_type
3394 3394
     ) {
3395
-        if (! empty($sub_query_params)) {
3396
-            if (! is_array($sub_query_params)) {
3395
+        if ( ! empty($sub_query_params)) {
3396
+            if ( ! is_array($sub_query_params)) {
3397 3397
                 throw new EE_Error(sprintf(
3398 3398
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399 3399
                     $sub_query_params
@@ -3427,7 +3427,7 @@  discard block
 block discarded – undo
3427 3427
      */
3428 3428
     public function _create_model_query_info_carrier($query_params)
3429 3429
     {
3430
-        if (! is_array($query_params)) {
3430
+        if ( ! is_array($query_params)) {
3431 3431
             EE_Error::doing_it_wrong(
3432 3432
                 'EEM_Base::_create_model_query_info_carrier',
3433 3433
                 sprintf(
@@ -3460,7 +3460,7 @@  discard block
 block discarded – undo
3460 3460
             // only include if related to a cpt where no password has been set
3461 3461
             $query_params[0]['OR*nopassword'] = array(
3462 3462
                 $where_param_key_for_password => '',
3463
-                $where_param_key_for_password . '*' => array('IS_NULL')
3463
+                $where_param_key_for_password.'*' => array('IS_NULL')
3464 3464
             );
3465 3465
         }
3466 3466
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3514,7 +3514,7 @@  discard block
 block discarded – undo
3514 3514
         // set limit
3515 3515
         if (array_key_exists('limit', $query_params)) {
3516 3516
             if (is_array($query_params['limit'])) {
3517
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3517
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518 3518
                     $e = sprintf(
3519 3519
                         __(
3520 3520
                             "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)",
@@ -3522,12 +3522,12 @@  discard block
 block discarded – undo
3522 3522
                         ),
3523 3523
                         http_build_query($query_params['limit'])
3524 3524
                     );
3525
-                    throw new EE_Error($e . "|" . $e);
3525
+                    throw new EE_Error($e."|".$e);
3526 3526
                 }
3527 3527
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
-            } elseif (! empty($query_params['limit'])) {
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3529
+            } elseif ( ! empty($query_params['limit'])) {
3530
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3531 3531
             }
3532 3532
         }
3533 3533
         // set order by
@@ -3559,10 +3559,10 @@  discard block
 block discarded – undo
3559 3559
                 $order_array = array();
3560 3560
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561 3561
                     $order = $this->_extract_order($order);
3562
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3562
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3563 3563
                 }
3564
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
-            } elseif (! empty($query_params['order_by'])) {
3564
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3565
+            } elseif ( ! empty($query_params['order_by'])) {
3566 3566
                 $this->_extract_related_model_info_from_query_param(
3567 3567
                     $query_params['order_by'],
3568 3568
                     $query_object,
@@ -3573,7 +3573,7 @@  discard block
 block discarded – undo
3573 3573
                     ? $this->_extract_order($query_params['order'])
3574 3574
                     : 'DESC';
3575 3575
                 $query_object->set_order_by_sql(
3576
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3576
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3577 3577
                 );
3578 3578
             }
3579 3579
         }
@@ -3585,7 +3585,7 @@  discard block
 block discarded – undo
3585 3585
         ) {
3586 3586
             $pk_field = $this->get_primary_key_field();
3587 3587
             $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3588
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3589 3589
         }
3590 3590
         // set group by
3591 3591
         if (array_key_exists('group_by', $query_params)) {
@@ -3595,10 +3595,10 @@  discard block
 block discarded – undo
3595 3595
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596 3596
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597 3597
                 }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3598
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3599
+            } elseif ( ! empty($query_params['group_by'])) {
3600 3600
                 $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3601
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3602 3602
                 );
3603 3603
             }
3604 3604
         }
@@ -3608,7 +3608,7 @@  discard block
 block discarded – undo
3608 3608
         }
3609 3609
         // now, just verify they didn't pass anything wack
3610 3610
         foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3611
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3612 3612
                 throw new EE_Error(
3613 3613
                     sprintf(
3614 3614
                         __(
@@ -3716,7 +3716,7 @@  discard block
 block discarded – undo
3716 3716
         $where_query_params = array()
3717 3717
     ) {
3718 3718
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3719
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720 3720
             throw new EE_Error(sprintf(
3721 3721
                 __(
3722 3722
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3848,19 +3848,19 @@  discard block
 block discarded – undo
3848 3848
     ) {
3849 3849
         $null_friendly_where_conditions = array();
3850 3850
         $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3851
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3852 3852
         foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3853
+            if (isset($provided_where_conditions[$key])) {
3854 3854
                 $none_overridden = false;
3855 3855
             } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3857 3857
             }
3858 3858
         }
3859 3859
         if ($none_overridden && $default_where_conditions) {
3860 3860
             if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3862 3862
                                                                                 . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3863
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
@@ -3965,7 +3965,7 @@  discard block
 block discarded – undo
3965 3965
             foreach ($tables as $table_obj) {
3966 3966
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967 3967
                                        . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3968
+                if ( ! in_array($qualified_pk_column, $selects)) {
3969 3969
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970 3970
                 }
3971 3971
             }
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         $query_parameter_type
4118 4118
     ) {
4119 4119
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4120
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4121 4121
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4122
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4123 4123
                 if ($possible_join_string === '') {
4124 4124
                     // nothing left to $query_param
4125 4125
                     // we should actually end in a field name, not a model like this!
@@ -4250,7 +4250,7 @@  discard block
 block discarded – undo
4250 4250
     {
4251 4251
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252 4252
         if ($SQL) {
4253
-            return " WHERE " . $SQL;
4253
+            return " WHERE ".$SQL;
4254 4254
         }
4255 4255
         return '';
4256 4256
     }
@@ -4269,7 +4269,7 @@  discard block
 block discarded – undo
4269 4269
     {
4270 4270
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271 4271
         if ($SQL) {
4272
-            return " HAVING " . $SQL;
4272
+            return " HAVING ".$SQL;
4273 4273
         }
4274 4274
         return '';
4275 4275
     }
@@ -4288,7 +4288,7 @@  discard block
 block discarded – undo
4288 4288
     {
4289 4289
         $where_clauses = array();
4290 4290
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4291
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4292 4292
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4293 4293
                 switch ($query_param) {
4294 4294
                     case 'not':
@@ -4322,7 +4322,7 @@  discard block
 block discarded – undo
4322 4322
             } else {
4323 4323
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4324 4324
                 // if it's not a normal field, maybe it's a custom selection?
4325
-                if (! $field_obj) {
4325
+                if ( ! $field_obj) {
4326 4326
                     if ($this->_custom_selections instanceof CustomSelects) {
4327 4327
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328 4328
                     } else {
@@ -4333,7 +4333,7 @@  discard block
 block discarded – undo
4333 4333
                     }
4334 4334
                 }
4335 4335
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4336
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4337 4337
             }
4338 4338
         }
4339 4339
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4356,7 +4356,7 @@  discard block
 block discarded – undo
4356 4356
                 $field->get_model_name(),
4357 4357
                 $query_param
4358 4358
             );
4359
-            return $table_alias_prefix . $field->get_qualified_column();
4359
+            return $table_alias_prefix.$field->get_qualified_column();
4360 4360
         }
4361 4361
         if (
4362 4362
             $this->_custom_selections instanceof CustomSelects
@@ -4416,7 +4416,7 @@  discard block
 block discarded – undo
4416 4416
     {
4417 4417
         if (is_array($op_and_value)) {
4418 4418
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
-            if (! $operator) {
4419
+            if ( ! $operator) {
4420 4420
                 $php_array_like_string = array();
4421 4421
                 foreach ($op_and_value as $key => $value) {
4422 4422
                     $php_array_like_string[] = "$key=>$value";
@@ -4438,14 +4438,14 @@  discard block
 block discarded – undo
4438 4438
         }
4439 4439
         // check to see if the value is actually another field
4440 4440
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4441
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4442 4442
         }
4443 4443
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444 4444
             // in this case, the value should be an array, or at least a comma-separated list
4445 4445
             // it will need to handle a little differently
4446 4446
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4447 4447
             // note: $cleaned_value has already been run through $wpdb->prepare()
4448
-            return $operator . SP . $cleaned_value;
4448
+            return $operator.SP.$cleaned_value;
4449 4449
         }
4450 4450
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451 4451
             // the value should be an array with count of two.
@@ -4461,7 +4461,7 @@  discard block
 block discarded – undo
4461 4461
                 );
4462 4462
             }
4463 4463
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
-            return $operator . SP . $cleaned_value;
4464
+            return $operator.SP.$cleaned_value;
4465 4465
         }
4466 4466
         if (in_array($operator, $this->valid_null_style_operators())) {
4467 4467
             if ($value !== null) {
@@ -4481,10 +4481,10 @@  discard block
 block discarded – undo
4481 4481
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482 4482
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4483 4483
             // remove other junk. So just treat it as a string.
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4484
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4485 4485
         }
4486
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4486
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4488 4488
         }
4489 4489
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490 4490
             throw new EE_Error(
@@ -4498,7 +4498,7 @@  discard block
 block discarded – undo
4498 4498
                 )
4499 4499
             );
4500 4500
         }
4501
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4501
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502 4502
             throw new EE_Error(
4503 4503
                 sprintf(
4504 4504
                     __(
@@ -4538,7 +4538,7 @@  discard block
 block discarded – undo
4538 4538
         foreach ($values as $value) {
4539 4539
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540 4540
         }
4541
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4541
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4542 4542
     }
4543 4543
 
4544 4544
 
@@ -4579,7 +4579,7 @@  discard block
 block discarded – undo
4579 4579
                                 . $main_table->get_table_name()
4580 4580
                                 . " WHERE FALSE";
4581 4581
         }
4582
-        return "(" . implode(",", $cleaned_values) . ")";
4582
+        return "(".implode(",", $cleaned_values).")";
4583 4583
     }
4584 4584
 
4585 4585
 
@@ -4600,7 +4600,7 @@  discard block
 block discarded – undo
4600 4600
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4601 4601
             );
4602 4602
         } //$field_obj should really just be a data type
4603
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4603
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604 4604
             throw new EE_Error(
4605 4605
                 sprintf(
4606 4606
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4633,14 +4633,14 @@  discard block
 block discarded – undo
4633 4633
             ), $query_param_name));
4634 4634
         }
4635 4635
         $number_of_parts = count($query_param_parts);
4636
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4636
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4637 4637
         if ($number_of_parts === 1) {
4638 4638
             $field_name = $last_query_param_part;
4639 4639
             $model_obj = $this;
4640 4640
         } else {// $number_of_parts >= 2
4641 4641
             // the last part is the column name, and there are only 2parts. therefore...
4642 4642
             $field_name = $last_query_param_part;
4643
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4643
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4644 4644
         }
4645 4645
         try {
4646 4646
             return $model_obj->field_settings_for($field_name);
@@ -4662,7 +4662,7 @@  discard block
 block discarded – undo
4662 4662
     public function _get_qualified_column_for_field($field_name)
4663 4663
     {
4664 4664
         $all_fields = $this->field_settings();
4665
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4665
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4666 4666
         if ($field) {
4667 4667
             return $field->get_qualified_column();
4668 4668
         }
@@ -4733,10 +4733,10 @@  discard block
 block discarded – undo
4733 4733
      */
4734 4734
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735 4735
     {
4736
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4736
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4737 4737
         $qualified_columns = array();
4738 4738
         foreach ($this->field_settings() as $field_name => $field) {
4739
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4739
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4740 4740
         }
4741 4741
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742 4742
     }
@@ -4760,11 +4760,11 @@  discard block
 block discarded – undo
4760 4760
             if ($table_obj instanceof EE_Primary_Table) {
4761 4761
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4762 4762
                     ? $table_obj->get_select_join_limit($limit)
4763
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4763
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4764 4764
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4765 4765
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4766 4766
                     ? $table_obj->get_select_join_limit_join($limit)
4767
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4767
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4768 4768
             }
4769 4769
         }
4770 4770
         return $SQL;
@@ -4836,7 +4836,7 @@  discard block
 block discarded – undo
4836 4836
         foreach ($this->field_settings() as $field_obj) {
4837 4837
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838 4838
             /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4839
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4840 4840
         }
4841 4841
         return $data_types;
4842 4842
     }
@@ -4852,14 +4852,14 @@  discard block
 block discarded – undo
4852 4852
      */
4853 4853
     public function get_related_model_obj($model_name)
4854 4854
     {
4855
-        $model_classname = "EEM_" . $model_name;
4856
-        if (! class_exists($model_classname)) {
4855
+        $model_classname = "EEM_".$model_name;
4856
+        if ( ! class_exists($model_classname)) {
4857 4857
             throw new EE_Error(sprintf(__(
4858 4858
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859 4859
                 'event_espresso'
4860 4860
             ), $model_name, $model_classname));
4861 4861
         }
4862
-        return call_user_func($model_classname . "::instance");
4862
+        return call_user_func($model_classname."::instance");
4863 4863
     }
4864 4864
 
4865 4865
 
@@ -4888,7 +4888,7 @@  discard block
 block discarded – undo
4888 4888
         $belongs_to_relations = array();
4889 4889
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890 4890
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4891
+                $belongs_to_relations[$model_name] = $relation_obj;
4892 4892
             }
4893 4893
         }
4894 4894
         return $belongs_to_relations;
@@ -4906,7 +4906,7 @@  discard block
 block discarded – undo
4906 4906
     public function related_settings_for($relation_name)
4907 4907
     {
4908 4908
         $relatedModels = $this->relation_settings();
4909
-        if (! array_key_exists($relation_name, $relatedModels)) {
4909
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4910 4910
             throw new EE_Error(
4911 4911
                 sprintf(
4912 4912
                     __(
@@ -4919,7 +4919,7 @@  discard block
 block discarded – undo
4919 4919
                 )
4920 4920
             );
4921 4921
         }
4922
-        return $relatedModels[ $relation_name ];
4922
+        return $relatedModels[$relation_name];
4923 4923
     }
4924 4924
 
4925 4925
 
@@ -4936,14 +4936,14 @@  discard block
 block discarded – undo
4936 4936
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4937 4937
     {
4938 4938
         $fieldSettings = $this->field_settings($include_db_only_fields);
4939
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4939
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4940 4940
             throw new EE_Error(sprintf(
4941 4941
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4942 4942
                 $fieldName,
4943 4943
                 get_class($this)
4944 4944
             ));
4945 4945
         }
4946
-        return $fieldSettings[ $fieldName ];
4946
+        return $fieldSettings[$fieldName];
4947 4947
     }
4948 4948
 
4949 4949
 
@@ -4957,7 +4957,7 @@  discard block
 block discarded – undo
4957 4957
     public function has_field($fieldName)
4958 4958
     {
4959 4959
         $fieldSettings = $this->field_settings(true);
4960
-        if (isset($fieldSettings[ $fieldName ])) {
4960
+        if (isset($fieldSettings[$fieldName])) {
4961 4961
             return true;
4962 4962
         }
4963 4963
         return false;
@@ -4974,7 +4974,7 @@  discard block
 block discarded – undo
4974 4974
     public function has_relation($relation_name)
4975 4975
     {
4976 4976
         $relations = $this->relation_settings();
4977
-        if (isset($relations[ $relation_name ])) {
4977
+        if (isset($relations[$relation_name])) {
4978 4978
             return true;
4979 4979
         }
4980 4980
         return false;
@@ -5012,7 +5012,7 @@  discard block
 block discarded – undo
5012 5012
                     break;
5013 5013
                 }
5014 5014
             }
5015
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5015
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016 5016
                 throw new EE_Error(sprintf(
5017 5017
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
5018 5018
                     get_class($this)
@@ -5073,24 +5073,24 @@  discard block
 block discarded – undo
5073 5073
      */
5074 5074
     public function get_foreign_key_to($model_name)
5075 5075
     {
5076
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5076
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5077 5077
             foreach ($this->field_settings() as $field) {
5078 5078
                 if (
5079 5079
                     $field instanceof EE_Foreign_Key_Field_Base
5080 5080
                     && in_array($model_name, $field->get_model_names_pointed_to())
5081 5081
                 ) {
5082
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5082
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5083 5083
                     break;
5084 5084
                 }
5085 5085
             }
5086
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5086
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5087 5087
                 throw new EE_Error(sprintf(__(
5088 5088
                     "There is no foreign key field pointing to model %s on model %s",
5089 5089
                     'event_espresso'
5090 5090
                 ), $model_name, get_class($this)));
5091 5091
             }
5092 5092
         }
5093
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5093
+        return $this->_cache_foreign_key_to_fields[$model_name];
5094 5094
     }
5095 5095
 
5096 5096
 
@@ -5106,7 +5106,7 @@  discard block
 block discarded – undo
5106 5106
     public function get_table_for_alias($table_alias)
5107 5107
     {
5108 5108
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5109
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5110 5110
     }
5111 5111
 
5112 5112
 
@@ -5125,7 +5125,7 @@  discard block
 block discarded – undo
5125 5125
                 $this->_cached_fields = array();
5126 5126
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5127 5127
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5128
+                        $this->_cached_fields[$field_name] = $field_obj;
5129 5129
                     }
5130 5130
                 }
5131 5131
             }
@@ -5136,8 +5136,8 @@  discard block
 block discarded – undo
5136 5136
             foreach ($this->_fields as $fields_corresponding_to_table) {
5137 5137
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138 5138
                     /** @var $field_obj EE_Model_Field_Base */
5139
-                    if (! $field_obj->is_db_only_field()) {
5140
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5139
+                    if ( ! $field_obj->is_db_only_field()) {
5140
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5141 5141
                     }
5142 5142
                 }
5143 5143
             }
@@ -5178,12 +5178,12 @@  discard block
 block discarded – undo
5178 5178
                     $primary_key_field->get_qualified_column(),
5179 5179
                     $primary_key_field->get_table_column()
5180 5180
                 );
5181
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5181
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5182 5182
                     continue;
5183 5183
                 }
5184 5184
             }
5185 5185
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5186
-            if (! $classInstance) {
5186
+            if ( ! $classInstance) {
5187 5187
                 throw new EE_Error(
5188 5188
                     sprintf(
5189 5189
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5196,7 +5196,7 @@  discard block
 block discarded – undo
5196 5196
             $classInstance->set_timezone($this->_timezone);
5197 5197
             // make sure if there is any timezone setting present that we set the timezone for the object
5198 5198
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
-            $array_of_objects[ $key ] = $classInstance;
5199
+            $array_of_objects[$key] = $classInstance;
5200 5200
             // also, for all the relations of type BelongsTo, see if we can cache
5201 5201
             // those related models
5202 5202
             // (we could do this for other relations too, but if there are conditions
@@ -5240,9 +5240,9 @@  discard block
 block discarded – undo
5240 5240
         $results = array();
5241 5241
         if ($this->_custom_selections instanceof CustomSelects) {
5242 5242
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
-                if (isset($db_results_row[ $alias ])) {
5244
-                    $results[ $alias ] = $this->convertValueToDataType(
5245
-                        $db_results_row[ $alias ],
5243
+                if (isset($db_results_row[$alias])) {
5244
+                    $results[$alias] = $this->convertValueToDataType(
5245
+                        $db_results_row[$alias],
5246 5246
                         $this->_custom_selections->getDataTypeForAlias($alias)
5247 5247
                     );
5248 5248
                 }
@@ -5284,7 +5284,7 @@  discard block
 block discarded – undo
5284 5284
         $this_model_fields_and_values = array();
5285 5285
         // setup the row using default values;
5286 5286
         foreach ($this->field_settings() as $field_name => $field_obj) {
5287
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5287
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5288 5288
         }
5289 5289
         $className = $this->_get_class_name();
5290 5290
         $classInstance = EE_Registry::instance()
@@ -5302,20 +5302,20 @@  discard block
 block discarded – undo
5302 5302
      */
5303 5303
     public function instantiate_class_from_array_or_object($cols_n_values)
5304 5304
     {
5305
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5305
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5306 5306
             $cols_n_values = get_object_vars($cols_n_values);
5307 5307
         }
5308 5308
         $primary_key = null;
5309 5309
         // make sure the array only has keys that are fields/columns on this model
5310 5310
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5311
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5312
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5313 5313
         }
5314 5314
         $className = $this->_get_class_name();
5315 5315
         // check we actually found results that we can use to build our model object
5316 5316
         // if not, return null
5317 5317
         if ($this->has_primary_key_field()) {
5318
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5318
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5319 5319
                 return null;
5320 5320
             }
5321 5321
         } elseif ($this->unique_indexes()) {
@@ -5327,7 +5327,7 @@  discard block
 block discarded – undo
5327 5327
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328 5328
         if ($primary_key) {
5329 5329
             $classInstance = $this->get_from_entity_map($primary_key);
5330
-            if (! $classInstance) {
5330
+            if ( ! $classInstance) {
5331 5331
                 $classInstance = EE_Registry::instance()
5332 5332
                                             ->load_class(
5333 5333
                                                 $className,
@@ -5360,8 +5360,8 @@  discard block
 block discarded – undo
5360 5360
      */
5361 5361
     public function get_from_entity_map($id)
5362 5362
     {
5363
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5363
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5364
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5365 5365
     }
5366 5366
 
5367 5367
 
@@ -5384,7 +5384,7 @@  discard block
 block discarded – undo
5384 5384
     public function add_to_entity_map(EE_Base_Class $object)
5385 5385
     {
5386 5386
         $className = $this->_get_class_name();
5387
-        if (! $object instanceof $className) {
5387
+        if ( ! $object instanceof $className) {
5388 5388
             throw new EE_Error(sprintf(
5389 5389
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390 5390
                 is_object($object) ? get_class($object) : $object,
@@ -5392,7 +5392,7 @@  discard block
 block discarded – undo
5392 5392
             ));
5393 5393
         }
5394 5394
         /** @var $object EE_Base_Class */
5395
-        if (! $object->ID()) {
5395
+        if ( ! $object->ID()) {
5396 5396
             throw new EE_Error(sprintf(__(
5397 5397
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5398 5398
                 "event_espresso"
@@ -5403,7 +5403,7 @@  discard block
 block discarded – undo
5403 5403
         if ($classInstance) {
5404 5404
             return $classInstance;
5405 5405
         }
5406
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5406
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5407 5407
         return $object;
5408 5408
     }
5409 5409
 
@@ -5419,11 +5419,11 @@  discard block
 block discarded – undo
5419 5419
     public function clear_entity_map($id = null)
5420 5420
     {
5421 5421
         if (empty($id)) {
5422
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5422
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5423 5423
             return true;
5424 5424
         }
5425
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5425
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5426
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5427 5427
             return true;
5428 5428
         }
5429 5429
         return false;
@@ -5466,17 +5466,17 @@  discard block
 block discarded – undo
5466 5466
             // there is a primary key on this table and its not set. Use defaults for all its columns
5467 5467
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468 5468
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
-                    if (! $field_obj->is_db_only_field()) {
5469
+                    if ( ! $field_obj->is_db_only_field()) {
5470 5470
                         // prepare field as if its coming from db
5471 5471
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5472
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5473 5473
                     }
5474 5474
                 }
5475 5475
             } else {
5476 5476
                 // the table's rows existed. Use their values
5477 5477
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
-                    if (! $field_obj->is_db_only_field()) {
5479
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5478
+                    if ( ! $field_obj->is_db_only_field()) {
5479
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5480 5480
                             $cols_n_values,
5481 5481
                             $field_obj->get_qualified_column(),
5482 5482
                             $field_obj->get_table_column()
@@ -5503,17 +5503,17 @@  discard block
 block discarded – undo
5503 5503
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504 5504
         // does the field on the model relate to this column retrieved from the db?
5505 5505
         // or is it a db-only field? (not relating to the model)
5506
-        if (isset($cols_n_values[ $qualified_column ])) {
5507
-            $value = $cols_n_values[ $qualified_column ];
5508
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5509
-            $value = $cols_n_values[ $regular_column ];
5510
-        } elseif (! empty($this->foreign_key_aliases)) {
5506
+        if (isset($cols_n_values[$qualified_column])) {
5507
+            $value = $cols_n_values[$qualified_column];
5508
+        } elseif (isset($cols_n_values[$regular_column])) {
5509
+            $value = $cols_n_values[$regular_column];
5510
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5511 5511
             // no PK?  ok check if there is a foreign key alias set for this table
5512 5512
             // then check if that alias exists in the incoming data
5513 5513
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514 5514
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
-                    $value = $cols_n_values[ $FK_alias ];
5515
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5516
+                    $value = $cols_n_values[$FK_alias];
5517 5517
                     [$pk_class] = explode('.', $PK_column);
5518 5518
                     $pk_model_name = "EEM_{$pk_class}";
5519 5519
                     /** @var EEM_Base $pk_model */
@@ -5557,7 +5557,7 @@  discard block
 block discarded – undo
5557 5557
                     $obj_in_map->clear_cache($relation_name, null, true);
5558 5558
                 }
5559 5559
             }
5560
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5560
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5561 5561
             return $obj_in_map;
5562 5562
         }
5563 5563
         return $this->get_one_by_ID($id);
@@ -5610,7 +5610,7 @@  discard block
 block discarded – undo
5610 5610
      */
5611 5611
     private function _get_class_name()
5612 5612
     {
5613
-        return "EE_" . $this->get_this_model_name();
5613
+        return "EE_".$this->get_this_model_name();
5614 5614
     }
5615 5615
 
5616 5616
 
@@ -5658,7 +5658,7 @@  discard block
 block discarded – undo
5658 5658
     {
5659 5659
         $className = get_class($this);
5660 5660
         $tagName = "FHEE__{$className}__{$methodName}";
5661
-        if (! has_filter($tagName)) {
5661
+        if ( ! has_filter($tagName)) {
5662 5662
             throw new EE_Error(
5663 5663
                 sprintf(
5664 5664
                     __(
@@ -5831,7 +5831,7 @@  discard block
 block discarded – undo
5831 5831
         $unique_indexes = array();
5832 5832
         foreach ($this->_indexes as $name => $index) {
5833 5833
             if ($index instanceof EE_Unique_Index) {
5834
-                $unique_indexes [ $name ] = $index;
5834
+                $unique_indexes [$name] = $index;
5835 5835
             }
5836 5836
         }
5837 5837
         return $unique_indexes;
@@ -5898,7 +5898,7 @@  discard block
 block discarded – undo
5898 5898
         $key_vals_in_combined_pk = array();
5899 5899
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900 5900
         foreach ($key_fields as $key_field_name => $field_obj) {
5901
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5901
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5902 5902
                 return null;
5903 5903
             }
5904 5904
         }
@@ -5919,7 +5919,7 @@  discard block
 block discarded – undo
5919 5919
     {
5920 5920
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921 5921
         foreach ($keys_it_should_have as $key) {
5922
-            if (! isset($key_vals[ $key ])) {
5922
+            if ( ! isset($key_vals[$key])) {
5923 5923
                 return false;
5924 5924
             }
5925 5925
         }
@@ -5952,8 +5952,8 @@  discard block
 block discarded – undo
5952 5952
         }
5953 5953
         // even copies obviously won't have the same ID, so remove the primary key
5954 5954
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5955
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5956
+            unset($attributes_array[$this->primary_key_name()]);
5957 5957
         }
5958 5958
         if (isset($query_params[0])) {
5959 5959
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5975,7 +5975,7 @@  discard block
 block discarded – undo
5975 5975
      */
5976 5976
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977 5977
     {
5978
-        if (! is_array($query_params)) {
5978
+        if ( ! is_array($query_params)) {
5979 5979
             EE_Error::doing_it_wrong(
5980 5980
                 'EEM_Base::get_one_copy',
5981 5981
                 sprintf(
@@ -6025,7 +6025,7 @@  discard block
 block discarded – undo
6025 6025
      */
6026 6026
     private function _prepare_operator_for_sql($operator_supplied)
6027 6027
     {
6028
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6029 6029
             : null;
6030 6030
         if ($sql_operator) {
6031 6031
             return $sql_operator;
@@ -6116,7 +6116,7 @@  discard block
 block discarded – undo
6116 6116
         $objs = $this->get_all($query_params);
6117 6117
         $names = array();
6118 6118
         foreach ($objs as $obj) {
6119
-            $names[ $obj->ID() ] = $obj->name();
6119
+            $names[$obj->ID()] = $obj->name();
6120 6120
         }
6121 6121
         return $names;
6122 6122
     }
@@ -6137,7 +6137,7 @@  discard block
 block discarded – undo
6137 6137
      */
6138 6138
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139 6139
     {
6140
-        if (! $this->has_primary_key_field()) {
6140
+        if ( ! $this->has_primary_key_field()) {
6141 6141
             if (WP_DEBUG) {
6142 6142
                 EE_Error::add_error(
6143 6143
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6150,7 +6150,7 @@  discard block
 block discarded – undo
6150 6150
         $IDs = array();
6151 6151
         foreach ($model_objects as $model_object) {
6152 6152
             $id = $model_object->ID();
6153
-            if (! $id) {
6153
+            if ( ! $id) {
6154 6154
                 if ($filter_out_empty_ids) {
6155 6155
                     continue;
6156 6156
                 }
@@ -6201,22 +6201,22 @@  discard block
 block discarded – undo
6201 6201
         EEM_Base::verify_is_valid_cap_context($context);
6202 6202
         // check if we ought to run the restriction generator first
6203 6203
         if (
6204
-            isset($this->_cap_restriction_generators[ $context ])
6205
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6204
+            isset($this->_cap_restriction_generators[$context])
6205
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6206
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6207 6207
         ) {
6208
-            $this->_cap_restrictions[ $context ] = array_merge(
6209
-                $this->_cap_restrictions[ $context ],
6210
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6208
+            $this->_cap_restrictions[$context] = array_merge(
6209
+                $this->_cap_restrictions[$context],
6210
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6211 6211
             );
6212 6212
         }
6213 6213
         // and make sure we've finalized the construction of each restriction
6214
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6214
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6215 6215
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216 6216
                 $where_conditions_obj->_finalize_construct($this);
6217 6217
             }
6218 6218
         }
6219
-        return $this->_cap_restrictions[ $context ];
6219
+        return $this->_cap_restrictions[$context];
6220 6220
     }
6221 6221
 
6222 6222
 
@@ -6248,9 +6248,9 @@  discard block
 block discarded – undo
6248 6248
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249 6249
             if (
6250 6250
                 ! EE_Capabilities::instance()
6251
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6251
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6252 6252
             ) {
6253
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6253
+                $missing_caps[$cap] = $restriction_if_no_cap;
6254 6254
             }
6255 6255
         }
6256 6256
         return $missing_caps;
@@ -6285,8 +6285,8 @@  discard block
 block discarded – undo
6285 6285
     public function cap_action_for_context($context)
6286 6286
     {
6287 6287
         $mapping = $this->cap_contexts_to_cap_action_map();
6288
-        if (isset($mapping[ $context ])) {
6289
-            return $mapping[ $context ];
6288
+        if (isset($mapping[$context])) {
6289
+            return $mapping[$context];
6290 6290
         }
6291 6291
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292 6292
             return $action;
@@ -6404,7 +6404,7 @@  discard block
 block discarded – undo
6404 6404
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405 6405
             if (
6406 6406
                 $query_param_key === $logic_query_param_key
6407
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6407
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6408 6408
             ) {
6409 6409
                 return true;
6410 6410
             }
@@ -6457,7 +6457,7 @@  discard block
 block discarded – undo
6457 6457
         if ($password_field instanceof EE_Password_Field) {
6458 6458
             $field_names = $password_field->protectedFields();
6459 6459
             foreach ($field_names as $field_name) {
6460
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6460
+                $fields[$field_name] = $this->field_settings_for($field_name);
6461 6461
             }
6462 6462
         }
6463 6463
         return $fields;
@@ -6482,7 +6482,7 @@  discard block
 block discarded – undo
6482 6482
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483 6483
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484 6484
         }
6485
-        if (!is_array($model_obj_or_fields_n_values)) {
6485
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6486 6486
             throw new UnexpectedEntityException(
6487 6487
                 $model_obj_or_fields_n_values,
6488 6488
                 'EE_Base_Class',
@@ -6557,7 +6557,7 @@  discard block
 block discarded – undo
6557 6557
                 )
6558 6558
             );
6559 6559
         }
6560
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6560
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6561 6561
     }
6562 6562
 
6563 6563
     /**
Please login to merge, or discard this patch.