Completed
Branch master (44537d)
by
unknown
14:30 queued 10:03
created
core/db_models/relations/EE_Belongs_To_Any_Relation.php 2 patches
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -14,106 +14,106 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Belongs_To_Any_Relation extends EE_Belongs_To_Relation
16 16
 {
17
-    /**
18
-     * get_join_statement
19
-     *
20
-     * @param string $model_relation_chain
21
-     * @return string
22
-     * @throws EE_Error
23
-     * @throws Exception
24
-     */
25
-    public function get_join_statement(string $model_relation_chain): string
26
-    {
27
-        // create the sql string like
28
-        $this_table_fk_field =
29
-            $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
30
-        // ALSO, need to get the field with the model name
31
-        $field_with_model_name = $this->get_this_model()->get_field_containing_related_model_name();
17
+	/**
18
+	 * get_join_statement
19
+	 *
20
+	 * @param string $model_relation_chain
21
+	 * @return string
22
+	 * @throws EE_Error
23
+	 * @throws Exception
24
+	 */
25
+	public function get_join_statement(string $model_relation_chain): string
26
+	{
27
+		// create the sql string like
28
+		$this_table_fk_field =
29
+			$this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
30
+		// ALSO, need to get the field with the model name
31
+		$field_with_model_name = $this->get_this_model()->get_field_containing_related_model_name();
32 32
 
33 33
 
34
-        $other_table_pk_field = $this->get_other_model()->get_primary_key_field();
35
-        $this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
36
-                $model_relation_chain,
37
-                $this->get_this_model()->get_this_model_name()
38
-            ) . $this_table_fk_field->get_table_alias();
39
-        $other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
40
-                $model_relation_chain,
41
-                $this->get_other_model()->get_this_model_name()
42
-            ) . $other_table_pk_field->get_table_alias();
43
-        $other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
44
-        return $this->_left_join(
45
-                $other_table,
46
-                $other_table_alias,
47
-                $other_table_pk_field->get_table_column(),
48
-                $this_table_alias,
49
-                $this_table_fk_field->get_table_column(),
50
-                $field_with_model_name->get_qualified_column() . "='" . $this->get_other_model()->get_this_model_name(
51
-                ) . "'"
52
-            )
53
-               . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
54
-    }
34
+		$other_table_pk_field = $this->get_other_model()->get_primary_key_field();
35
+		$this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
36
+				$model_relation_chain,
37
+				$this->get_this_model()->get_this_model_name()
38
+			) . $this_table_fk_field->get_table_alias();
39
+		$other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
40
+				$model_relation_chain,
41
+				$this->get_other_model()->get_this_model_name()
42
+			) . $other_table_pk_field->get_table_alias();
43
+		$other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
44
+		return $this->_left_join(
45
+				$other_table,
46
+				$other_table_alias,
47
+				$other_table_pk_field->get_table_column(),
48
+				$this_table_alias,
49
+				$this_table_fk_field->get_table_column(),
50
+				$field_with_model_name->get_qualified_column() . "='" . $this->get_other_model()->get_this_model_name(
51
+				) . "'"
52
+			)
53
+			   . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
54
+	}
55 55
 
56 56
 
57
-    /**
58
-     * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
59
-     * you like.
60
-     *
61
-     * @param EE_Base_Class|int $this_obj_or_id
62
-     * @param EE_Base_Class|int $other_obj_or_id
63
-     * @param array             $extra_join_model_fields_n_values
64
-     * @return EE_Base_Class
65
-     * @throws EE_Error
66
-     * @throws ReflectionException
67
-     * @throws Exception
68
-     */
69
-    public function add_relation_to(
70
-        $this_obj_or_id,
71
-        $other_obj_or_id,
72
-        array $extra_join_model_fields_n_values = []
73
-    ): EE_Base_Class {
74
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
75
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
76
-        // find the field on THIS model which a foreign key to the other model
77
-        $fk_on_this_model =
78
-            $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
79
-        // set that field on the other model to this model's ID
80
-        $this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
81
-        // and make sure this model's field with the foreign model name is set to the correct value
82
-        $this_model_obj->set(
83
-            $this->get_this_model()->get_field_containing_related_model_name()->get_name(),
84
-            $this->get_other_model()->get_this_model_name()
85
-        );
86
-        $this_model_obj->save();
87
-        return $other_model_obj;
88
-    }
57
+	/**
58
+	 * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
59
+	 * you like.
60
+	 *
61
+	 * @param EE_Base_Class|int $this_obj_or_id
62
+	 * @param EE_Base_Class|int $other_obj_or_id
63
+	 * @param array             $extra_join_model_fields_n_values
64
+	 * @return EE_Base_Class
65
+	 * @throws EE_Error
66
+	 * @throws ReflectionException
67
+	 * @throws Exception
68
+	 */
69
+	public function add_relation_to(
70
+		$this_obj_or_id,
71
+		$other_obj_or_id,
72
+		array $extra_join_model_fields_n_values = []
73
+	): EE_Base_Class {
74
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
75
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
76
+		// find the field on THIS model which a foreign key to the other model
77
+		$fk_on_this_model =
78
+			$this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
79
+		// set that field on the other model to this model's ID
80
+		$this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
81
+		// and make sure this model's field with the foreign model name is set to the correct value
82
+		$this_model_obj->set(
83
+			$this->get_this_model()->get_field_containing_related_model_name()->get_name(),
84
+			$this->get_other_model()->get_this_model_name()
85
+		);
86
+		$this_model_obj->save();
87
+		return $other_model_obj;
88
+	}
89 89
 
90 90
 
91
-    /**
92
-     * Sets the this model object's foreign key to its default, instead of pointing to the other model object
93
-     *
94
-     * @param EE_Base_Class|int $this_obj_or_id
95
-     * @param EE_Base_Class|int $other_obj_or_id
96
-     * @param array             $where_query
97
-     * @return EE_Base_Class
98
-     * @throws EE_Error
99
-     * @throws ReflectionException
100
-     * @throws Exception
101
-     */
102
-    public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
103
-    {
104
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
105
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
106
-        // find the field on the other model which is a foreign key to this model
107
-        $fk_on_this_model =
108
-            $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
109
-        // set that field on the other model to this model's ID
110
-        $this_model_obj->set($fk_on_this_model->get_name(), null, true);
111
-        $this_model_obj->set(
112
-            $this->get_this_model()->get_field_containing_related_model_name()->get_name(),
113
-            null,
114
-            true
115
-        );
116
-        $this_model_obj->save();
117
-        return $other_model_obj;
118
-    }
91
+	/**
92
+	 * Sets the this model object's foreign key to its default, instead of pointing to the other model object
93
+	 *
94
+	 * @param EE_Base_Class|int $this_obj_or_id
95
+	 * @param EE_Base_Class|int $other_obj_or_id
96
+	 * @param array             $where_query
97
+	 * @return EE_Base_Class
98
+	 * @throws EE_Error
99
+	 * @throws ReflectionException
100
+	 * @throws Exception
101
+	 */
102
+	public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
103
+	{
104
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
105
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
106
+		// find the field on the other model which is a foreign key to this model
107
+		$fk_on_this_model =
108
+			$this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
109
+		// set that field on the other model to this model's ID
110
+		$this_model_obj->set($fk_on_this_model->get_name(), null, true);
111
+		$this_model_obj->set(
112
+			$this->get_this_model()->get_field_containing_related_model_name()->get_name(),
113
+			null,
114
+			true
115
+		);
116
+		$this_model_obj->save();
117
+		return $other_model_obj;
118
+	}
119 119
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -35,20 +35,20 @@
 block discarded – undo
35 35
         $this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
36 36
                 $model_relation_chain,
37 37
                 $this->get_this_model()->get_this_model_name()
38
-            ) . $this_table_fk_field->get_table_alias();
39
-        $other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
38
+            ).$this_table_fk_field->get_table_alias();
39
+        $other_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
40 40
                 $model_relation_chain,
41 41
                 $this->get_other_model()->get_this_model_name()
42
-            ) . $other_table_pk_field->get_table_alias();
43
-        $other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
42
+            ).$other_table_pk_field->get_table_alias();
43
+        $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias);
44 44
         return $this->_left_join(
45 45
                 $other_table,
46 46
                 $other_table_alias,
47 47
                 $other_table_pk_field->get_table_column(),
48 48
                 $this_table_alias,
49 49
                 $this_table_fk_field->get_table_column(),
50
-                $field_with_model_name->get_qualified_column() . "='" . $this->get_other_model()->get_this_model_name(
51
-                ) . "'"
50
+                $field_with_model_name->get_qualified_column()."='".$this->get_other_model()->get_this_model_name(
51
+                )."'"
52 52
             )
53 53
                . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
54 54
     }
Please login to merge, or discard this patch.
core/db_models/relations/EE_Belongs_To_Relation.php 2 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -11,153 +11,153 @@
 block discarded – undo
11 11
  */
12 12
 class EE_Belongs_To_Relation extends EE_Model_Relation_Base
13 13
 {
14
-    /**
15
-     * Object representing the relationship between two models. Belongs_To means that THIS model has the foreign key
16
-     * to the other model. This knows how to join the models,
17
-     * get related models across the relation, and add-and-remove the relationships.
18
-     *
19
-     * @param bool   $block_deletes                                 For Belongs_To relations, this is set to FALSE by
20
-     *                                                              default. if there are related models across this
21
-     *                                                              relation, block (prevent and add an error) the
22
-     *                                                              deletion of this model
23
-     * @param string $related_model_objects_deletion_error_message  a customized error message on blocking deletes
24
-     *                                                              instead of the default
25
-     */
26
-    public function __construct(bool $block_deletes = false, string $related_model_objects_deletion_error_message = '')
27
-    {
28
-        parent::__construct($block_deletes, $related_model_objects_deletion_error_message);
29
-    }
14
+	/**
15
+	 * Object representing the relationship between two models. Belongs_To means that THIS model has the foreign key
16
+	 * to the other model. This knows how to join the models,
17
+	 * get related models across the relation, and add-and-remove the relationships.
18
+	 *
19
+	 * @param bool   $block_deletes                                 For Belongs_To relations, this is set to FALSE by
20
+	 *                                                              default. if there are related models across this
21
+	 *                                                              relation, block (prevent and add an error) the
22
+	 *                                                              deletion of this model
23
+	 * @param string $related_model_objects_deletion_error_message  a customized error message on blocking deletes
24
+	 *                                                              instead of the default
25
+	 */
26
+	public function __construct(bool $block_deletes = false, string $related_model_objects_deletion_error_message = '')
27
+	{
28
+		parent::__construct($block_deletes, $related_model_objects_deletion_error_message);
29
+	}
30 30
 
31 31
 
32
-    /**
33
-     * get_join_statement
34
-     *
35
-     * @param string $model_relation_chain
36
-     * @return string
37
-     * @throws EE_Error
38
-     * @throws Exception
39
-     */
40
-    public function get_join_statement(string $model_relation_chain): string
41
-    {
42
-        // create the sql string like
43
-        $this_table_fk_field  =
44
-            $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
45
-        $other_table_pk_field = $this->get_other_model()->get_primary_key_field();
46
-        $this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
47
-                $model_relation_chain,
48
-                $this->get_this_model()->get_this_model_name()
49
-            ) . $this_table_fk_field->get_table_alias();
50
-        $other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
51
-                $model_relation_chain,
52
-                $this->get_other_model()->get_this_model_name()
53
-            ) . $other_table_pk_field->get_table_alias();
54
-        $other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
55
-        return $this->_left_join(
56
-                $other_table,
57
-                $other_table_alias,
58
-                $other_table_pk_field->get_table_column(),
59
-                $this_table_alias,
60
-                $this_table_fk_field->get_table_column()
61
-            ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
62
-    }
32
+	/**
33
+	 * get_join_statement
34
+	 *
35
+	 * @param string $model_relation_chain
36
+	 * @return string
37
+	 * @throws EE_Error
38
+	 * @throws Exception
39
+	 */
40
+	public function get_join_statement(string $model_relation_chain): string
41
+	{
42
+		// create the sql string like
43
+		$this_table_fk_field  =
44
+			$this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
45
+		$other_table_pk_field = $this->get_other_model()->get_primary_key_field();
46
+		$this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
47
+				$model_relation_chain,
48
+				$this->get_this_model()->get_this_model_name()
49
+			) . $this_table_fk_field->get_table_alias();
50
+		$other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
51
+				$model_relation_chain,
52
+				$this->get_other_model()->get_this_model_name()
53
+			) . $other_table_pk_field->get_table_alias();
54
+		$other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
55
+		return $this->_left_join(
56
+				$other_table,
57
+				$other_table_alias,
58
+				$other_table_pk_field->get_table_column(),
59
+				$this_table_alias,
60
+				$this_table_fk_field->get_table_column()
61
+			) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
62
+	}
63 63
 
64 64
 
65
-    /**
66
-     * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
67
-     * you like.
68
-     *
69
-     * @param EE_Base_Class|int $this_obj_or_id
70
-     * @param EE_Base_Class|int $other_obj_or_id
71
-     * @param array             $extra_join_model_fields_n_values
72
-     * @return EE_Base_Class
73
-     * @throws EE_Error
74
-     * @throws Exception
75
-     */
76
-    public function add_relation_to(
77
-        $this_obj_or_id,
78
-        $other_obj_or_id,
79
-        array $extra_join_model_fields_n_values = []
80
-    ): EE_Base_Class {
81
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
82
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
83
-        // find the field on the other model which is a foreign key to this model
84
-        $fk_on_this_model =
85
-            $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
86
-        if ($this_model_obj->get($fk_on_this_model->get_name()) != $other_model_obj->ID()) {
87
-            // set that field on the other model to this model's ID
88
-            $this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
89
-            $this_model_obj->save();
90
-        }
91
-        return $other_model_obj;
92
-    }
65
+	/**
66
+	 * Sets this model object's foreign key to the other model object's primary key. Feel free to do this manually if
67
+	 * you like.
68
+	 *
69
+	 * @param EE_Base_Class|int $this_obj_or_id
70
+	 * @param EE_Base_Class|int $other_obj_or_id
71
+	 * @param array             $extra_join_model_fields_n_values
72
+	 * @return EE_Base_Class
73
+	 * @throws EE_Error
74
+	 * @throws Exception
75
+	 */
76
+	public function add_relation_to(
77
+		$this_obj_or_id,
78
+		$other_obj_or_id,
79
+		array $extra_join_model_fields_n_values = []
80
+	): EE_Base_Class {
81
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
82
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id, true);
83
+		// find the field on the other model which is a foreign key to this model
84
+		$fk_on_this_model =
85
+			$this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
86
+		if ($this_model_obj->get($fk_on_this_model->get_name()) != $other_model_obj->ID()) {
87
+			// set that field on the other model to this model's ID
88
+			$this_model_obj->set($fk_on_this_model->get_name(), $other_model_obj->ID());
89
+			$this_model_obj->save();
90
+		}
91
+		return $other_model_obj;
92
+	}
93 93
 
94 94
 
95
-    /**
96
-     * Sets the this model object's foreign key to its default, instead of pointing to the other model object
97
-     *
98
-     * @param EE_Base_Class|int $this_obj_or_id
99
-     * @param EE_Base_Class|int $other_obj_or_id
100
-     * @param array             $where_query
101
-     * @return EE_Base_Class
102
-     * @throws EE_Error
103
-     * @throws Exception
104
-     */
105
-    public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
106
-    {
107
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
108
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
109
-        // find the field on the other model which is a foreign key to this model
110
-        $fk_on_this_model = $this->get_this_model()->get_foreign_key_to(
111
-            $this->get_other_model()->get_this_model_name()
112
-        );
113
-        // set that field on the other model to this model's ID
114
-        $this_model_obj->set($fk_on_this_model->get_name(), null, true);
115
-        $this_model_obj->save();
116
-        return $other_model_obj;
117
-    }
95
+	/**
96
+	 * Sets the this model object's foreign key to its default, instead of pointing to the other model object
97
+	 *
98
+	 * @param EE_Base_Class|int $this_obj_or_id
99
+	 * @param EE_Base_Class|int $other_obj_or_id
100
+	 * @param array             $where_query
101
+	 * @return EE_Base_Class
102
+	 * @throws EE_Error
103
+	 * @throws Exception
104
+	 */
105
+	public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
106
+	{
107
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
108
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
109
+		// find the field on the other model which is a foreign key to this model
110
+		$fk_on_this_model = $this->get_this_model()->get_foreign_key_to(
111
+			$this->get_other_model()->get_this_model_name()
112
+		);
113
+		// set that field on the other model to this model's ID
114
+		$this_model_obj->set($fk_on_this_model->get_name(), null, true);
115
+		$this_model_obj->save();
116
+		return $other_model_obj;
117
+	}
118 118
 
119 119
 
120
-    /**
121
-     * Overrides parent so that we don't NEED to save the $model_object before getting the related objects.
122
-     *
123
-     * @param EE_Base_Class $model_object_or_id
124
-     * @param array|null    $query_params
125
-     * @param boolean       $values_already_prepared_by_model_object @deprecated since 4.8.1
126
-     * @return EE_Base_Class[]
127
-     * @throws EE_Error
128
-     * @throws Exception
129
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
130
-     */
131
-    public function get_all_related(
132
-        $model_object_or_id,
133
-        ?array $query_params = [],
134
-        bool $values_already_prepared_by_model_object = false
135
-    ): array {
136
-        if ($values_already_prepared_by_model_object !== false) {
137
-            EE_Error::doing_it_wrong(
138
-                'EE_Model_Relation_Base::get_all_related',
139
-                esc_html__(
140
-                    'The argument $values_already_prepared_by_model_object is no longer used.',
141
-                    'event_espresso'
142
-                ),
143
-                '4.8.1'
144
-            );
145
-        }
146
-        // get column on this model object which is a foreign key to the other model
147
-        $fk_field_obj = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
148
-        // get its value
149
-        if ($model_object_or_id instanceof EE_Base_Class) {
150
-            $model_obj = $model_object_or_id;
151
-        } else {
152
-            $model_obj = $this->get_this_model()->ensure_is_obj($model_object_or_id);
153
-        }
154
-        $ID_value_on_other_model = $model_obj->get($fk_field_obj->get_name());
155
-        // get all where their PK matches that value
156
-        $query_params[0][ $this->get_other_model()->get_primary_key_field()->get_name() ] = $ID_value_on_other_model;
157
-        $query_params                                                                     =
158
-            $this->_disable_default_where_conditions_on_query_param($query_params);
120
+	/**
121
+	 * Overrides parent so that we don't NEED to save the $model_object before getting the related objects.
122
+	 *
123
+	 * @param EE_Base_Class $model_object_or_id
124
+	 * @param array|null    $query_params
125
+	 * @param boolean       $values_already_prepared_by_model_object @deprecated since 4.8.1
126
+	 * @return EE_Base_Class[]
127
+	 * @throws EE_Error
128
+	 * @throws Exception
129
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
130
+	 */
131
+	public function get_all_related(
132
+		$model_object_or_id,
133
+		?array $query_params = [],
134
+		bool $values_already_prepared_by_model_object = false
135
+	): array {
136
+		if ($values_already_prepared_by_model_object !== false) {
137
+			EE_Error::doing_it_wrong(
138
+				'EE_Model_Relation_Base::get_all_related',
139
+				esc_html__(
140
+					'The argument $values_already_prepared_by_model_object is no longer used.',
141
+					'event_espresso'
142
+				),
143
+				'4.8.1'
144
+			);
145
+		}
146
+		// get column on this model object which is a foreign key to the other model
147
+		$fk_field_obj = $this->get_this_model()->get_foreign_key_to($this->get_other_model()->get_this_model_name());
148
+		// get its value
149
+		if ($model_object_or_id instanceof EE_Base_Class) {
150
+			$model_obj = $model_object_or_id;
151
+		} else {
152
+			$model_obj = $this->get_this_model()->ensure_is_obj($model_object_or_id);
153
+		}
154
+		$ID_value_on_other_model = $model_obj->get($fk_field_obj->get_name());
155
+		// get all where their PK matches that value
156
+		$query_params[0][ $this->get_other_model()->get_primary_key_field()->get_name() ] = $ID_value_on_other_model;
157
+		$query_params                                                                     =
158
+			$this->_disable_default_where_conditions_on_query_param($query_params);
159 159
 //      echo '$query_params';
160 160
 //      var_dump($query_params);
161
-        return $this->get_other_model()->get_all($query_params);
162
-    }
161
+		return $this->get_other_model()->get_all($query_params);
162
+	}
163 163
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -46,19 +46,19 @@  discard block
 block discarded – undo
46 46
         $this_table_alias     = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
47 47
                 $model_relation_chain,
48 48
                 $this->get_this_model()->get_this_model_name()
49
-            ) . $this_table_fk_field->get_table_alias();
50
-        $other_table_alias    = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
49
+            ).$this_table_fk_field->get_table_alias();
50
+        $other_table_alias = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
51 51
                 $model_relation_chain,
52 52
                 $this->get_other_model()->get_this_model_name()
53
-            ) . $other_table_pk_field->get_table_alias();
54
-        $other_table          = $this->get_other_model()->get_table_for_alias($other_table_alias);
53
+            ).$other_table_pk_field->get_table_alias();
54
+        $other_table = $this->get_other_model()->get_table_for_alias($other_table_alias);
55 55
         return $this->_left_join(
56 56
                 $other_table,
57 57
                 $other_table_alias,
58 58
                 $other_table_pk_field->get_table_column(),
59 59
                 $this_table_alias,
60 60
                 $this_table_fk_field->get_table_column()
61
-            ) . $this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
61
+            ).$this->get_other_model()->_construct_internal_join_to_table_with_alias($other_table_alias);
62 62
     }
63 63
 
64 64
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
         }
154 154
         $ID_value_on_other_model = $model_obj->get($fk_field_obj->get_name());
155 155
         // get all where their PK matches that value
156
-        $query_params[0][ $this->get_other_model()->get_primary_key_field()->get_name() ] = $ID_value_on_other_model;
156
+        $query_params[0][$this->get_other_model()->get_primary_key_field()->get_name()] = $ID_value_on_other_model;
157 157
         $query_params                                                                     =
158 158
             $this->_disable_default_where_conditions_on_query_param($query_params);
159 159
 //      echo '$query_params';
Please login to merge, or discard this patch.
core/db_models/relations/EE_Has_Many_Revision_Relation.php 2 patches
Indentation   +316 added lines, -316 removed lines patch added patch discarded remove patch
@@ -10,323 +10,323 @@
 block discarded – undo
10 10
  */
11 11
 class EE_Has_Many_Revision_Relation extends EE_Has_Many_Relation
12 12
 {
13
-    /**
14
-     * The Foreign key on the model that acts as the PRIMARY KEY used in special autosave handling where we query for
15
-     * autosaves (or the Foreign key on other models in relations pointing to this models primary key which is this
16
-     * value).  The _primary_cpt_field is what is equivalent to the post_id field on a cpt join.
17
-     */
18
-    private string $_primary_cpt_field;
19
-
20
-
21
-    /**
22
-     * This is what field serves as the "parent" column that is linked with whatever the main model's calling this
23
-     * relation has as a primary key.  In other words EEM_Event has 'Datetime' => new
24
-     * EE_Has_Many_Revision_Relation('EVT_ID', 'DTT_parent').  That means that in the EEM_Datetime model the
25
-     * 'DTT_Parent' field is related to the 'DTT_ID' primary key field (in the same model) because 'DTT_ID' is the
26
-     * primary key in the other model (EEM_Datetime).
27
-     */
28
-    private string $_parent_pk_relation_field;
29
-
30
-
31
-    /**
32
-     * Object representing the relationship between two models. Has_Many_Relations are where the OTHER model has the
33
-     * foreign key this model. IE, there can be many other model objects related to one of this model's objects (but
34
-     * NOT through a JOIN table, which is the case for EE_HABTM_Relations). This knows how to join the models, get
35
-     * related models across the relation, and add-and-remove the relationships.
36
-     *
37
-     * @param string $primary_cpt_field              See property description for details
38
-     * @param string $parent_pk_relation_field       This is the field that is "connected" to the $primary_cpt_field.
39
-     *                                               See property desc for details.
40
-     * @param bool   $block_deletes                  For this type of relation, we block by default. If there are
41
-     *                                               related models across this relation, block (prevent and add an
42
-     *                                               error) the deletion of this model
43
-     * @param string $blocking_delete_error_message  a customized error message on blocking deletes instead of the
44
-     *                                               default
45
-     */
46
-    public function __construct(
47
-        string $primary_cpt_field,
48
-        string $parent_pk_relation_field,
49
-        bool $block_deletes = true,
50
-        string $blocking_delete_error_message = ''
51
-    ) {
52
-        $this->_primary_cpt_field        = $primary_cpt_field;
53
-        $this->_parent_pk_relation_field = $parent_pk_relation_field;
54
-        parent::__construct($block_deletes, $blocking_delete_error_message);
55
-    }
56
-
57
-
58
-    /**
59
-     * Sets the other model object's foreign key to this model object's primary key. Feel free to do this manually if
60
-     * you like.
61
-     *
62
-     * @param EE_Base_Class|int $this_obj_or_id
63
-     * @param EE_Base_Class|int $other_obj_or_id
64
-     * @param array             $extra_join_model_fields_n_values
65
-     * @return EE_Base_Class
66
-     * @throws EE_Error
67
-     * @throws Exception
68
-     */
69
-    public function add_relation_to(
70
-        $this_obj_or_id,
71
-        $other_obj_or_id,
72
-        array $extra_join_model_fields_n_values = []
73
-    ): EE_Base_Class {
74
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
75
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
76
-
77
-        // handle possible revisions
78
-        $other_model_obj = $this->_check_for_revision($this_model_obj, $other_model_obj);
79
-
80
-        // if is array, then we've already done the add_relation so let's get out
81
-        if (is_array($other_model_obj)) {
82
-            return $other_model_obj[0];
83
-        }
84
-        // find the field on the other model which is a foreign key to this model
85
-        $fk_field_on_other_model =
86
-            $this->get_other_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
87
-        // set that field on the other model to this model's ID
88
-        $other_model_obj->set($fk_field_on_other_model->get_name(), $this_model_obj->ID());
89
-        $other_model_obj->save();
90
-        return $other_model_obj;
91
-    }
92
-
93
-
94
-    /**
95
-     * Sets the other model object's foreign key to its default, instead of pointing to this model object
96
-     *
97
-     * @param EE_Base_Class|int $this_obj_or_id
98
-     * @param EE_Base_Class|int $other_obj_or_id
99
-     * @param array             $where_query
100
-     * @return EE_Base_Class
101
-     * @throws EE_Error
102
-     * @throws Exception
103
-     */
104
-    public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
105
-    {
106
-        $this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id);
107
-        $other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
108
-        // handle possible revisions
109
-        $other_model_obj = $this->_check_for_revision($this_model_obj, $other_model_obj, true);
110
-
111
-
112
-        // if is array, then we've already done the add_relation so let's get out
113
-        if (is_array($other_model_obj)) {
114
-            return $other_model_obj[0];
115
-        }
116
-
117
-        // find the field on the other model which is a foreign key to this model
118
-        $fk_field_on_other_model =
119
-            $this->get_other_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
120
-
121
-
122
-        // set that field on the other model to this model's ID
123
-        if ($this->_blocking_delete) {
124
-            $other_model_obj->set($fk_field_on_other_model->get_name(), null, true);
125
-            $other_model_obj->save();
126
-        } else {
127
-            $other_model_obj->delete();
128
-            $other_model_obj->set($fk_field_on_other_model->get_name(), null, true);
129
-            return $other_model_obj;
130
-        }
131
-        return $other_model_obj;
132
-    }
133
-
134
-
135
-    /**
136
-     * This is identical to EE_Model_Relation->get_all_related() except we're going handle special autosave conditions
137
-     * in here.
138
-     *
139
-     * @param EE_Base_Class|int $model_object_or_id
140
-     * @param array|null        $query_params                            @see
141
-     *                                                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
143
-     * @return EE_Base_Class[]
144
-     * @throws EE_Error
145
-     * @throws ReflectionException
146
-     */
147
-    public function get_all_related(
148
-        $model_object_or_id,
149
-        ?array $query_params = [],
150
-        bool $values_already_prepared_by_model_object = false
151
-    ): array {
152
-        if ($values_already_prepared_by_model_object !== false) {
153
-            EE_Error::doing_it_wrong(
154
-                'EE_Model_Relation_Base::get_all_related',
155
-                esc_html__(
156
-                    'The argument $values_already_prepared_by_model_object is no longer used.',
157
-                    'event_espresso'
158
-                ),
159
-                '4.8.1'
160
-            );
161
-        }
162
-
163
-        // if this is an autosave then we're going to get things differently
164
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
165
-            return $this->_do_autosave_get_all($model_object_or_id, $query_params);
166
-        }
167
-
168
-        return parent::get_all_related($model_object_or_id, $query_params);
169
-    }
170
-
171
-
172
-    /**
173
-     * If we're in the midst of an autosave then we're going to do things a bit differently than the usual
174
-     * get_all_related (commenting within).  For description of params see the get_all_related() comments
175
-     *
176
-     * @access protected
177
-     * @param      $model_object_or_id
178
-     * @param      $query_params
179
-     * @return EE_Base_Class[]
180
-     * @throws EE_Error
181
-     * @throws ReflectionException
182
-     * @throws Exception
183
-     */
184
-    protected function _do_autosave_get_all($model_object_or_id, $query_params): array
185
-    {
186
-        // first we check if the post_id for the incoming query is for an autosave.  If it isn't that's what we want!
187
-        $model_object_id = $this->_get_model_object_id($model_object_or_id);
188
-
189
-        $autosave  = wp_get_post_autosave($model_object_id);
190
-        $id_to_use = $autosave ? $autosave->ID : $model_object_id;
191
-
192
-        $autosave_relations = parent::get_all_related($id_to_use, $query_params);
193
-        $parent_ids         = $parents = [];
194
-        $return_objs        = [];
195
-
196
-        // k this is where things differ because NOW what we're going to do is get the PARENTS for the get all related
197
-        // (and we'll also start setting up the return_objs array containing related that DON'T have parent ids,
198
-        // for those that DON'T have parents to merge with our returned objects);
199
-        foreach ($autosave_relations as $a_r) {
200
-            $pid = method_exists($a_r, 'parent') ? $a_r->parent() : null;
201
-            if (! empty($pid)) {
202
-                $parent_ids[] = $pid;
203
-            } else {
204
-                $return_objs[] = $a_r;
205
-            }
206
-        }
207
-
208
-        // we have to make sure we also include the ORIGINAL values
209
-        $originals = parent::get_all_related($model_object_or_id, $query_params);
210
-
211
-        // merge $originals with $return_objs
212
-        if ($originals) {
213
-            $return_objs = array_merge($originals, $return_objs);
214
-        }
215
-
216
-        // now we setup the query to get all the parents
217
-        if (! empty($parent_ids)) {
218
-            $query_param_where_this_model_pk = $this->get_this_model()->get_this_model_name() . "."
219
-                                               . $this->get_this_model()->get_primary_key_field()->get_name();
220
-
221
-            $query_params[0][ $query_param_where_this_model_pk ] = ['IN', $parent_ids];
222
-
223
-            $parents = $this->get_other_model()->get_all($query_params);
224
-        }
225
-
226
-        // var_dump($parents);
227
-
228
-
229
-        // now merge parents with our current $return_objs and send back
230
-        return array_merge($parents, $return_objs);
231
-    }
232
-
233
-
234
-    /**
235
-     * Basically this method gets called to verify if the incoming object needs to be manipulated somewhat because it
236
-     * is a revision save.  If so, then we change things before sending back.  We also do verifications when this IS
237
-     * NOT an revision because we always need to make sure that the autosave/revision has parent recorded (which is
238
-     * sometime delayed if the object is created/saved first by the autosave)
239
-     *
240
-     * @param EE_Base_Class $this_obj
241
-     * @param EE_Base_Class $other_obj
242
-     * @param boolean       $remove_relation Indicates whether we're doing a remove_relation or add_relation.
243
-     * @return EE_Base_Class|EE_Base_Class[] ($other_obj);
244
-     * @throws EE_Error
245
-     * @throws Exception
246
-     */
247
-    protected function _check_for_revision(
248
-        EE_Base_Class $this_obj,
249
-        EE_Base_Class $other_obj,
250
-        bool $remove_relation = false
251
-    ) {
252
-        $pk_on_related_model = $this->get_other_model()->get_primary_key_field()->get_name();
253
-        // now we need to determine if we're in a WP revision save cause if we are we need to do some special handling
254
-        if ($this_obj instanceof EE_CPT_Base && $this_obj->post_type() === 'revision') {
255
-            // first if $other_obj fk = this_obj pk then we know that this is a pk object, let's make sure there is a matching set for the autosave if there is then we save over it, if there isn't then we need to create a new one.
256
-            $parent_evt_id = $this_obj->parent();
257
-            /*var_dump($parent_evt_id);
13
+	/**
14
+	 * The Foreign key on the model that acts as the PRIMARY KEY used in special autosave handling where we query for
15
+	 * autosaves (or the Foreign key on other models in relations pointing to this models primary key which is this
16
+	 * value).  The _primary_cpt_field is what is equivalent to the post_id field on a cpt join.
17
+	 */
18
+	private string $_primary_cpt_field;
19
+
20
+
21
+	/**
22
+	 * This is what field serves as the "parent" column that is linked with whatever the main model's calling this
23
+	 * relation has as a primary key.  In other words EEM_Event has 'Datetime' => new
24
+	 * EE_Has_Many_Revision_Relation('EVT_ID', 'DTT_parent').  That means that in the EEM_Datetime model the
25
+	 * 'DTT_Parent' field is related to the 'DTT_ID' primary key field (in the same model) because 'DTT_ID' is the
26
+	 * primary key in the other model (EEM_Datetime).
27
+	 */
28
+	private string $_parent_pk_relation_field;
29
+
30
+
31
+	/**
32
+	 * Object representing the relationship between two models. Has_Many_Relations are where the OTHER model has the
33
+	 * foreign key this model. IE, there can be many other model objects related to one of this model's objects (but
34
+	 * NOT through a JOIN table, which is the case for EE_HABTM_Relations). This knows how to join the models, get
35
+	 * related models across the relation, and add-and-remove the relationships.
36
+	 *
37
+	 * @param string $primary_cpt_field              See property description for details
38
+	 * @param string $parent_pk_relation_field       This is the field that is "connected" to the $primary_cpt_field.
39
+	 *                                               See property desc for details.
40
+	 * @param bool   $block_deletes                  For this type of relation, we block by default. If there are
41
+	 *                                               related models across this relation, block (prevent and add an
42
+	 *                                               error) the deletion of this model
43
+	 * @param string $blocking_delete_error_message  a customized error message on blocking deletes instead of the
44
+	 *                                               default
45
+	 */
46
+	public function __construct(
47
+		string $primary_cpt_field,
48
+		string $parent_pk_relation_field,
49
+		bool $block_deletes = true,
50
+		string $blocking_delete_error_message = ''
51
+	) {
52
+		$this->_primary_cpt_field        = $primary_cpt_field;
53
+		$this->_parent_pk_relation_field = $parent_pk_relation_field;
54
+		parent::__construct($block_deletes, $blocking_delete_error_message);
55
+	}
56
+
57
+
58
+	/**
59
+	 * Sets the other model object's foreign key to this model object's primary key. Feel free to do this manually if
60
+	 * you like.
61
+	 *
62
+	 * @param EE_Base_Class|int $this_obj_or_id
63
+	 * @param EE_Base_Class|int $other_obj_or_id
64
+	 * @param array             $extra_join_model_fields_n_values
65
+	 * @return EE_Base_Class
66
+	 * @throws EE_Error
67
+	 * @throws Exception
68
+	 */
69
+	public function add_relation_to(
70
+		$this_obj_or_id,
71
+		$other_obj_or_id,
72
+		array $extra_join_model_fields_n_values = []
73
+	): EE_Base_Class {
74
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id, true);
75
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
76
+
77
+		// handle possible revisions
78
+		$other_model_obj = $this->_check_for_revision($this_model_obj, $other_model_obj);
79
+
80
+		// if is array, then we've already done the add_relation so let's get out
81
+		if (is_array($other_model_obj)) {
82
+			return $other_model_obj[0];
83
+		}
84
+		// find the field on the other model which is a foreign key to this model
85
+		$fk_field_on_other_model =
86
+			$this->get_other_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
87
+		// set that field on the other model to this model's ID
88
+		$other_model_obj->set($fk_field_on_other_model->get_name(), $this_model_obj->ID());
89
+		$other_model_obj->save();
90
+		return $other_model_obj;
91
+	}
92
+
93
+
94
+	/**
95
+	 * Sets the other model object's foreign key to its default, instead of pointing to this model object
96
+	 *
97
+	 * @param EE_Base_Class|int $this_obj_or_id
98
+	 * @param EE_Base_Class|int $other_obj_or_id
99
+	 * @param array             $where_query
100
+	 * @return EE_Base_Class
101
+	 * @throws EE_Error
102
+	 * @throws Exception
103
+	 */
104
+	public function remove_relation_to($this_obj_or_id, $other_obj_or_id, array $where_query = []): EE_Base_Class
105
+	{
106
+		$this_model_obj  = $this->get_this_model()->ensure_is_obj($this_obj_or_id);
107
+		$other_model_obj = $this->get_other_model()->ensure_is_obj($other_obj_or_id);
108
+		// handle possible revisions
109
+		$other_model_obj = $this->_check_for_revision($this_model_obj, $other_model_obj, true);
110
+
111
+
112
+		// if is array, then we've already done the add_relation so let's get out
113
+		if (is_array($other_model_obj)) {
114
+			return $other_model_obj[0];
115
+		}
116
+
117
+		// find the field on the other model which is a foreign key to this model
118
+		$fk_field_on_other_model =
119
+			$this->get_other_model()->get_foreign_key_to($this->get_this_model()->get_this_model_name());
120
+
121
+
122
+		// set that field on the other model to this model's ID
123
+		if ($this->_blocking_delete) {
124
+			$other_model_obj->set($fk_field_on_other_model->get_name(), null, true);
125
+			$other_model_obj->save();
126
+		} else {
127
+			$other_model_obj->delete();
128
+			$other_model_obj->set($fk_field_on_other_model->get_name(), null, true);
129
+			return $other_model_obj;
130
+		}
131
+		return $other_model_obj;
132
+	}
133
+
134
+
135
+	/**
136
+	 * This is identical to EE_Model_Relation->get_all_related() except we're going handle special autosave conditions
137
+	 * in here.
138
+	 *
139
+	 * @param EE_Base_Class|int $model_object_or_id
140
+	 * @param array|null        $query_params                            @see
141
+	 *                                                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
142
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
143
+	 * @return EE_Base_Class[]
144
+	 * @throws EE_Error
145
+	 * @throws ReflectionException
146
+	 */
147
+	public function get_all_related(
148
+		$model_object_or_id,
149
+		?array $query_params = [],
150
+		bool $values_already_prepared_by_model_object = false
151
+	): array {
152
+		if ($values_already_prepared_by_model_object !== false) {
153
+			EE_Error::doing_it_wrong(
154
+				'EE_Model_Relation_Base::get_all_related',
155
+				esc_html__(
156
+					'The argument $values_already_prepared_by_model_object is no longer used.',
157
+					'event_espresso'
158
+				),
159
+				'4.8.1'
160
+			);
161
+		}
162
+
163
+		// if this is an autosave then we're going to get things differently
164
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
165
+			return $this->_do_autosave_get_all($model_object_or_id, $query_params);
166
+		}
167
+
168
+		return parent::get_all_related($model_object_or_id, $query_params);
169
+	}
170
+
171
+
172
+	/**
173
+	 * If we're in the midst of an autosave then we're going to do things a bit differently than the usual
174
+	 * get_all_related (commenting within).  For description of params see the get_all_related() comments
175
+	 *
176
+	 * @access protected
177
+	 * @param      $model_object_or_id
178
+	 * @param      $query_params
179
+	 * @return EE_Base_Class[]
180
+	 * @throws EE_Error
181
+	 * @throws ReflectionException
182
+	 * @throws Exception
183
+	 */
184
+	protected function _do_autosave_get_all($model_object_or_id, $query_params): array
185
+	{
186
+		// first we check if the post_id for the incoming query is for an autosave.  If it isn't that's what we want!
187
+		$model_object_id = $this->_get_model_object_id($model_object_or_id);
188
+
189
+		$autosave  = wp_get_post_autosave($model_object_id);
190
+		$id_to_use = $autosave ? $autosave->ID : $model_object_id;
191
+
192
+		$autosave_relations = parent::get_all_related($id_to_use, $query_params);
193
+		$parent_ids         = $parents = [];
194
+		$return_objs        = [];
195
+
196
+		// k this is where things differ because NOW what we're going to do is get the PARENTS for the get all related
197
+		// (and we'll also start setting up the return_objs array containing related that DON'T have parent ids,
198
+		// for those that DON'T have parents to merge with our returned objects);
199
+		foreach ($autosave_relations as $a_r) {
200
+			$pid = method_exists($a_r, 'parent') ? $a_r->parent() : null;
201
+			if (! empty($pid)) {
202
+				$parent_ids[] = $pid;
203
+			} else {
204
+				$return_objs[] = $a_r;
205
+			}
206
+		}
207
+
208
+		// we have to make sure we also include the ORIGINAL values
209
+		$originals = parent::get_all_related($model_object_or_id, $query_params);
210
+
211
+		// merge $originals with $return_objs
212
+		if ($originals) {
213
+			$return_objs = array_merge($originals, $return_objs);
214
+		}
215
+
216
+		// now we setup the query to get all the parents
217
+		if (! empty($parent_ids)) {
218
+			$query_param_where_this_model_pk = $this->get_this_model()->get_this_model_name() . "."
219
+											   . $this->get_this_model()->get_primary_key_field()->get_name();
220
+
221
+			$query_params[0][ $query_param_where_this_model_pk ] = ['IN', $parent_ids];
222
+
223
+			$parents = $this->get_other_model()->get_all($query_params);
224
+		}
225
+
226
+		// var_dump($parents);
227
+
228
+
229
+		// now merge parents with our current $return_objs and send back
230
+		return array_merge($parents, $return_objs);
231
+	}
232
+
233
+
234
+	/**
235
+	 * Basically this method gets called to verify if the incoming object needs to be manipulated somewhat because it
236
+	 * is a revision save.  If so, then we change things before sending back.  We also do verifications when this IS
237
+	 * NOT an revision because we always need to make sure that the autosave/revision has parent recorded (which is
238
+	 * sometime delayed if the object is created/saved first by the autosave)
239
+	 *
240
+	 * @param EE_Base_Class $this_obj
241
+	 * @param EE_Base_Class $other_obj
242
+	 * @param boolean       $remove_relation Indicates whether we're doing a remove_relation or add_relation.
243
+	 * @return EE_Base_Class|EE_Base_Class[] ($other_obj);
244
+	 * @throws EE_Error
245
+	 * @throws Exception
246
+	 */
247
+	protected function _check_for_revision(
248
+		EE_Base_Class $this_obj,
249
+		EE_Base_Class $other_obj,
250
+		bool $remove_relation = false
251
+	) {
252
+		$pk_on_related_model = $this->get_other_model()->get_primary_key_field()->get_name();
253
+		// now we need to determine if we're in a WP revision save cause if we are we need to do some special handling
254
+		if ($this_obj instanceof EE_CPT_Base && $this_obj->post_type() === 'revision') {
255
+			// first if $other_obj fk = this_obj pk then we know that this is a pk object, let's make sure there is a matching set for the autosave if there is then we save over it, if there isn't then we need to create a new one.
256
+			$parent_evt_id = $this_obj->parent();
257
+			/*var_dump($parent_evt_id);
258 258
             var_dump($this_obj);
259 259
             var_dump($other_obj);/**/
260 260
 
261
-            if (! empty($parent_evt_id) && $parent_evt_id == $other_obj->get($this->_primary_cpt_field)) {
262
-                // let's do query on this objects model to see if the incoming pk value on the obj matches any parents in this objects table.
263
-                $has_parent_obj = $this->get_other_model()->get_one(
264
-                    [
265
-                        [
266
-                            $this->_parent_pk_relation_field => $other_obj->ID(),
267
-                            $this->_primary_cpt_field        => $this_obj->ID(),
268
-                        ],
269
-                    ]
270
-                );
271
-
272
-                $other_obj->set($this->_parent_pk_relation_field, $other_obj->ID());
273
-                if ($has_parent_obj) {
274
-                    // this makes sure the update on the current obj happens to the revision's row NOT the parent row.
275
-
276
-                    $other_obj->set($pk_on_related_model, $has_parent_obj->ID());
277
-                    $other_obj->set($this->_primary_cpt_field, $this_obj->ID());
278
-
279
-                    if (! $remove_relation) {
280
-                        $other_obj->save();
281
-                        return [$other_obj];
282
-                    }
283
-                    if (! $this->_blocking_delete) {
284
-                        $other_obj->delete();
285
-                        $other_obj->set($this->_parent_pk_relation_field, null, true);
286
-                        return [$other_obj];
287
-                    }
288
-                } else {
289
-                    $other_obj->set($this->_primary_cpt_field, $this_obj->ID());
290
-                    $other_obj->set(
291
-                        $pk_on_related_model,
292
-                        null,
293
-                        true
294
-                    );                  // ensure we create a new row for the autosave with parent id the same as the incoming ID.
295
-                    $other_obj->save(); // make sure we insert.
296
-                    return [$other_obj];
297
-                }
298
-            }
299
-
300
-            // var_dump('what makes it here');
301
-            // var_dump($other_obj);
302
-            // the next possible condition is that the incoming other_model obj has a NULL pk which means it just gets saved (which in turn creates it)
303
-
304
-            // the last possible condition on a revision is that the incoming other_model object has a fk that == $this_obj pk which means we just return the $other obj and let it save as normal so we see the return at the bottom of this method.
305
-        } else {
306
-            // we only need to do the below IF this is not a remove relation
307
-            if (! $remove_relation) {
308
-                // okay this is is a normal update/save/remove so, let's make sure the other object is not a revision of the current object.
309
-                // the other object will likely NOT have the correct fk on it (which is the primary_cpt_field_mame) so we must retrieve from the db to get that first.
310
-                $existing_other_obj    = $this->get_other_model()->get_one_by_ID($other_obj->ID());
311
-                $potential_revision_id =
312
-                    is_object($existing_other_obj) ? $existing_other_obj->get($this->_primary_cpt_field) : null;
313
-
314
-                if (wp_is_post_revision($potential_revision_id)) {
315
-                    // yes the OTHER object is linked to the revision of the parent, not the parent itself. That means we need to make the other_object an attachment of this_obj and then duplicate other_obj for the revision.
316
-                    $other_obj->set($this->_primary_cpt_field, $this_obj->ID());
317
-                    $other_obj->save();
318
-
319
-                    // now create a new other_obj and fill with details from existing object
320
-                    $new_obj = $other_obj;
321
-                    $new_obj->set($this->_primary_cpt_field, $potential_revision_id);
322
-                    $new_obj->set($this->_parent_pk_relation_field, $other_obj->ID());
323
-                    $new_obj->set($pk_on_related_model, null);
324
-                    $new_obj->save();
325
-                    return [$new_obj];
326
-                }
327
-            }
328
-        }
329
-
330
-        return $other_obj;
331
-    }
261
+			if (! empty($parent_evt_id) && $parent_evt_id == $other_obj->get($this->_primary_cpt_field)) {
262
+				// let's do query on this objects model to see if the incoming pk value on the obj matches any parents in this objects table.
263
+				$has_parent_obj = $this->get_other_model()->get_one(
264
+					[
265
+						[
266
+							$this->_parent_pk_relation_field => $other_obj->ID(),
267
+							$this->_primary_cpt_field        => $this_obj->ID(),
268
+						],
269
+					]
270
+				);
271
+
272
+				$other_obj->set($this->_parent_pk_relation_field, $other_obj->ID());
273
+				if ($has_parent_obj) {
274
+					// this makes sure the update on the current obj happens to the revision's row NOT the parent row.
275
+
276
+					$other_obj->set($pk_on_related_model, $has_parent_obj->ID());
277
+					$other_obj->set($this->_primary_cpt_field, $this_obj->ID());
278
+
279
+					if (! $remove_relation) {
280
+						$other_obj->save();
281
+						return [$other_obj];
282
+					}
283
+					if (! $this->_blocking_delete) {
284
+						$other_obj->delete();
285
+						$other_obj->set($this->_parent_pk_relation_field, null, true);
286
+						return [$other_obj];
287
+					}
288
+				} else {
289
+					$other_obj->set($this->_primary_cpt_field, $this_obj->ID());
290
+					$other_obj->set(
291
+						$pk_on_related_model,
292
+						null,
293
+						true
294
+					);                  // ensure we create a new row for the autosave with parent id the same as the incoming ID.
295
+					$other_obj->save(); // make sure we insert.
296
+					return [$other_obj];
297
+				}
298
+			}
299
+
300
+			// var_dump('what makes it here');
301
+			// var_dump($other_obj);
302
+			// the next possible condition is that the incoming other_model obj has a NULL pk which means it just gets saved (which in turn creates it)
303
+
304
+			// the last possible condition on a revision is that the incoming other_model object has a fk that == $this_obj pk which means we just return the $other obj and let it save as normal so we see the return at the bottom of this method.
305
+		} else {
306
+			// we only need to do the below IF this is not a remove relation
307
+			if (! $remove_relation) {
308
+				// okay this is is a normal update/save/remove so, let's make sure the other object is not a revision of the current object.
309
+				// the other object will likely NOT have the correct fk on it (which is the primary_cpt_field_mame) so we must retrieve from the db to get that first.
310
+				$existing_other_obj    = $this->get_other_model()->get_one_by_ID($other_obj->ID());
311
+				$potential_revision_id =
312
+					is_object($existing_other_obj) ? $existing_other_obj->get($this->_primary_cpt_field) : null;
313
+
314
+				if (wp_is_post_revision($potential_revision_id)) {
315
+					// yes the OTHER object is linked to the revision of the parent, not the parent itself. That means we need to make the other_object an attachment of this_obj and then duplicate other_obj for the revision.
316
+					$other_obj->set($this->_primary_cpt_field, $this_obj->ID());
317
+					$other_obj->save();
318
+
319
+					// now create a new other_obj and fill with details from existing object
320
+					$new_obj = $other_obj;
321
+					$new_obj->set($this->_primary_cpt_field, $potential_revision_id);
322
+					$new_obj->set($this->_parent_pk_relation_field, $other_obj->ID());
323
+					$new_obj->set($pk_on_related_model, null);
324
+					$new_obj->save();
325
+					return [$new_obj];
326
+				}
327
+			}
328
+		}
329
+
330
+		return $other_obj;
331
+	}
332 332
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
         // for those that DON'T have parents to merge with our returned objects);
199 199
         foreach ($autosave_relations as $a_r) {
200 200
             $pid = method_exists($a_r, 'parent') ? $a_r->parent() : null;
201
-            if (! empty($pid)) {
201
+            if ( ! empty($pid)) {
202 202
                 $parent_ids[] = $pid;
203 203
             } else {
204 204
                 $return_objs[] = $a_r;
@@ -214,11 +214,11 @@  discard block
 block discarded – undo
214 214
         }
215 215
 
216 216
         // now we setup the query to get all the parents
217
-        if (! empty($parent_ids)) {
218
-            $query_param_where_this_model_pk = $this->get_this_model()->get_this_model_name() . "."
217
+        if ( ! empty($parent_ids)) {
218
+            $query_param_where_this_model_pk = $this->get_this_model()->get_this_model_name()."."
219 219
                                                . $this->get_this_model()->get_primary_key_field()->get_name();
220 220
 
221
-            $query_params[0][ $query_param_where_this_model_pk ] = ['IN', $parent_ids];
221
+            $query_params[0][$query_param_where_this_model_pk] = ['IN', $parent_ids];
222 222
 
223 223
             $parents = $this->get_other_model()->get_all($query_params);
224 224
         }
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
             var_dump($this_obj);
259 259
             var_dump($other_obj);/**/
260 260
 
261
-            if (! empty($parent_evt_id) && $parent_evt_id == $other_obj->get($this->_primary_cpt_field)) {
261
+            if ( ! empty($parent_evt_id) && $parent_evt_id == $other_obj->get($this->_primary_cpt_field)) {
262 262
                 // let's do query on this objects model to see if the incoming pk value on the obj matches any parents in this objects table.
263 263
                 $has_parent_obj = $this->get_other_model()->get_one(
264 264
                     [
@@ -276,11 +276,11 @@  discard block
 block discarded – undo
276 276
                     $other_obj->set($pk_on_related_model, $has_parent_obj->ID());
277 277
                     $other_obj->set($this->_primary_cpt_field, $this_obj->ID());
278 278
 
279
-                    if (! $remove_relation) {
279
+                    if ( ! $remove_relation) {
280 280
                         $other_obj->save();
281 281
                         return [$other_obj];
282 282
                     }
283
-                    if (! $this->_blocking_delete) {
283
+                    if ( ! $this->_blocking_delete) {
284 284
                         $other_obj->delete();
285 285
                         $other_obj->set($this->_parent_pk_relation_field, null, true);
286 286
                         return [$other_obj];
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
                         $pk_on_related_model,
292 292
                         null,
293 293
                         true
294
-                    );                  // ensure we create a new row for the autosave with parent id the same as the incoming ID.
294
+                    ); // ensure we create a new row for the autosave with parent id the same as the incoming ID.
295 295
                     $other_obj->save(); // make sure we insert.
296 296
                     return [$other_obj];
297 297
                 }
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
             // the last possible condition on a revision is that the incoming other_model object has a fk that == $this_obj pk which means we just return the $other obj and let it save as normal so we see the return at the bottom of this method.
305 305
         } else {
306 306
             // we only need to do the below IF this is not a remove relation
307
-            if (! $remove_relation) {
307
+            if ( ! $remove_relation) {
308 308
                 // okay this is is a normal update/save/remove so, let's make sure the other object is not a revision of the current object.
309 309
                 // the other object will likely NOT have the correct fk on it (which is the primary_cpt_field_mame) so we must retrieve from the db to get that first.
310 310
                 $existing_other_obj    = $this->get_other_model()->get_one_by_ID($other_obj->ID());
Please login to merge, or discard this patch.
core/db_models/EEM_Transaction.model.php 1 patch
Indentation   +448 added lines, -448 removed lines patch added patch discarded remove patch
@@ -18,226 +18,226 @@  discard block
 block discarded – undo
18 18
  */
19 19
 class EEM_Transaction extends EEM_Base
20 20
 {
21
-    // private instance of the Transaction object
22
-    protected static $_instance;
23
-
24
-    /**
25
-     * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
26
-     * but payment is pending. This is the state for transactions where payment is promised
27
-     * from an offline gateway.
28
-     */
29
-    //  const open_status_code = 'TPN';
30
-
31
-    /**
32
-     * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
33
-     * either due to a technical reason (server or computer crash during registration),
34
-     *  or some other reason that prevent the collection of any useful contact information from any of the registrants
35
-     */
36
-    const failed_status_code = 'TFL';
37
-
38
-    /**
39
-     * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
40
-     * either due to a technical reason (server or computer crash during registration),
41
-     * or due to an abandoned cart after registrant chose not to complete the registration process
42
-     * HOWEVER...
43
-     * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
44
-     * registrant
45
-     */
46
-    const abandoned_status_code = 'TAB';
47
-
48
-    /**
49
-     * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
50
-     * meaning that monies are still owing: TXN_paid < TXN_total
51
-     */
52
-    const incomplete_status_code = 'TIN';
53
-
54
-    /**
55
-     * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
56
-     * meaning that NO monies are owing: TXN_paid == TXN_total
57
-     */
58
-    const complete_status_code = 'TCM';
59
-
60
-    /**
61
-     *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
62
-     *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
63
-     */
64
-    const overpaid_status_code = 'TOP';
65
-
66
-
67
-    /**
68
-     * private constructor to prevent direct creation
69
-     *
70
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
71
-     *                              any incoming timezone data that gets saved). Note this just sends the timezone info
72
-     *                              to the date time model field objects.  Default is NULL (and will be assumed using
73
-     *                              the set timezone in the 'timezone_string' wp option)
74
-     * @throws EE_Error
75
-     * @throws ReflectionException
76
-     */
77
-    protected function __construct(?string $timezone = '')
78
-    {
79
-        $this->singular_item = esc_html__('Transaction', 'event_espresso');
80
-        $this->plural_item   = esc_html__('Transactions', 'event_espresso');
81
-
82
-        $this->_tables                 = [
83
-            'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
84
-        ];
85
-        $this->_fields                 = [
86
-            'TransactionTable' => [
87
-                'TXN_ID'           => new EE_Primary_Key_Int_Field(
88
-                    'TXN_ID', esc_html__('Transaction ID', 'event_espresso')
89
-                ),
90
-                'TXN_timestamp'    => new EE_Datetime_Field(
91
-                    'TXN_timestamp',
92
-                    esc_html__('date when transaction was created', 'event_espresso'),
93
-                    false,
94
-                    EE_Datetime_Field::now,
95
-                    $timezone
96
-                ),
97
-                'TXN_total'        => new EE_Money_Field(
98
-                    'TXN_total',
99
-                    esc_html__('Total value of Transaction', 'event_espresso'),
100
-                    false,
101
-                    0
102
-                ),
103
-                'TXN_paid'         => new EE_Money_Field(
104
-                    'TXN_paid',
105
-                    esc_html__('Amount paid towards transaction to date', 'event_espresso'),
106
-                    false,
107
-                    0
108
-                ),
109
-                'STS_ID'           => new EE_Foreign_Key_String_Field(
110
-                    'STS_ID',
111
-                    esc_html__('Status ID', 'event_espresso'),
112
-                    false,
113
-                    EEM_Transaction::failed_status_code,
114
-                    'Status'
115
-                ),
116
-                'TXN_session_data' => new EE_Serialized_Text_Field(
117
-                    'TXN_session_data',
118
-                    esc_html__('Serialized session data', 'event_espresso'),
119
-                    true,
120
-                    ''
121
-                ),
122
-                'TXN_hash_salt'    => new EE_Plain_Text_Field(
123
-                    'TXN_hash_salt',
124
-                    esc_html__('Transaction Hash Salt', 'event_espresso'),
125
-                    true,
126
-                    ''
127
-                ),
128
-                'PMD_ID'           => new EE_Foreign_Key_Int_Field(
129
-                    'PMD_ID',
130
-                    esc_html__("Last Used Payment Method", 'event_espresso'),
131
-                    true,
132
-                    null,
133
-                    'Payment_Method'
134
-                ),
135
-                'TXN_reg_steps'    => new EE_Serialized_Text_Field(
136
-                    'TXN_reg_steps',
137
-                    esc_html__('Registration Steps', 'event_espresso'),
138
-                    false,
139
-                    []
140
-                ),
141
-            ],
142
-        ];
143
-        $this->_model_relations        = [
144
-            'Registration'   => new EE_Has_Many_Relation(),
145
-            'Payment'        => new EE_Has_Many_Relation(),
146
-            'Status'         => new EE_Belongs_To_Relation(),
147
-            'Line_Item'      => new EE_Has_Many_Relation(false),
148
-            // you can delete a transaction without needing to delete its line items
149
-            'Payment_Method' => new EE_Belongs_To_Relation(),
150
-            'Message'        => new EE_Has_Many_Relation(),
151
-        ];
152
-        $this->_model_chain_to_wp_user = 'Registration.Event';
153
-        parent::__construct($timezone);
154
-    }
155
-
156
-
157
-    /**
158
-     *    txn_status_array
159
-     * get list of transaction statuses
160
-     *
161
-     * @access public
162
-     * @return array
163
-     */
164
-    public static function txn_status_array()
165
-    {
166
-        return apply_filters(
167
-            'FHEE__EEM_Transaction__txn_status_array',
168
-            [
169
-                EEM_Transaction::overpaid_status_code,
170
-                EEM_Transaction::complete_status_code,
171
-                EEM_Transaction::incomplete_status_code,
172
-                EEM_Transaction::abandoned_status_code,
173
-                EEM_Transaction::failed_status_code,
174
-            ]
175
-        );
176
-    }
177
-
178
-
179
-    /**
180
-     *        get the revenue per day  for the Transaction Admin page Reports Tab
181
-     *
182
-     * @access        public
183
-     * @param string $period
184
-     * @return stdClass[]
185
-     * @throws EE_Error
186
-     * @throws EE_Error
187
-     */
188
-    public function get_revenue_per_day_report($period = '-1 month')
189
-    {
190
-        $sql_date = $this->convert_datetime_for_query(
191
-            'TXN_timestamp',
192
-            date('Y-m-d H:i:s', strtotime($period)),
193
-            'Y-m-d H:i:s',
194
-            'UTC'
195
-        );
196
-
197
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
198
-
199
-        return $this->_get_all_wpdb_results(
200
-            [
201
-                [
202
-                    'TXN_timestamp' => ['>=', $sql_date],
203
-                ],
204
-                'group_by' => 'txnDate',
205
-                'order_by' => ['TXN_timestamp' => 'ASC'],
206
-            ],
207
-            OBJECT,
208
-            [
209
-                'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
210
-                'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
211
-            ]
212
-        );
213
-    }
214
-
215
-
216
-    /**
217
-     *        get the revenue per event  for the Transaction Admin page Reports Tab
218
-     *
219
-     * @access        public
220
-     * @param string $period
221
-     * @return EE_Transaction[]
222
-     */
223
-    public function get_revenue_per_event_report($period = '-1 month')
224
-    {
225
-        global $wpdb;
226
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
227
-        $registration_table         = $wpdb->prefix . 'esp_registration';
228
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
229
-        $event_table                = $wpdb->posts;
230
-        $payment_table              = $wpdb->prefix . 'esp_payment';
231
-        $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
232
-        $approved_payment_status    = EEM_Payment::status_id_approved;
233
-        $extra_event_on_join        = '';
234
-        // exclude events not authored by user if permissions in effect
235
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
236
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
237
-        }
238
-
239
-        return $wpdb->get_results(
240
-            "SELECT
21
+	// private instance of the Transaction object
22
+	protected static $_instance;
23
+
24
+	/**
25
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
26
+	 * but payment is pending. This is the state for transactions where payment is promised
27
+	 * from an offline gateway.
28
+	 */
29
+	//  const open_status_code = 'TPN';
30
+
31
+	/**
32
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
33
+	 * either due to a technical reason (server or computer crash during registration),
34
+	 *  or some other reason that prevent the collection of any useful contact information from any of the registrants
35
+	 */
36
+	const failed_status_code = 'TFL';
37
+
38
+	/**
39
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
40
+	 * either due to a technical reason (server or computer crash during registration),
41
+	 * or due to an abandoned cart after registrant chose not to complete the registration process
42
+	 * HOWEVER...
43
+	 * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
44
+	 * registrant
45
+	 */
46
+	const abandoned_status_code = 'TAB';
47
+
48
+	/**
49
+	 * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
50
+	 * meaning that monies are still owing: TXN_paid < TXN_total
51
+	 */
52
+	const incomplete_status_code = 'TIN';
53
+
54
+	/**
55
+	 * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
56
+	 * meaning that NO monies are owing: TXN_paid == TXN_total
57
+	 */
58
+	const complete_status_code = 'TCM';
59
+
60
+	/**
61
+	 *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
62
+	 *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
63
+	 */
64
+	const overpaid_status_code = 'TOP';
65
+
66
+
67
+	/**
68
+	 * private constructor to prevent direct creation
69
+	 *
70
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
71
+	 *                              any incoming timezone data that gets saved). Note this just sends the timezone info
72
+	 *                              to the date time model field objects.  Default is NULL (and will be assumed using
73
+	 *                              the set timezone in the 'timezone_string' wp option)
74
+	 * @throws EE_Error
75
+	 * @throws ReflectionException
76
+	 */
77
+	protected function __construct(?string $timezone = '')
78
+	{
79
+		$this->singular_item = esc_html__('Transaction', 'event_espresso');
80
+		$this->plural_item   = esc_html__('Transactions', 'event_espresso');
81
+
82
+		$this->_tables                 = [
83
+			'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
84
+		];
85
+		$this->_fields                 = [
86
+			'TransactionTable' => [
87
+				'TXN_ID'           => new EE_Primary_Key_Int_Field(
88
+					'TXN_ID', esc_html__('Transaction ID', 'event_espresso')
89
+				),
90
+				'TXN_timestamp'    => new EE_Datetime_Field(
91
+					'TXN_timestamp',
92
+					esc_html__('date when transaction was created', 'event_espresso'),
93
+					false,
94
+					EE_Datetime_Field::now,
95
+					$timezone
96
+				),
97
+				'TXN_total'        => new EE_Money_Field(
98
+					'TXN_total',
99
+					esc_html__('Total value of Transaction', 'event_espresso'),
100
+					false,
101
+					0
102
+				),
103
+				'TXN_paid'         => new EE_Money_Field(
104
+					'TXN_paid',
105
+					esc_html__('Amount paid towards transaction to date', 'event_espresso'),
106
+					false,
107
+					0
108
+				),
109
+				'STS_ID'           => new EE_Foreign_Key_String_Field(
110
+					'STS_ID',
111
+					esc_html__('Status ID', 'event_espresso'),
112
+					false,
113
+					EEM_Transaction::failed_status_code,
114
+					'Status'
115
+				),
116
+				'TXN_session_data' => new EE_Serialized_Text_Field(
117
+					'TXN_session_data',
118
+					esc_html__('Serialized session data', 'event_espresso'),
119
+					true,
120
+					''
121
+				),
122
+				'TXN_hash_salt'    => new EE_Plain_Text_Field(
123
+					'TXN_hash_salt',
124
+					esc_html__('Transaction Hash Salt', 'event_espresso'),
125
+					true,
126
+					''
127
+				),
128
+				'PMD_ID'           => new EE_Foreign_Key_Int_Field(
129
+					'PMD_ID',
130
+					esc_html__("Last Used Payment Method", 'event_espresso'),
131
+					true,
132
+					null,
133
+					'Payment_Method'
134
+				),
135
+				'TXN_reg_steps'    => new EE_Serialized_Text_Field(
136
+					'TXN_reg_steps',
137
+					esc_html__('Registration Steps', 'event_espresso'),
138
+					false,
139
+					[]
140
+				),
141
+			],
142
+		];
143
+		$this->_model_relations        = [
144
+			'Registration'   => new EE_Has_Many_Relation(),
145
+			'Payment'        => new EE_Has_Many_Relation(),
146
+			'Status'         => new EE_Belongs_To_Relation(),
147
+			'Line_Item'      => new EE_Has_Many_Relation(false),
148
+			// you can delete a transaction without needing to delete its line items
149
+			'Payment_Method' => new EE_Belongs_To_Relation(),
150
+			'Message'        => new EE_Has_Many_Relation(),
151
+		];
152
+		$this->_model_chain_to_wp_user = 'Registration.Event';
153
+		parent::__construct($timezone);
154
+	}
155
+
156
+
157
+	/**
158
+	 *    txn_status_array
159
+	 * get list of transaction statuses
160
+	 *
161
+	 * @access public
162
+	 * @return array
163
+	 */
164
+	public static function txn_status_array()
165
+	{
166
+		return apply_filters(
167
+			'FHEE__EEM_Transaction__txn_status_array',
168
+			[
169
+				EEM_Transaction::overpaid_status_code,
170
+				EEM_Transaction::complete_status_code,
171
+				EEM_Transaction::incomplete_status_code,
172
+				EEM_Transaction::abandoned_status_code,
173
+				EEM_Transaction::failed_status_code,
174
+			]
175
+		);
176
+	}
177
+
178
+
179
+	/**
180
+	 *        get the revenue per day  for the Transaction Admin page Reports Tab
181
+	 *
182
+	 * @access        public
183
+	 * @param string $period
184
+	 * @return stdClass[]
185
+	 * @throws EE_Error
186
+	 * @throws EE_Error
187
+	 */
188
+	public function get_revenue_per_day_report($period = '-1 month')
189
+	{
190
+		$sql_date = $this->convert_datetime_for_query(
191
+			'TXN_timestamp',
192
+			date('Y-m-d H:i:s', strtotime($period)),
193
+			'Y-m-d H:i:s',
194
+			'UTC'
195
+		);
196
+
197
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
198
+
199
+		return $this->_get_all_wpdb_results(
200
+			[
201
+				[
202
+					'TXN_timestamp' => ['>=', $sql_date],
203
+				],
204
+				'group_by' => 'txnDate',
205
+				'order_by' => ['TXN_timestamp' => 'ASC'],
206
+			],
207
+			OBJECT,
208
+			[
209
+				'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
210
+				'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
211
+			]
212
+		);
213
+	}
214
+
215
+
216
+	/**
217
+	 *        get the revenue per event  for the Transaction Admin page Reports Tab
218
+	 *
219
+	 * @access        public
220
+	 * @param string $period
221
+	 * @return EE_Transaction[]
222
+	 */
223
+	public function get_revenue_per_event_report($period = '-1 month')
224
+	{
225
+		global $wpdb;
226
+		$transaction_table          = $wpdb->prefix . 'esp_transaction';
227
+		$registration_table         = $wpdb->prefix . 'esp_registration';
228
+		$registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
229
+		$event_table                = $wpdb->posts;
230
+		$payment_table              = $wpdb->prefix . 'esp_payment';
231
+		$sql_date                   = date('Y-m-d H:i:s', strtotime($period));
232
+		$approved_payment_status    = EEM_Payment::status_id_approved;
233
+		$extra_event_on_join        = '';
234
+		// exclude events not authored by user if permissions in effect
235
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
236
+			$extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
237
+		}
238
+
239
+		return $wpdb->get_results(
240
+			"SELECT
241 241
 			Transaction_Event.event_name AS event_name,
242 242
 			SUM(Transaction_Event.paid) AS revenue
243 243
 			FROM
@@ -265,232 +265,232 @@  discard block
 block discarded – undo
265 265
 					$extra_event_on_join
266 266
 				) AS Transaction_Event
267 267
 			GROUP BY event_name"
268
-        );
269
-    }
270
-
271
-
272
-    /**
273
-     * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
274
-     * request global variable. Either way, tries to find the current transaction (through
275
-     * the registration pointed to by reg_url_link), if not returns null
276
-     *
277
-     * @param string $reg_url_link
278
-     * @return EE_Transaction
279
-     * @throws EE_Error
280
-     */
281
-    public function get_transaction_from_reg_url_link($reg_url_link = '')
282
-    {
283
-        if (empty($reg_url_link)) {
284
-            $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
285
-            $reg_url_link = $request->getRequestParam('e_reg_url_link');
286
-        }
287
-        return $this->get_one(
288
-            [
289
-                [
290
-                    'Registration.REG_url_link' => $reg_url_link,
291
-                ],
292
-            ]
293
-        );
294
-    }
295
-
296
-
297
-    /**
298
-     * Updates the provided EE_Transaction with all the applicable payments
299
-     * (or fetch the EE_Transaction from its ID)
300
-     *
301
-     * @param EE_Transaction|int $transaction_obj_or_id
302
-     * @param boolean            $save_txn whether or not to save the transaction during this function call
303
-     * @return array
304
-     * @throws EE_Error
305
-     * @throws ReflectionException
306
-     * @deprecated
307
-     */
308
-    public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
309
-    {
310
-        EE_Error::doing_it_wrong(
311
-            __CLASS__ . '::' . __FUNCTION__,
312
-            sprintf(
313
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
314
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
315
-            ),
316
-            '4.6.0'
317
-        );
318
-        /** @type EE_Transaction_Processor $transaction_processor */
319
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
320
-
321
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
322
-            $this->ensure_is_obj($transaction_obj_or_id)
323
-        );
324
-    }
325
-
326
-
327
-    /**
328
-     * Deletes "junk" transactions that were probably added by bots. There might be TONS
329
-     * of these, so we are very careful to NOT select (which the models do even when deleting),
330
-     * and so we only use wpdb directly and only do minimal joins.
331
-     * Transactions are considered "junk" if they're failed for longer than a week.
332
-     * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
333
-     * it, it's probably not junk (regardless of what status it has).
334
-     * The downside to this approach is that is addons are listening for object deletions
335
-     * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
336
-     * to catch these types of deletions.
337
-     *
338
-     * @return int
339
-     * @throws EE_Error
340
-     * @throws EE_Error
341
-     * @global WPDB $wpdb
342
-     */
343
-    public function delete_junk_transactions()
344
-    {
345
-        global $wpdb;
346
-        $deleted             = false;
347
-        $time_to_leave_alone = (int) apply_filters(
348
-            'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
349
-            WEEK_IN_SECONDS
350
-        );
351
-
352
-
353
-        /**
354
-         * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
355
-         * Useful for plugins that want to exclude transactions matching certain query parameters.
356
-         * The query parameters should be in the format accepted by the EEM_Base model queries.
357
-         */
358
-        $ids_query = apply_filters(
359
-            'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
360
-            [
361
-                0          => [
362
-                    'STS_ID'         => EEM_Transaction::failed_status_code,
363
-                    'Payment.PAY_ID' => ['IS NULL'],
364
-                    'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
365
-                ],
366
-                'order_by' => ['TXN_timestamp' => 'ASC'],
367
-                'limit'    => 1000,
368
-            ],
369
-            $time_to_leave_alone
370
-        );
371
-
372
-
373
-        /**
374
-         * This filter is for when code needs to filter the list of transaction ids that represent transactions
375
-         * about to be deleted based on some other criteria that isn't easily done via the query args filter.
376
-         */
377
-        $txn_ids = apply_filters(
378
-            'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
379
-            EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
380
-            $time_to_leave_alone
381
-        );
382
-        // now that we have the ids to delete
383
-        if (! empty($txn_ids) && is_array($txn_ids)) {
384
-            // first, make sure these TXN's are removed the "ee_locked_transactions" array
385
-            EEM_Transaction::unset_locked_transactions($txn_ids);
386
-
387
-            // Create IDs placeholder.
388
-            $placeholders = array_fill(0, count($txn_ids), '%d');
389
-
390
-            // Glue it together to use inside $wpdb->prepare.
391
-            $format = implode(', ', $placeholders);
392
-
393
-            // let's get deleting...
394
-            // We got the ids from the original query to get them FROM
395
-            // the db (which is sanitized) so no need to prepare them again.
396
-            $query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
397
-            $deleted = $wpdb->query($query);
398
-        }
399
-        if ($deleted) {
400
-            /**
401
-             * Allows code to do something after the transactions have been deleted.
402
-             */
403
-            do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
404
-        }
405
-
406
-        return $deleted;
407
-    }
408
-
409
-
410
-    /**
411
-     * @param array $transaction_IDs
412
-     * @return bool
413
-     */
414
-    public static function unset_locked_transactions(array $transaction_IDs)
415
-    {
416
-        $locked_transactions = get_option('ee_locked_transactions', []);
417
-        $update              = false;
418
-        foreach ($transaction_IDs as $TXN_ID) {
419
-            if (isset($locked_transactions[ $TXN_ID ])) {
420
-                unset($locked_transactions[ $TXN_ID ]);
421
-                $update = true;
422
-            }
423
-        }
424
-        if ($update) {
425
-            update_option('ee_locked_transactions', $locked_transactions);
426
-        }
427
-
428
-        return $update;
429
-    }
430
-
431
-
432
-    /**
433
-     * returns an array of EE_Transaction objects whose timestamp is greater than
434
-     * the current time minus the session lifespan, which defaults to 60 minutes
435
-     *
436
-     * @return EE_Base_Class[]|EE_Transaction[]
437
-     * @throws EE_Error
438
-     * @throws InvalidArgumentException
439
-     * @throws InvalidDataTypeException
440
-     * @throws InvalidInterfaceException
441
-     */
442
-    public function get_transactions_in_progress()
443
-    {
444
-        return $this->_get_transactions_in_progress();
445
-    }
446
-
447
-
448
-    /**
449
-     * returns an array of EE_Transaction objects whose timestamp is less than
450
-     * the current time minus the session lifespan, which defaults to 60 minutes
451
-     *
452
-     * @return EE_Base_Class[]|EE_Transaction[]
453
-     * @throws EE_Error
454
-     * @throws InvalidArgumentException
455
-     * @throws InvalidDataTypeException
456
-     * @throws InvalidInterfaceException
457
-     */
458
-    public function get_transactions_not_in_progress()
459
-    {
460
-        return $this->_get_transactions_in_progress('<=');
461
-    }
462
-
463
-
464
-    /**
465
-     * @param string $comparison
466
-     * @return EE_Transaction[]
467
-     * @throws EE_Error
468
-     * @throws InvalidArgumentException
469
-     * @throws InvalidDataTypeException
470
-     * @throws InvalidInterfaceException
471
-     */
472
-    private function _get_transactions_in_progress($comparison = '>=')
473
-    {
474
-        $comparison = $comparison === '>=' || $comparison === '<='
475
-            ? $comparison
476
-            : '>=';
477
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
478
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
479
-            'EventEspresso\core\domain\values\session\SessionLifespan'
480
-        );
481
-        return $this->get_all(
482
-            [
483
-                [
484
-                    'TXN_timestamp' => [
485
-                        $comparison,
486
-                        $session_lifespan->expiration(),
487
-                    ],
488
-                    'STS_ID'        => [
489
-                        '!=',
490
-                        EEM_Transaction::complete_status_code,
491
-                    ],
492
-                ],
493
-            ]
494
-        );
495
-    }
268
+		);
269
+	}
270
+
271
+
272
+	/**
273
+	 * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
274
+	 * request global variable. Either way, tries to find the current transaction (through
275
+	 * the registration pointed to by reg_url_link), if not returns null
276
+	 *
277
+	 * @param string $reg_url_link
278
+	 * @return EE_Transaction
279
+	 * @throws EE_Error
280
+	 */
281
+	public function get_transaction_from_reg_url_link($reg_url_link = '')
282
+	{
283
+		if (empty($reg_url_link)) {
284
+			$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
285
+			$reg_url_link = $request->getRequestParam('e_reg_url_link');
286
+		}
287
+		return $this->get_one(
288
+			[
289
+				[
290
+					'Registration.REG_url_link' => $reg_url_link,
291
+				],
292
+			]
293
+		);
294
+	}
295
+
296
+
297
+	/**
298
+	 * Updates the provided EE_Transaction with all the applicable payments
299
+	 * (or fetch the EE_Transaction from its ID)
300
+	 *
301
+	 * @param EE_Transaction|int $transaction_obj_or_id
302
+	 * @param boolean            $save_txn whether or not to save the transaction during this function call
303
+	 * @return array
304
+	 * @throws EE_Error
305
+	 * @throws ReflectionException
306
+	 * @deprecated
307
+	 */
308
+	public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
309
+	{
310
+		EE_Error::doing_it_wrong(
311
+			__CLASS__ . '::' . __FUNCTION__,
312
+			sprintf(
313
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
314
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
315
+			),
316
+			'4.6.0'
317
+		);
318
+		/** @type EE_Transaction_Processor $transaction_processor */
319
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
320
+
321
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
322
+			$this->ensure_is_obj($transaction_obj_or_id)
323
+		);
324
+	}
325
+
326
+
327
+	/**
328
+	 * Deletes "junk" transactions that were probably added by bots. There might be TONS
329
+	 * of these, so we are very careful to NOT select (which the models do even when deleting),
330
+	 * and so we only use wpdb directly and only do minimal joins.
331
+	 * Transactions are considered "junk" if they're failed for longer than a week.
332
+	 * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
333
+	 * it, it's probably not junk (regardless of what status it has).
334
+	 * The downside to this approach is that is addons are listening for object deletions
335
+	 * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
336
+	 * to catch these types of deletions.
337
+	 *
338
+	 * @return int
339
+	 * @throws EE_Error
340
+	 * @throws EE_Error
341
+	 * @global WPDB $wpdb
342
+	 */
343
+	public function delete_junk_transactions()
344
+	{
345
+		global $wpdb;
346
+		$deleted             = false;
347
+		$time_to_leave_alone = (int) apply_filters(
348
+			'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
349
+			WEEK_IN_SECONDS
350
+		);
351
+
352
+
353
+		/**
354
+		 * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
355
+		 * Useful for plugins that want to exclude transactions matching certain query parameters.
356
+		 * The query parameters should be in the format accepted by the EEM_Base model queries.
357
+		 */
358
+		$ids_query = apply_filters(
359
+			'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
360
+			[
361
+				0          => [
362
+					'STS_ID'         => EEM_Transaction::failed_status_code,
363
+					'Payment.PAY_ID' => ['IS NULL'],
364
+					'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
365
+				],
366
+				'order_by' => ['TXN_timestamp' => 'ASC'],
367
+				'limit'    => 1000,
368
+			],
369
+			$time_to_leave_alone
370
+		);
371
+
372
+
373
+		/**
374
+		 * This filter is for when code needs to filter the list of transaction ids that represent transactions
375
+		 * about to be deleted based on some other criteria that isn't easily done via the query args filter.
376
+		 */
377
+		$txn_ids = apply_filters(
378
+			'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
379
+			EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
380
+			$time_to_leave_alone
381
+		);
382
+		// now that we have the ids to delete
383
+		if (! empty($txn_ids) && is_array($txn_ids)) {
384
+			// first, make sure these TXN's are removed the "ee_locked_transactions" array
385
+			EEM_Transaction::unset_locked_transactions($txn_ids);
386
+
387
+			// Create IDs placeholder.
388
+			$placeholders = array_fill(0, count($txn_ids), '%d');
389
+
390
+			// Glue it together to use inside $wpdb->prepare.
391
+			$format = implode(', ', $placeholders);
392
+
393
+			// let's get deleting...
394
+			// We got the ids from the original query to get them FROM
395
+			// the db (which is sanitized) so no need to prepare them again.
396
+			$query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
397
+			$deleted = $wpdb->query($query);
398
+		}
399
+		if ($deleted) {
400
+			/**
401
+			 * Allows code to do something after the transactions have been deleted.
402
+			 */
403
+			do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
404
+		}
405
+
406
+		return $deleted;
407
+	}
408
+
409
+
410
+	/**
411
+	 * @param array $transaction_IDs
412
+	 * @return bool
413
+	 */
414
+	public static function unset_locked_transactions(array $transaction_IDs)
415
+	{
416
+		$locked_transactions = get_option('ee_locked_transactions', []);
417
+		$update              = false;
418
+		foreach ($transaction_IDs as $TXN_ID) {
419
+			if (isset($locked_transactions[ $TXN_ID ])) {
420
+				unset($locked_transactions[ $TXN_ID ]);
421
+				$update = true;
422
+			}
423
+		}
424
+		if ($update) {
425
+			update_option('ee_locked_transactions', $locked_transactions);
426
+		}
427
+
428
+		return $update;
429
+	}
430
+
431
+
432
+	/**
433
+	 * returns an array of EE_Transaction objects whose timestamp is greater than
434
+	 * the current time minus the session lifespan, which defaults to 60 minutes
435
+	 *
436
+	 * @return EE_Base_Class[]|EE_Transaction[]
437
+	 * @throws EE_Error
438
+	 * @throws InvalidArgumentException
439
+	 * @throws InvalidDataTypeException
440
+	 * @throws InvalidInterfaceException
441
+	 */
442
+	public function get_transactions_in_progress()
443
+	{
444
+		return $this->_get_transactions_in_progress();
445
+	}
446
+
447
+
448
+	/**
449
+	 * returns an array of EE_Transaction objects whose timestamp is less than
450
+	 * the current time minus the session lifespan, which defaults to 60 minutes
451
+	 *
452
+	 * @return EE_Base_Class[]|EE_Transaction[]
453
+	 * @throws EE_Error
454
+	 * @throws InvalidArgumentException
455
+	 * @throws InvalidDataTypeException
456
+	 * @throws InvalidInterfaceException
457
+	 */
458
+	public function get_transactions_not_in_progress()
459
+	{
460
+		return $this->_get_transactions_in_progress('<=');
461
+	}
462
+
463
+
464
+	/**
465
+	 * @param string $comparison
466
+	 * @return EE_Transaction[]
467
+	 * @throws EE_Error
468
+	 * @throws InvalidArgumentException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws InvalidInterfaceException
471
+	 */
472
+	private function _get_transactions_in_progress($comparison = '>=')
473
+	{
474
+		$comparison = $comparison === '>=' || $comparison === '<='
475
+			? $comparison
476
+			: '>=';
477
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
478
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
479
+			'EventEspresso\core\domain\values\session\SessionLifespan'
480
+		);
481
+		return $this->get_all(
482
+			[
483
+				[
484
+					'TXN_timestamp' => [
485
+						$comparison,
486
+						$session_lifespan->expiration(),
487
+					],
488
+					'STS_ID'        => [
489
+						'!=',
490
+						EEM_Transaction::complete_status_code,
491
+					],
492
+				],
493
+			]
494
+		);
495
+	}
496 496
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Message_Template_Group.model.php 2 patches
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -13,437 +13,437 @@
 block discarded – undo
13 13
  */
14 14
 class EEM_Message_Template_Group extends EEM_Soft_Delete_Base
15 15
 {
16
-    // private instance of the EEM_Message_Template_Group object
17
-    protected static $_instance = null;
18
-
19
-
20
-    /**
21
-     * @param string|null $timezone
22
-     * @throws EE_Error
23
-     */
24
-    protected function __construct(?string $timezone = '')
25
-    {
26
-        $this->singular_item    = esc_html__('Message Template Group', 'event_espresso');
27
-        $this->plural_item      = esc_html__('Message Template Groups', 'event_espresso');
28
-        $this->_tables          = [
29
-            'Message_Template_Group' => new EE_Primary_Table('esp_message_template_group', 'GRP_ID'),
30
-        ];
31
-        $this->_fields          = [
32
-            'Message_Template_Group' => [
33
-                'GRP_ID'           => new EE_Primary_Key_Int_Field(
34
-                    'GRP_ID',
35
-                    esc_html__('Message Template Group ID', 'event_espresso')
36
-                ),
37
-                'MTP_name'         => new EE_Plain_Text_Field(
38
-                    'MTP_name',
39
-                    esc_html__('The name of the template group', 'event_espresso'),
40
-                    false,
41
-                    ''
42
-                ),
43
-                'MTP_description'  => new EE_Simple_HTML_Field(
44
-                    'MTP_description',
45
-                    esc_html__(
46
-                        'A brief description about this template.',
47
-                        'event_espresso'
48
-                    ),
49
-                    false,
50
-                    ''
51
-                ),
52
-                'MTP_user_id'      => new EE_WP_User_Field(
53
-                    'MTP_user_id',
54
-                    esc_html__('Template Creator ID', 'event_espresso'),
55
-                    false
56
-                ),
57
-                'MTP_messenger'    => new EE_Plain_Text_Field(
58
-                    'MTP_messenger',
59
-                    esc_html__(
60
-                        'Messenger Used for Template',
61
-                        'event_espresso'
62
-                    ),
63
-                    false,
64
-                    'email'
65
-                ),
66
-                'MTP_message_type' => new EE_Plain_Text_Field(
67
-                    'MTP_message_type',
68
-                    esc_html__('Message Type', 'event_espresso'),
69
-                    false,
70
-                    'registration'
71
-                ),
72
-                'MTP_is_global'    => new EE_Boolean_Field(
73
-                    'MTP_is_global',
74
-                    esc_html__(
75
-                        'Flag indicating if Template Group is Global',
76
-                        'event_espresso'
77
-                    ),
78
-                    false,
79
-                    true
80
-                ),
81
-                'MTP_is_override'  => new EE_Boolean_Field(
82
-                    'MTP_is_override',
83
-                    esc_html__(
84
-                        'Flag indicating if Template Group overrides any other Templates for the messenger/messagetype combination',
85
-                        'event_espresso'
86
-                    ),
87
-                    false,
88
-                    false
89
-                ),
90
-                'MTP_deleted'      => new EE_Trashed_Flag_Field(
91
-                    'MTP_deleted',
92
-                    esc_html__(
93
-                        'Flag indicating whether this has been trashed',
94
-                        'event_espresso'
95
-                    ),
96
-                    false,
97
-                    false
98
-                ),
99
-                'MTP_is_active'    => new EE_Boolean_Field(
100
-                    'MTP_is_active',
101
-                    esc_html__(
102
-                        'Flag indicating whether template group is active',
103
-                        'event_espresso'
104
-                    ),
105
-                    false,
106
-                    true
107
-                ),
108
-            ],
109
-        ];
110
-        $this->_model_relations = [
111
-            'Message_Template' => new EE_Has_Many_Relation(),
112
-            'Message'          => new EE_Has_Many_Relation(),
113
-            'Event'            => new EE_HABTM_Relation('Event_Message_Template'),
114
-            'WP_User'          => new EE_Belongs_To_Relation(),
115
-        ];
116
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
117
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_Global('MTP_is_global');
118
-        }
119
-        $this->_caps_slug = 'messages';
120
-
121
-        parent::__construct($timezone);
122
-    }
123
-
124
-
125
-    /**
126
-     * get_all_trashed_message_templates_by_event
127
-     *
128
-     * @access public
129
-     * @param int    $EVT_ID specific event id
130
-     * @param string $orderby
131
-     * @param string $order
132
-     * @param null   $limit
133
-     * @param bool   $count
134
-     * @return array message template objects that are attached to a specific event.
135
-     */
136
-    public function get_all_trashed_message_templates_by_event(
137
-        $EVT_ID,
138
-        $orderby = 'GRP_ID',
139
-        $order = 'ASC',
140
-        $limit = null,
141
-        $count = false
142
-    ) {
143
-        $query_params = [['Event.EVT_ID' => $EVT_ID], 'order_by' => [$orderby => $order], 'limit' => $limit];
144
-        return $count ? $this->count_deleted($query_params, 'GRP_ID', true) : $this->get_all_deleted($query_params);
145
-    }
146
-
147
-
148
-    /**
149
-     * get_all_message_templates_by_messenger
150
-     *
151
-     * @access public
152
-     * @param        $messenger
153
-     * @param string $orderby
154
-     * @param string $order
155
-     * @return array all (including trashed or inactive) message template group objects for the given messenger
156
-     */
157
-    public function get_all_message_templates_by_messenger($messenger, $orderby = 'GRP_ID', $order = 'ASC')
158
-    {
159
-        return $this->get_all_deleted_and_undeleted(
160
-            [['MTP_messenger' => $messenger], 'order_by' => [$orderby => $order]]
161
-        );
162
-    }
163
-
164
-
165
-    /**
166
-     * This simply adds on any messenger/message type filters that may be present in the request
167
-     *
168
-     * @param array $_where any existing where conditions to append these to.
169
-     * @return array          original where conditions or original with additional filters.
170
-     */
171
-    protected function _maybe_mtp_filters($_where = [])
172
-    {
173
-        /** @var RequestInterface $request */
174
-        $request   = LoaderFactory::getLoader()->getShared(RequestInterface::class);
175
-        $messenger = $request->getRequestParam('ee_messenger_filter_by');
176
-        // account for messenger or message type filters
177
-        if ($messenger !== '' && $messenger !== 'none_selected' && $messenger !== 'all') {
178
-            $_where['MTP_messenger'] = $messenger;
179
-        }
180
-        $message_type = $request->getRequestParam('ee_message_type_filter_by');
181
-        if (
182
-            $message_type !== '' && $message_type !== 'none_selected'
183
-        ) {
184
-            $_where['MTP_message_type'] = $message_type;
185
-        }
186
-
187
-        return $_where;
188
-    }
189
-
190
-
191
-    /**
192
-     * get_all_active_message_templates groups
193
-     *
194
-     * @access public
195
-     * @param string $orderby
196
-     * @param string $order
197
-     * @param null   $limit
198
-     * @param bool   $count
199
-     * @param bool   $global
200
-     * @param bool   $user_check
201
-     * @return array|int all active (non_trashed, active) message template objects
202
-     */
203
-    public function get_all_active_message_templates(
204
-        $orderby = 'GRP_ID',
205
-        $order = 'ASC',
206
-        $limit = null,
207
-        $count = false,
208
-        $global = true,
209
-        $user_check = false
210
-    ) {
211
-        $_where                  = $global ? ['MTP_is_global' => true] : ['MTP_is_global' => false];
212
-        $_where['MTP_is_active'] = true;
213
-        $_where                  = $this->_maybe_mtp_filters($_where);
214
-
215
-        if (
216
-            $user_check
217
-            && ! $global
218
-            && ! EE_Registry::instance()->CAP->current_user_can(
219
-                'ee_read_others_messages',
220
-                'get_all_active_message_templates'
221
-            )
222
-        ) {
223
-            $_where['MTP_user_id'] = get_current_user_id();
224
-        }
225
-
226
-        $query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
227
-
228
-        return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
229
-    }
230
-
231
-
232
-    /**
233
-     *    retrieve ALL message_template groups from db regardless of wht
234
-     *
235
-     * @access    public
236
-     * @param string $orderby
237
-     * @param string $order
238
-     * @param null   $limit
239
-     * @param bool   $count
240
-     * @return mixed array on success, FALSE on fail
241
-     */
242
-    public function get_all_message_templates($orderby = 'GRP_ID', $order = 'ASC', $limit = null, $count = false)
243
-    {
244
-        $_where = $this->_maybe_mtp_filters();
245
-
246
-        $query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
247
-
248
-        $r_templates = $count
249
-            ? $this->count_deleted_and_undeleted($query_params, 'GRP_ID', true)
250
-            : $this->get_all_deleted_and_undeleted($query_params);
251
-
252
-        return $r_templates;
253
-    }
254
-
255
-
256
-    /**
257
-     * This gets all the custom templates attached to a specific event
258
-     *
259
-     * @param int   $EVT_ID       event id
260
-     * @param array $query_params @see
261
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
262
-     * @return  EE_Message_Template_Group[]
263
-     */
264
-    public function get_all_custom_templates_by_event($EVT_ID, $query_params = [])
265
-    {
266
-        $where = array_merge($query_params, ['Event.EVT_ID' => $EVT_ID]);
267
-        return $this->get_all(
268
-            [$where]
269
-        );
270
-    }
271
-
272
-
273
-    /**
274
-     * get_all_trashed_grouped_message_templates
275
-     * this returns ONLY the template groups where ALL contexts are trashed and none of the group are non-trashed
276
-     *
277
-     * @access public
278
-     * @param string $orderby
279
-     * @param string $order
280
-     * @param null   $limit
281
-     * @param bool   $count
282
-     * @param bool   $global
283
-     * @return array|int EE_Message_Template_Group[] message template groups.
284
-     */
285
-    public function get_all_trashed_grouped_message_templates(
286
-        $orderby = 'GRP_ID',
287
-        $order = 'ASC',
288
-        $limit = null,
289
-        $count = false,
290
-        $global = true
291
-    ) {
292
-        $_where                  = $global ? ['MTP_is_global' => true] : ['MTP_is_global' => false];
293
-        $_where['MTP_is_active'] = true;
294
-        $_where                  = $this->_maybe_mtp_filters($_where);
295
-
296
-        $query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
297
-
298
-        return $count ? $this->count_deleted($query_params, 'GRP_ID', true) : $this->get_all_deleted($query_params);
299
-    }
300
-
301
-
302
-    /**
303
-     * this returns the message template group(s) for a given event, messenger, and message template
304
-     *
305
-     * @param string              $messenger
306
-     * @param string              $message_type
307
-     * @param                     $evt_id
308
-     * @param string              $orderby pointless at this point but still included
309
-     * @param string              $order
310
-     * @param mixed (array|null) $limit   array($offset, $num)
311
-     * @param bool                $count   true = just return count, false = objects
312
-     * @param bool                $active  ignore "active" or not. (default only return active)
313
-     * @return \mixed[]) depending on $count.
314
-     */
315
-    public function get_event_message_templates_by_m_and_mt_and_evt(
316
-        $messenger,
317
-        $message_type,
318
-        $evt_id,
319
-        $orderby = 'GRP_ID',
320
-        $order = 'ASC',
321
-        $limit = null,
322
-        $count = false,
323
-        $active = true
324
-    ) {
325
-        $_where = [
326
-            'MTP_messenger'    => $messenger,
327
-            'MTP_message_type' => $message_type,
328
-            'Event.EVT_ID'     => $evt_id,
329
-            'MTP_is_global'    => true,
330
-            'MTP_is_active'    => $active,
331
-        ];
332
-
333
-        $query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
334
-
335
-        return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
336
-    }
337
-
338
-
339
-    /**
340
-     * get all GLOBAL message template groups for the given messenger and message type
341
-     *
342
-     * @param string $messenger     slug for messenger
343
-     * @param string $message_type  slug for message type
344
-     * @param string $orderby       what column to orderby
345
-     * @param string $order         ASC or DESC
346
-     * @param mixed (array|null) $limit array($offset, $num)
347
-     * @param bool   $count         true = just return count, false = objects
348
-     * @param bool   $active        ignore "active" or not. (default only return active) -
349
-     *                              'all' means return both inactive AND inactive.
350
-     * @return array               message template objects that are global (i.e. non-event)
351
-     */
352
-    public function get_global_message_template_by_m_and_mt(
353
-        $messenger,
354
-        $message_type,
355
-        $orderby = 'GRP_ID',
356
-        $order = 'ASC',
357
-        $limit = null,
358
-        $count = false,
359
-        $active = true
360
-    ) {
361
-        $_where = [
362
-            'MTP_messenger'    => $messenger,
363
-            'MTP_message_type' => $message_type,
364
-            'MTP_is_global'    => true,
365
-        ];
366
-
367
-        if ($active != 'all') {
368
-            $_where['MTP_is_active'] = $active;
369
-        }
370
-
371
-        $query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
372
-
373
-        return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
374
-    }
375
-
376
-
377
-    /**
378
-     * get all custom message template groups for the given messenger and message type
379
-     *
380
-     * @param string $messenger    messenger
381
-     * @param string $message_type messagetype
382
-     * @param array  $query_params same as EEM_Base->get_all()
383
-     * @return EE_Message_Template_Group[]
384
-     */
385
-    public function get_custom_message_template_by_m_and_mt($messenger, $message_type, $query_params = [])
386
-    {
387
-        return $this->get_all(
388
-            array_merge(
389
-                $query_params,
390
-                [
391
-                    [
392
-                        'MTP_is_global'    => false,
393
-                        'MTP_messenger'    => $messenger,
394
-                        'MTP_message_type' => $message_type,
395
-                    ],
396
-                ]
397
-            )
398
-        );
399
-    }
400
-
401
-
402
-    /**
403
-     * This sends things to the validator for the given messenger and message type.
404
-     *
405
-     * @param array  $fields       the incoming fields to check.
406
-     *                             Note this array is in the formatted fields from the form fields setup.
407
-     *                             So we need to reformat this into an array of expected field refs by the validator.
408
-     *                             Note also that this is not only the fields for the Message Template Group
409
-     *                             but ALSO for Message Template.
410
-     * @param string $context      The context the fields were obtained from.
411
-     * @param string $messenger    The messenger we are validating
412
-     * @param string $message_type The message type we are validating.
413
-     * @return bool
414
-     * @throws DomainException
415
-     */
416
-    public function validate(array $fields, string $context, string $messenger, string $message_type): bool
417
-    {
418
-        /** @var MessageTemplateValidator $validator */
419
-        $validator = LoaderFactory::getShared(MessageTemplateValidator::class);
420
-        return $validator->validateTemplateFields($messenger, $message_type, $context, $fields);
421
-    }
422
-
423
-
424
-    /**
425
-     * Updates all message template groups matching the incoming arguments to inactive status.
426
-     *
427
-     * @param array $messenger_names    The messenger slugs.
428
-     *                                  If empty then all templates matching the message types are marked inactive.
429
-     *                                  Otherwise only templates matching the messengers and message types.
430
-     * @param array $message_type_names The message type slugs.
431
-     *                                  If empty then all templates matching the messengers are marked inactive.
432
-     *                                  Otherwise only templates matching the messengers and message types.
433
-     * @return int  count of updated records.
434
-     */
435
-    public function deactivate_message_template_groups_for($messenger_names = [], $message_type_names = [])
436
-    {
437
-        $query_args = [];
438
-        if (empty($messenger_names) && empty($message_type_names)) {
439
-            return 0;
440
-        }
441
-        if (! empty($messenger_names)) {
442
-            $query_args[0]['MTP_messenger'] = ['IN', (array) $messenger_names];
443
-        }
444
-        if (! empty($message_type_names)) {
445
-            $query_args[0]['MTP_message_type'] = ['IN', (array) $message_type_names];
446
-        }
447
-        return $this->update(['MTP_is_active' => false], $query_args);
448
-    }
16
+	// private instance of the EEM_Message_Template_Group object
17
+	protected static $_instance = null;
18
+
19
+
20
+	/**
21
+	 * @param string|null $timezone
22
+	 * @throws EE_Error
23
+	 */
24
+	protected function __construct(?string $timezone = '')
25
+	{
26
+		$this->singular_item    = esc_html__('Message Template Group', 'event_espresso');
27
+		$this->plural_item      = esc_html__('Message Template Groups', 'event_espresso');
28
+		$this->_tables          = [
29
+			'Message_Template_Group' => new EE_Primary_Table('esp_message_template_group', 'GRP_ID'),
30
+		];
31
+		$this->_fields          = [
32
+			'Message_Template_Group' => [
33
+				'GRP_ID'           => new EE_Primary_Key_Int_Field(
34
+					'GRP_ID',
35
+					esc_html__('Message Template Group ID', 'event_espresso')
36
+				),
37
+				'MTP_name'         => new EE_Plain_Text_Field(
38
+					'MTP_name',
39
+					esc_html__('The name of the template group', 'event_espresso'),
40
+					false,
41
+					''
42
+				),
43
+				'MTP_description'  => new EE_Simple_HTML_Field(
44
+					'MTP_description',
45
+					esc_html__(
46
+						'A brief description about this template.',
47
+						'event_espresso'
48
+					),
49
+					false,
50
+					''
51
+				),
52
+				'MTP_user_id'      => new EE_WP_User_Field(
53
+					'MTP_user_id',
54
+					esc_html__('Template Creator ID', 'event_espresso'),
55
+					false
56
+				),
57
+				'MTP_messenger'    => new EE_Plain_Text_Field(
58
+					'MTP_messenger',
59
+					esc_html__(
60
+						'Messenger Used for Template',
61
+						'event_espresso'
62
+					),
63
+					false,
64
+					'email'
65
+				),
66
+				'MTP_message_type' => new EE_Plain_Text_Field(
67
+					'MTP_message_type',
68
+					esc_html__('Message Type', 'event_espresso'),
69
+					false,
70
+					'registration'
71
+				),
72
+				'MTP_is_global'    => new EE_Boolean_Field(
73
+					'MTP_is_global',
74
+					esc_html__(
75
+						'Flag indicating if Template Group is Global',
76
+						'event_espresso'
77
+					),
78
+					false,
79
+					true
80
+				),
81
+				'MTP_is_override'  => new EE_Boolean_Field(
82
+					'MTP_is_override',
83
+					esc_html__(
84
+						'Flag indicating if Template Group overrides any other Templates for the messenger/messagetype combination',
85
+						'event_espresso'
86
+					),
87
+					false,
88
+					false
89
+				),
90
+				'MTP_deleted'      => new EE_Trashed_Flag_Field(
91
+					'MTP_deleted',
92
+					esc_html__(
93
+						'Flag indicating whether this has been trashed',
94
+						'event_espresso'
95
+					),
96
+					false,
97
+					false
98
+				),
99
+				'MTP_is_active'    => new EE_Boolean_Field(
100
+					'MTP_is_active',
101
+					esc_html__(
102
+						'Flag indicating whether template group is active',
103
+						'event_espresso'
104
+					),
105
+					false,
106
+					true
107
+				),
108
+			],
109
+		];
110
+		$this->_model_relations = [
111
+			'Message_Template' => new EE_Has_Many_Relation(),
112
+			'Message'          => new EE_Has_Many_Relation(),
113
+			'Event'            => new EE_HABTM_Relation('Event_Message_Template'),
114
+			'WP_User'          => new EE_Belongs_To_Relation(),
115
+		];
116
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
117
+			$this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_Global('MTP_is_global');
118
+		}
119
+		$this->_caps_slug = 'messages';
120
+
121
+		parent::__construct($timezone);
122
+	}
123
+
124
+
125
+	/**
126
+	 * get_all_trashed_message_templates_by_event
127
+	 *
128
+	 * @access public
129
+	 * @param int    $EVT_ID specific event id
130
+	 * @param string $orderby
131
+	 * @param string $order
132
+	 * @param null   $limit
133
+	 * @param bool   $count
134
+	 * @return array message template objects that are attached to a specific event.
135
+	 */
136
+	public function get_all_trashed_message_templates_by_event(
137
+		$EVT_ID,
138
+		$orderby = 'GRP_ID',
139
+		$order = 'ASC',
140
+		$limit = null,
141
+		$count = false
142
+	) {
143
+		$query_params = [['Event.EVT_ID' => $EVT_ID], 'order_by' => [$orderby => $order], 'limit' => $limit];
144
+		return $count ? $this->count_deleted($query_params, 'GRP_ID', true) : $this->get_all_deleted($query_params);
145
+	}
146
+
147
+
148
+	/**
149
+	 * get_all_message_templates_by_messenger
150
+	 *
151
+	 * @access public
152
+	 * @param        $messenger
153
+	 * @param string $orderby
154
+	 * @param string $order
155
+	 * @return array all (including trashed or inactive) message template group objects for the given messenger
156
+	 */
157
+	public function get_all_message_templates_by_messenger($messenger, $orderby = 'GRP_ID', $order = 'ASC')
158
+	{
159
+		return $this->get_all_deleted_and_undeleted(
160
+			[['MTP_messenger' => $messenger], 'order_by' => [$orderby => $order]]
161
+		);
162
+	}
163
+
164
+
165
+	/**
166
+	 * This simply adds on any messenger/message type filters that may be present in the request
167
+	 *
168
+	 * @param array $_where any existing where conditions to append these to.
169
+	 * @return array          original where conditions or original with additional filters.
170
+	 */
171
+	protected function _maybe_mtp_filters($_where = [])
172
+	{
173
+		/** @var RequestInterface $request */
174
+		$request   = LoaderFactory::getLoader()->getShared(RequestInterface::class);
175
+		$messenger = $request->getRequestParam('ee_messenger_filter_by');
176
+		// account for messenger or message type filters
177
+		if ($messenger !== '' && $messenger !== 'none_selected' && $messenger !== 'all') {
178
+			$_where['MTP_messenger'] = $messenger;
179
+		}
180
+		$message_type = $request->getRequestParam('ee_message_type_filter_by');
181
+		if (
182
+			$message_type !== '' && $message_type !== 'none_selected'
183
+		) {
184
+			$_where['MTP_message_type'] = $message_type;
185
+		}
186
+
187
+		return $_where;
188
+	}
189
+
190
+
191
+	/**
192
+	 * get_all_active_message_templates groups
193
+	 *
194
+	 * @access public
195
+	 * @param string $orderby
196
+	 * @param string $order
197
+	 * @param null   $limit
198
+	 * @param bool   $count
199
+	 * @param bool   $global
200
+	 * @param bool   $user_check
201
+	 * @return array|int all active (non_trashed, active) message template objects
202
+	 */
203
+	public function get_all_active_message_templates(
204
+		$orderby = 'GRP_ID',
205
+		$order = 'ASC',
206
+		$limit = null,
207
+		$count = false,
208
+		$global = true,
209
+		$user_check = false
210
+	) {
211
+		$_where                  = $global ? ['MTP_is_global' => true] : ['MTP_is_global' => false];
212
+		$_where['MTP_is_active'] = true;
213
+		$_where                  = $this->_maybe_mtp_filters($_where);
214
+
215
+		if (
216
+			$user_check
217
+			&& ! $global
218
+			&& ! EE_Registry::instance()->CAP->current_user_can(
219
+				'ee_read_others_messages',
220
+				'get_all_active_message_templates'
221
+			)
222
+		) {
223
+			$_where['MTP_user_id'] = get_current_user_id();
224
+		}
225
+
226
+		$query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
227
+
228
+		return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
229
+	}
230
+
231
+
232
+	/**
233
+	 *    retrieve ALL message_template groups from db regardless of wht
234
+	 *
235
+	 * @access    public
236
+	 * @param string $orderby
237
+	 * @param string $order
238
+	 * @param null   $limit
239
+	 * @param bool   $count
240
+	 * @return mixed array on success, FALSE on fail
241
+	 */
242
+	public function get_all_message_templates($orderby = 'GRP_ID', $order = 'ASC', $limit = null, $count = false)
243
+	{
244
+		$_where = $this->_maybe_mtp_filters();
245
+
246
+		$query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
247
+
248
+		$r_templates = $count
249
+			? $this->count_deleted_and_undeleted($query_params, 'GRP_ID', true)
250
+			: $this->get_all_deleted_and_undeleted($query_params);
251
+
252
+		return $r_templates;
253
+	}
254
+
255
+
256
+	/**
257
+	 * This gets all the custom templates attached to a specific event
258
+	 *
259
+	 * @param int   $EVT_ID       event id
260
+	 * @param array $query_params @see
261
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
262
+	 * @return  EE_Message_Template_Group[]
263
+	 */
264
+	public function get_all_custom_templates_by_event($EVT_ID, $query_params = [])
265
+	{
266
+		$where = array_merge($query_params, ['Event.EVT_ID' => $EVT_ID]);
267
+		return $this->get_all(
268
+			[$where]
269
+		);
270
+	}
271
+
272
+
273
+	/**
274
+	 * get_all_trashed_grouped_message_templates
275
+	 * this returns ONLY the template groups where ALL contexts are trashed and none of the group are non-trashed
276
+	 *
277
+	 * @access public
278
+	 * @param string $orderby
279
+	 * @param string $order
280
+	 * @param null   $limit
281
+	 * @param bool   $count
282
+	 * @param bool   $global
283
+	 * @return array|int EE_Message_Template_Group[] message template groups.
284
+	 */
285
+	public function get_all_trashed_grouped_message_templates(
286
+		$orderby = 'GRP_ID',
287
+		$order = 'ASC',
288
+		$limit = null,
289
+		$count = false,
290
+		$global = true
291
+	) {
292
+		$_where                  = $global ? ['MTP_is_global' => true] : ['MTP_is_global' => false];
293
+		$_where['MTP_is_active'] = true;
294
+		$_where                  = $this->_maybe_mtp_filters($_where);
295
+
296
+		$query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
297
+
298
+		return $count ? $this->count_deleted($query_params, 'GRP_ID', true) : $this->get_all_deleted($query_params);
299
+	}
300
+
301
+
302
+	/**
303
+	 * this returns the message template group(s) for a given event, messenger, and message template
304
+	 *
305
+	 * @param string              $messenger
306
+	 * @param string              $message_type
307
+	 * @param                     $evt_id
308
+	 * @param string              $orderby pointless at this point but still included
309
+	 * @param string              $order
310
+	 * @param mixed (array|null) $limit   array($offset, $num)
311
+	 * @param bool                $count   true = just return count, false = objects
312
+	 * @param bool                $active  ignore "active" or not. (default only return active)
313
+	 * @return \mixed[]) depending on $count.
314
+	 */
315
+	public function get_event_message_templates_by_m_and_mt_and_evt(
316
+		$messenger,
317
+		$message_type,
318
+		$evt_id,
319
+		$orderby = 'GRP_ID',
320
+		$order = 'ASC',
321
+		$limit = null,
322
+		$count = false,
323
+		$active = true
324
+	) {
325
+		$_where = [
326
+			'MTP_messenger'    => $messenger,
327
+			'MTP_message_type' => $message_type,
328
+			'Event.EVT_ID'     => $evt_id,
329
+			'MTP_is_global'    => true,
330
+			'MTP_is_active'    => $active,
331
+		];
332
+
333
+		$query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
334
+
335
+		return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
336
+	}
337
+
338
+
339
+	/**
340
+	 * get all GLOBAL message template groups for the given messenger and message type
341
+	 *
342
+	 * @param string $messenger     slug for messenger
343
+	 * @param string $message_type  slug for message type
344
+	 * @param string $orderby       what column to orderby
345
+	 * @param string $order         ASC or DESC
346
+	 * @param mixed (array|null) $limit array($offset, $num)
347
+	 * @param bool   $count         true = just return count, false = objects
348
+	 * @param bool   $active        ignore "active" or not. (default only return active) -
349
+	 *                              'all' means return both inactive AND inactive.
350
+	 * @return array               message template objects that are global (i.e. non-event)
351
+	 */
352
+	public function get_global_message_template_by_m_and_mt(
353
+		$messenger,
354
+		$message_type,
355
+		$orderby = 'GRP_ID',
356
+		$order = 'ASC',
357
+		$limit = null,
358
+		$count = false,
359
+		$active = true
360
+	) {
361
+		$_where = [
362
+			'MTP_messenger'    => $messenger,
363
+			'MTP_message_type' => $message_type,
364
+			'MTP_is_global'    => true,
365
+		];
366
+
367
+		if ($active != 'all') {
368
+			$_where['MTP_is_active'] = $active;
369
+		}
370
+
371
+		$query_params = [$_where, 'order_by' => [$orderby => $order], 'limit' => $limit];
372
+
373
+		return $count ? $this->count($query_params, 'GRP_ID', true) : $this->get_all($query_params);
374
+	}
375
+
376
+
377
+	/**
378
+	 * get all custom message template groups for the given messenger and message type
379
+	 *
380
+	 * @param string $messenger    messenger
381
+	 * @param string $message_type messagetype
382
+	 * @param array  $query_params same as EEM_Base->get_all()
383
+	 * @return EE_Message_Template_Group[]
384
+	 */
385
+	public function get_custom_message_template_by_m_and_mt($messenger, $message_type, $query_params = [])
386
+	{
387
+		return $this->get_all(
388
+			array_merge(
389
+				$query_params,
390
+				[
391
+					[
392
+						'MTP_is_global'    => false,
393
+						'MTP_messenger'    => $messenger,
394
+						'MTP_message_type' => $message_type,
395
+					],
396
+				]
397
+			)
398
+		);
399
+	}
400
+
401
+
402
+	/**
403
+	 * This sends things to the validator for the given messenger and message type.
404
+	 *
405
+	 * @param array  $fields       the incoming fields to check.
406
+	 *                             Note this array is in the formatted fields from the form fields setup.
407
+	 *                             So we need to reformat this into an array of expected field refs by the validator.
408
+	 *                             Note also that this is not only the fields for the Message Template Group
409
+	 *                             but ALSO for Message Template.
410
+	 * @param string $context      The context the fields were obtained from.
411
+	 * @param string $messenger    The messenger we are validating
412
+	 * @param string $message_type The message type we are validating.
413
+	 * @return bool
414
+	 * @throws DomainException
415
+	 */
416
+	public function validate(array $fields, string $context, string $messenger, string $message_type): bool
417
+	{
418
+		/** @var MessageTemplateValidator $validator */
419
+		$validator = LoaderFactory::getShared(MessageTemplateValidator::class);
420
+		return $validator->validateTemplateFields($messenger, $message_type, $context, $fields);
421
+	}
422
+
423
+
424
+	/**
425
+	 * Updates all message template groups matching the incoming arguments to inactive status.
426
+	 *
427
+	 * @param array $messenger_names    The messenger slugs.
428
+	 *                                  If empty then all templates matching the message types are marked inactive.
429
+	 *                                  Otherwise only templates matching the messengers and message types.
430
+	 * @param array $message_type_names The message type slugs.
431
+	 *                                  If empty then all templates matching the messengers are marked inactive.
432
+	 *                                  Otherwise only templates matching the messengers and message types.
433
+	 * @return int  count of updated records.
434
+	 */
435
+	public function deactivate_message_template_groups_for($messenger_names = [], $message_type_names = [])
436
+	{
437
+		$query_args = [];
438
+		if (empty($messenger_names) && empty($message_type_names)) {
439
+			return 0;
440
+		}
441
+		if (! empty($messenger_names)) {
442
+			$query_args[0]['MTP_messenger'] = ['IN', (array) $messenger_names];
443
+		}
444
+		if (! empty($message_type_names)) {
445
+			$query_args[0]['MTP_message_type'] = ['IN', (array) $message_type_names];
446
+		}
447
+		return $this->update(['MTP_is_active' => false], $query_args);
448
+	}
449 449
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
             'WP_User'          => new EE_Belongs_To_Relation(),
115 115
         ];
116 116
         foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
117
-            $this->_cap_restriction_generators[ $context ] = new EE_Restriction_Generator_Global('MTP_is_global');
117
+            $this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_Global('MTP_is_global');
118 118
         }
119 119
         $this->_caps_slug = 'messages';
120 120
 
@@ -438,10 +438,10 @@  discard block
 block discarded – undo
438 438
         if (empty($messenger_names) && empty($message_type_names)) {
439 439
             return 0;
440 440
         }
441
-        if (! empty($messenger_names)) {
441
+        if ( ! empty($messenger_names)) {
442 442
             $query_args[0]['MTP_messenger'] = ['IN', (array) $messenger_names];
443 443
         }
444
-        if (! empty($message_type_names)) {
444
+        if ( ! empty($message_type_names)) {
445 445
             $query_args[0]['MTP_message_type'] = ['IN', (array) $message_type_names];
446 446
         }
447 447
         return $this->update(['MTP_is_active' => false], $query_args);
Please login to merge, or discard this patch.
core/db_models/EEM_Registration.model.php 2 patches
Indentation   +885 added lines, -885 removed lines patch added patch discarded remove patch
@@ -14,834 +14,834 @@  discard block
 block discarded – undo
14 14
  */
15 15
 class EEM_Registration extends EEM_Soft_Delete_Base
16 16
 {
17
-    /**
18
-     * The value of REG_count for a primary registrant
19
-     */
20
-    const PRIMARY_REGISTRANT_COUNT = 1;
21
-
22
-    /**
23
-     * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
24
-     * Initial status for registrations when they are first created
25
-     * Payments are NOT allowed.
26
-     * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
27
-     * information reg step NO space reserved. Registration is NOT active
28
-     */
29
-    const status_id_incomplete = 'RIC';
30
-
31
-    /**
32
-     * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
33
-     * Payments are NOT allowed.
34
-     * Event Admin must manually toggle STS_ID for it to change
35
-     * No space reserved.
36
-     * Registration is active
37
-     */
38
-    const status_id_not_approved = 'RNA';
39
-
40
-    /**
41
-     * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
42
-     * Payments are allowed.
43
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
44
-     * No space reserved.
45
-     * Registration is active
46
-     */
47
-    const status_id_pending_payment = 'RPP';
48
-
49
-    /**
50
-     * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
51
-     * Payments are allowed.
52
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
53
-     * No space reserved.
54
-     * Registration is active
55
-     */
56
-    const status_id_wait_list = 'RWL';
57
-
58
-    /**
59
-     * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
60
-     * the TXN may or may not be completed ( paid in full )
61
-     * Payments are allowed.
62
-     * A space IS reserved.
63
-     * Registration is active
64
-     */
65
-    const status_id_approved = 'RAP';
66
-
67
-    /**
68
-     * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
69
-     * Payments are NOT allowed.
70
-     * NO space reserved.
71
-     * Registration is NOT active
72
-     */
73
-    const status_id_cancelled = 'RCN';
74
-
75
-    /**
76
-     * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
77
-     * Payments are NOT allowed.
78
-     * No space reserved.
79
-     * Registration is NOT active
80
-     */
81
-    const status_id_declined = 'RDC';
82
-
83
-
84
-    protected static ?EEM_Registration $_instance       = null;
85
-
86
-    protected ?TableAnalysis           $_table_analysis = null;
87
-
88
-    /**
89
-     * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
90
-     * are status codes (eg, approved, cancelled, etc)
91
-     *
92
-     * @var array|null
93
-     */
94
-    private static array $_reg_status = [];
95
-
96
-
97
-    /**
98
-     * private constructor to prevent direct creation
99
-     *
100
-     * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
101
-     *                              any incoming timezone data that gets saved). Note this just sends the timezone info
102
-     *                              to the date time model field objects.  Default is NULL (and will be assumed using
103
-     *                              the set timezone in the 'timezone_string' wp option)
104
-     * @throws EE_Error
105
-     * @throws ReflectionException
106
-     */
107
-    protected function __construct(?string $timezone = '')
108
-    {
109
-        $this->_table_analysis         = EE_Registry::instance()->create('TableAnalysis', [], true);
110
-        $this->singular_item           = esc_html__('Registration', 'event_espresso');
111
-        $this->plural_item             = esc_html__('Registrations', 'event_espresso');
112
-        $this->_tables                 = [
113
-            'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
114
-        ];
115
-        $this->_fields                 = [
116
-            'Registration' => [
117
-                'REG_ID'           => new EE_Primary_Key_Int_Field(
118
-                    'REG_ID',
119
-                    esc_html__('Registration ID', 'event_espresso')
120
-                ),
121
-                'EVT_ID'           => new EE_Foreign_Key_Int_Field(
122
-                    'EVT_ID',
123
-                    esc_html__('Event ID', 'event_espresso'),
124
-                    false,
125
-                    0,
126
-                    'Event'
127
-                ),
128
-                'ATT_ID'           => new EE_Foreign_Key_Int_Field(
129
-                    'ATT_ID',
130
-                    esc_html__('Attendee ID', 'event_espresso'),
131
-                    false,
132
-                    0,
133
-                    'Attendee'
134
-                ),
135
-                'TXN_ID'           => new EE_Foreign_Key_Int_Field(
136
-                    'TXN_ID',
137
-                    esc_html__('Transaction ID', 'event_espresso'),
138
-                    false,
139
-                    0,
140
-                    'Transaction'
141
-                ),
142
-                'TKT_ID'           => new EE_Foreign_Key_Int_Field(
143
-                    'TKT_ID',
144
-                    esc_html__('Ticket ID', 'event_espresso'),
145
-                    false,
146
-                    0,
147
-                    'Ticket'
148
-                ),
149
-                'STS_ID'           => new EE_Foreign_Key_String_Field(
150
-                    'STS_ID',
151
-                    esc_html__('Status ID', 'event_espresso'),
152
-                    false,
153
-                    EEM_Registration::status_id_incomplete,
154
-                    'Status'
155
-                ),
156
-                'REG_date'         => new EE_Datetime_Field(
157
-                    'REG_date',
158
-                    esc_html__('Time registration occurred', 'event_espresso'),
159
-                    false,
160
-                    EE_Datetime_Field::now,
161
-                    $timezone
162
-                ),
163
-                'REG_final_price'  => new EE_Money_Field(
164
-                    'REG_final_price',
165
-                    esc_html__('Registration\'s share of the transaction total', 'event_espresso'),
166
-                    false,
167
-                    0
168
-                ),
169
-                'REG_paid'         => new EE_Money_Field(
170
-                    'REG_paid',
171
-                    esc_html__('Amount paid to date towards registration', 'event_espresso'),
172
-                    false,
173
-                    0
174
-                ),
175
-                'REG_session'      => new EE_Plain_Text_Field(
176
-                    'REG_session',
177
-                    esc_html__('Session ID of registration', 'event_espresso'),
178
-                    false,
179
-                    ''
180
-                ),
181
-                'REG_code'         => new EE_Plain_Text_Field(
182
-                    'REG_code',
183
-                    esc_html__('Unique Code for this registration', 'event_espresso'),
184
-                    false,
185
-                    ''
186
-                ),
187
-                'REG_url_link'     => new EE_Plain_Text_Field(
188
-                    'REG_url_link',
189
-                    esc_html__('String to be used in URL for identifying registration', 'event_espresso'),
190
-                    false,
191
-                    ''
192
-                ),
193
-                'REG_count'        => new EE_Integer_Field(
194
-                    'REG_count',
195
-                    esc_html__('Count of this registration in the group registration', 'event_espresso'),
196
-                    true,
197
-                    1
198
-                ),
199
-                'REG_group_size'   => new EE_Integer_Field(
200
-                    'REG_group_size',
201
-                    esc_html__('Number of registrations on this group', 'event_espresso'),
202
-                    false,
203
-                    1
204
-                ),
205
-                'REG_att_is_going' => new EE_Boolean_Field(
206
-                    'REG_att_is_going',
207
-                    esc_html__('Flag indicating the registrant plans on attending', 'event_espresso'),
208
-                    false,
209
-                    false
210
-                ),
211
-                'REG_deleted'      => new EE_Trashed_Flag_Field(
212
-                    'REG_deleted',
213
-                    esc_html__('Flag indicating if registration has been archived or not.', 'event_espresso'),
214
-                    false,
215
-                    false
216
-                ),
217
-            ],
218
-        ];
219
-        $this->_model_relations        = [
220
-            'Event'                => new EE_Belongs_To_Relation(),
221
-            'Attendee'             => new EE_Belongs_To_Relation(),
222
-            'Transaction'          => new EE_Belongs_To_Relation(),
223
-            'Ticket'               => new EE_Belongs_To_Relation(),
224
-            'Status'               => new EE_Belongs_To_Relation(),
225
-            'Answer'               => new EE_Has_Many_Relation(),
226
-            'Checkin'              => new EE_Has_Many_Relation(),
227
-            'Registration_Payment' => new EE_Has_Many_Relation(),
228
-            'Payment'              => new EE_HABTM_Relation('Registration_Payment'),
229
-            'Message'              => new EE_Has_Many_Any_Relation(false),
230
-            // allow deletes even if there are messages in the queue related
231
-        ];
232
-        $this->_model_chain_to_wp_user = 'Event';
233
-        parent::__construct($timezone);
234
-    }
235
-
236
-
237
-    /**
238
-     * a list of ALL valid registration statuses currently in use within the system
239
-     * generated by combining the filterable active and inactive reg status arrays
240
-     *
241
-     * @return array
242
-     */
243
-    public static function reg_statuses(): array
244
-    {
245
-        return array_unique(
246
-            array_merge(
247
-                EEM_Registration::active_reg_statuses(),
248
-                EEM_Registration::inactive_reg_statuses()
249
-            )
250
-        );
251
-    }
252
-
253
-
254
-    /**
255
-     * reg_statuses_that_allow_payment
256
-     * a filterable list of registration statuses that allow a registrant to make a payment
257
-     *
258
-     * @access public
259
-     * @return array
260
-     */
261
-    public static function reg_statuses_that_allow_payment(): array
262
-    {
263
-        return (array) apply_filters(
264
-            'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
265
-            [
266
-                EEM_Registration::status_id_approved,
267
-                EEM_Registration::status_id_pending_payment,
268
-            ]
269
-        );
270
-    }
271
-
272
-
273
-    /**
274
-     * active_reg_statuses
275
-     * a filterable list of registration statuses that are considered active
276
-     *
277
-     * @access public
278
-     * @return array
279
-     */
280
-    public static function active_reg_statuses(): array
281
-    {
282
-        return (array) apply_filters(
283
-            'FHEE__EEM_Registration__active_reg_statuses',
284
-            [
285
-                EEM_Registration::status_id_approved,
286
-                EEM_Registration::status_id_pending_payment,
287
-                EEM_Registration::status_id_wait_list,
288
-                EEM_Registration::status_id_not_approved,
289
-            ]
290
-        );
291
-    }
292
-
293
-
294
-    /**
295
-     * inactive_reg_statuses
296
-     * a filterable list of registration statuses that are not considered active
297
-     *
298
-     * @access public
299
-     * @return array
300
-     */
301
-    public static function inactive_reg_statuses(): array
302
-    {
303
-        return (array) apply_filters(
304
-            'FHEE__EEM_Registration__inactive_reg_statuses',
305
-            [
306
-                EEM_Registration::status_id_incomplete,
307
-                EEM_Registration::status_id_cancelled,
308
-                EEM_Registration::status_id_declined,
309
-            ]
310
-        );
311
-    }
312
-
313
-
314
-    /**
315
-     *    closed_reg_statuses
316
-     *    a filterable list of registration statuses that are considered "closed"
317
-     * meaning they should not be considered in any calculations involving monies owing
318
-     *
319
-     * @access public
320
-     * @return array
321
-     */
322
-    public static function closed_reg_statuses(): array
323
-    {
324
-        return (array) apply_filters(
325
-            'FHEE__EEM_Registration__closed_reg_statuses',
326
-            [
327
-                EEM_Registration::status_id_cancelled,
328
-                EEM_Registration::status_id_declined,
329
-                EEM_Registration::status_id_wait_list,
330
-            ]
331
-        );
332
-    }
333
-
334
-
335
-    /**
336
-     * get list of registration statuses
337
-     *
338
-     * @param array $exclude    The status ids to exclude from the returned results
339
-     * @param bool  $translated If true will return the values as singular localized strings
340
-     * @return array
341
-     * @throws EE_Error
342
-     * @throws ReflectionException
343
-     */
344
-    public static function reg_status_array(array $exclude = [], bool $translated = false): array
345
-    {
346
-        if (empty(self::$_reg_status)) {
347
-            EEM_Registration::instance()->_get_registration_status_array($exclude);
348
-        }
349
-        return $translated
350
-            ? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
351
-            : self::$_reg_status;
352
-    }
353
-
354
-
355
-    /**
356
-     * get list of registration statuses
357
-     *
358
-     * @param array $exclude
359
-     * @param bool  $recurse
360
-     * @return void
361
-     * @throws EE_Error
362
-     * @throws ReflectionException
363
-     */
364
-    private function _get_registration_status_array(array $exclude = [], bool $recurse = true)
365
-    {
366
-        // in the very rare circumstance that we are deleting a model's table's data
367
-        // and the table hasn't actually been created, this could have an error
368
-        /** @type WPDB $wpdb */
369
-        global $wpdb;
370
-        if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
371
-            $results           = $wpdb->get_results(
372
-                "SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
373
-            );
374
-            self::$_reg_status = [];
375
-            foreach ($results as $status) {
376
-                if (! in_array($status->STS_ID, $exclude, true)) {
377
-                    self::$_reg_status[ $status->STS_ID ] = $status->STS_code;
378
-                }
379
-            }
380
-        }
381
-        // in case reg status codes have been deleted from db
382
-        if ($recurse && empty(self::$_reg_status)) {
383
-            EEH_Activation::insert_default_status_codes();
384
-            EEM_Registration::instance()->_get_registration_status_array($exclude, false);
385
-        }
386
-    }
387
-
388
-
389
-    /**
390
-     * Gets the injected table analyzer, or throws an exception
391
-     *
392
-     * @return TableAnalysis
393
-     * @throws EE_Error
394
-     */
395
-    protected function _get_table_analysis(): TableAnalysis
396
-    {
397
-        if ($this->_table_analysis instanceof TableAnalysis) {
398
-            return $this->_table_analysis;
399
-        }
400
-        throw new EE_Error(
401
-            sprintf(
402
-                esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
403
-                get_class($this)
404
-            )
405
-        );
406
-    }
407
-
408
-
409
-    /**
410
-     * This returns a wpdb->results array of all registration date month and years matching the incoming query params
411
-     * and grouped by month and year.
412
-     *
413
-     * @param array $where_params
414
-     * @return bool|stdClass[]
415
-     * @throws EE_Error
416
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
417
-     */
418
-    public function get_reg_months_and_years(array $where_params)
419
-    {
420
-        $query_params[0]          = $where_params;
421
-        $query_params['group_by'] = ['reg_year', 'reg_month'];
422
-        $query_params['order_by'] = ['REG_date' => 'DESC'];
423
-        $columns_to_select        = [
424
-            'reg_year'  => ['YEAR(REG_date)', '%s'],
425
-            'reg_month' => ['MONTHNAME(REG_date)', '%s'],
426
-        ];
427
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
428
-    }
429
-
430
-
431
-    /**
432
-     * retrieve ALL registrations for a particular Attendee from db
433
-     *
434
-     * @param int $ATT_ID
435
-     * @return EE_Registration[]|bool|null
436
-     * @throws EE_Error
437
-     * @throws ReflectionException
438
-     */
439
-    public function get_all_registrations_for_attendee(int $ATT_ID = 0): ?array
440
-    {
441
-        if (! $ATT_ID) {
442
-            return null;
443
-        }
444
-        return $this->get_all([['ATT_ID' => $ATT_ID]]);
445
-    }
446
-
447
-
448
-    /**
449
-     * Gets a registration given their REG_url_link. Yes, this should usually
450
-     * be passed via a GET parameter.
451
-     *
452
-     * @param string $REG_url_link
453
-     * @return EE_Registration|null
454
-     * @throws EE_Error
455
-     */
456
-    public function get_registration_for_reg_url_link(string $REG_url_link): ?EE_Registration
457
-    {
458
-        if (! $REG_url_link) {
459
-            return null;
460
-        }
461
-        return $this->get_one([['REG_url_link' => $REG_url_link]]);
462
-    }
463
-
464
-
465
-    /**
466
-     *        retrieve registration for a specific transaction attendee from db
467
-     *
468
-     * @access        public
469
-     * @param int $TXN_ID
470
-     * @param int $ATT_ID
471
-     * @param int $att_nmbr    in case the ATT_ID is the same for multiple registrations (same details used) then the
472
-     *                         attendee number is required
473
-     * @return EE_Registration|null array on success, FALSE on fail
474
-     * @throws EE_Error
475
-     */
476
-    public function get_registration_for_transaction_attendee(int $TXN_ID = 0, int $ATT_ID = 0, int $att_nmbr = 0):
477
-    ?EE_Registration {
478
-        return $this->get_one(
479
-            [
480
-                [
481
-                    'TXN_ID' => $TXN_ID,
482
-                    'ATT_ID' => $ATT_ID,
483
-                ],
484
-                'limit' => [min($att_nmbr - 1, 0), 1],
485
-            ]
486
-        );
487
-    }
488
-
489
-
490
-    /**
491
-     *        get the number of registrations per day  for the Registration Admin page Reports Tab.
492
-     *        (doesn't utilize models because it's a fairly specialized query)
493
-     *
494
-     * @access        public
495
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
496
-     * @return EE_Registration[]|bool|null with properties regDate and total
497
-     * @throws EE_Error
498
-     */
499
-    public function get_registrations_per_day_report(string $period = '-1 month')
500
-    {
501
-        $sql_date = $this->convert_datetime_for_query(
502
-            'REG_date',
503
-            date('Y-m-d H:i:s', strtotime($period)),
504
-            'Y-m-d H:i:s',
505
-            'UTC'
506
-        );
507
-        $where    = [
508
-            'REG_date' => ['>=', $sql_date],
509
-            'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
510
-        ];
511
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
512
-            $where['Event.EVT_wp_user'] = get_current_user_id();
513
-        }
514
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
515
-        return $this->_get_all_wpdb_results(
516
-            [
517
-                $where,
518
-                'group_by' => 'regDate',
519
-                'order_by' => ['REG_date' => 'ASC'],
520
-            ],
521
-            OBJECT,
522
-            [
523
-                'regDate' => ['DATE(' . $query_interval . ')', '%s'],
524
-                'total'   => ['count(REG_ID)', '%d'],
525
-            ]
526
-        );
527
-    }
528
-
529
-
530
-    /**
531
-     * Get the number of registrations per day including the count of registrations for each Registration Status.
532
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
533
-     *
534
-     * @param string $period
535
-     * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
536
-     * @throws EE_Error
537
-     *                    (i.e. RAP)
538
-     * @throws EE_Error|ReflectionException
539
-     */
540
-    public function get_registrations_per_day_and_per_status_report(string $period = '-1 month'): array
541
-    {
542
-        global $wpdb;
543
-        $registration_table = $wpdb->prefix . 'esp_registration';
544
-        $event_table        = $wpdb->posts;
545
-        $sql_date           = date('Y-m-d H:i:s', strtotime($period));
546
-        // prepare the query interval for displaying offset
547
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
548
-        // inner date query
549
-        $inner_date_query = "SELECT DISTINCT REG_date from $registration_table ";
550
-        $inner_where      = ' WHERE';
551
-        // exclude events not authored by user if permissions in effect
552
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
553
-            $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
554
-            $inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
555
-        }
556
-        $inner_where      .= " REG_date >= '$sql_date'";
557
-        $inner_date_query .= $inner_where;
558
-        // start main query
559
-        $select       = "SELECT DATE($query_interval) as Registration_REG_date, ";
560
-        $join         = '';
561
-        $join_parts   = [];
562
-        $select_parts = [];
563
-        // loop through registration stati to do parts for each status.
564
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
565
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
566
-                continue;
567
-            }
568
-            $select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
569
-            $join_parts[]   =
570
-                "$registration_table AS $STS_code ON $STS_code.REG_date = dates.REG_date AND $STS_code.STS_ID = '$STS_ID'";
571
-        }
572
-        // setup the selects
573
-        $select .= implode(', ', $select_parts);
574
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
575
-        // setup the joins
576
-        $join .= implode(' LEFT JOIN ', $join_parts);
577
-        // now let's put it all together
578
-        $query = $select . $join . ' GROUP BY Registration_REG_date';
579
-        // and execute it
580
-        return $wpdb->get_results($query, ARRAY_A);
581
-    }
582
-
583
-
584
-    /**
585
-     *        get the number of registrations per event  for the Registration Admin page Reports Tab
586
-     *
587
-     * @access        public
588
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
589
-     * @return stdClass[] each with properties event_name, reg_limit, and total
590
-     * @throws EE_Error
591
-     */
592
-    public function get_registrations_per_event_report(string $period = '-1 month'): array
593
-    {
594
-        $date_sql = $this->convert_datetime_for_query(
595
-            'REG_date',
596
-            date('Y-m-d H:i:s', strtotime($period)),
597
-            'Y-m-d H:i:s',
598
-            'UTC'
599
-        );
600
-        $where    = [
601
-            'REG_date' => ['>=', $date_sql],
602
-            'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
603
-        ];
604
-        if (
605
-            ! EE_Registry::instance()->CAP->current_user_can(
606
-                'ee_read_others_registrations',
607
-                'reg_per_event_report'
608
-            )
609
-        ) {
610
-            $where['Event.EVT_wp_user'] = get_current_user_id();
611
-        }
612
-        return $this->_get_all_wpdb_results(
613
-            [
614
-                $where,
615
-                'group_by' => 'Event.EVT_name',
616
-                'order_by' => 'Event.EVT_name',
617
-                'limit'    => [0, 24],
618
-            ],
619
-            OBJECT,
620
-            [
621
-                'event_name' => ['Event_CPT.post_title', '%s'],
622
-                'total'      => ['COUNT(REG_ID)', '%s'],
623
-            ]
624
-        );
625
-    }
626
-
627
-
628
-    /**
629
-     * Get the number of registrations per event grouped by registration status.
630
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
631
-     *
632
-     * @param string $period
633
-     * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
634
-     *                    (i.e. RAP)
635
-     * @throws EE_Error
636
-     * @throws ReflectionException
637
-     */
638
-    public function get_registrations_per_event_and_per_status_report(string $period = '-1 month'): array
639
-    {
640
-        global $wpdb;
641
-        $registration_table = $wpdb->prefix . 'esp_registration';
642
-        $event_table        = $wpdb->posts;
643
-        $sql_date           = date('Y-m-d H:i:s', strtotime($period));
644
-        // inner date query
645
-        $inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
646
-        $inner_where      = ' WHERE';
647
-        // exclude events not authored by user if permissions in effect
648
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
649
-            $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
650
-            $inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
651
-        }
652
-        $inner_where      .= " REG_date >= '$sql_date'";
653
-        $inner_date_query .= $inner_where;
654
-        // build main query
655
-        $select       = 'SELECT Event.post_title as Registration_Event, ';
656
-        $join         = '';
657
-        $join_parts   = [];
658
-        $select_parts = [];
659
-        // loop through registration stati to do parts for each status.
660
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
661
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
662
-                continue;
663
-            }
664
-            $select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
665
-            $join_parts[]   =
666
-                "$registration_table AS $STS_code ON $STS_code.EVT_ID = dates.EVT_ID AND $STS_code.STS_ID = '$STS_ID' AND $STS_code.REG_date = dates.REG_date";
667
-        }
668
-        // setup the selects
669
-        $select .= implode(', ', $select_parts);
670
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
671
-        // setup remaining joins
672
-        $join .= implode(' LEFT JOIN ', $join_parts);
673
-        // now put it all together
674
-        $query = $select . $join . ' GROUP BY Registration_Event';
675
-        // and execute
676
-        return $wpdb->get_results($query, ARRAY_A);
677
-    }
678
-
679
-
680
-    /**
681
-     * Returns the EE_Registration of the primary attendee on the transaction id provided
682
-     *
683
-     * @param int $TXN_ID
684
-     * @return EE_Registration|null
685
-     * @throws EE_Error
686
-     */
687
-    public function get_primary_registration_for_transaction_ID(int $TXN_ID = 0): ?EE_Registration
688
-    {
689
-        if (! $TXN_ID) {
690
-            return null;
691
-        }
692
-        return $this->get_one(
693
-            [
694
-                [
695
-                    'TXN_ID'    => $TXN_ID,
696
-                    'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
697
-                ],
698
-            ]
699
-        );
700
-    }
701
-
702
-
703
-    /**
704
-     *        get_event_registration_count
705
-     *
706
-     * @access public
707
-     * @param int     $EVT_ID
708
-     * @param boolean $for_incomplete_payments
709
-     * @return int
710
-     * @throws EE_Error
711
-     */
712
-    public function get_event_registration_count(int $EVT_ID, bool $for_incomplete_payments = false): int
713
-    {
714
-        // we only count approved registrations towards registration limits
715
-        $query_params = [['EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved]];
716
-        if ($for_incomplete_payments) {
717
-            $query_params[0]['Transaction.STS_ID'] = ['!=', EEM_Transaction::complete_status_code];
718
-        }
719
-        return $this->count($query_params);
720
-    }
721
-
722
-
723
-    /**
724
-     * Deletes all registrations with no transactions. Note that this needs to be very efficient
725
-     * and so it uses wpdb directly. Also, we can't put a limit on this because MySQL doesn't allow a limit on a delete
726
-     * when joining tables like this.
727
-     *
728
-     * @return int|bool number deleted
729
-     * @throws EE_Error
730
-     * @throws ReflectionException
731
-     * @global WPDB $wpdb
732
-     */
733
-    public function delete_registrations_with_no_transaction()
734
-    {
735
-        /** @type WPDB $wpdb */
736
-        global $wpdb;
737
-        return $wpdb->query(
738
-            'DELETE r FROM '
739
-            . $this->table()
740
-            . ' r LEFT JOIN '
741
-            . EEM_Transaction::instance()->table()
742
-            . ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL'
743
-        );
744
-    }
745
-
746
-
747
-    /**
748
-     *  Count registrations checked into (or out of) a datetime
749
-     *
750
-     * @param int  $DTT_ID     datetime ID
751
-     * @param bool $checked_in whether to count registrations checked IN or OUT
752
-     * @return int
753
-     * @throws EE_Error
754
-     * @throws ReflectionException
755
-     * @throws ReflectionException
756
-     */
757
-    public function count_registrations_checked_into_datetime(int $DTT_ID, bool $checked_in = true): int
758
-    {
759
-        global $wpdb;
760
-        // subquery to get latest checkin
761
-        $query = $wpdb->prepare(
762
-            'SELECT '
763
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
764
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
765
-            . '( SELECT '
766
-            . 'max( CHK_timestamp ) AS latest_checkin, '
767
-            . 'REG_ID AS REG_ID '
768
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' '
769
-            . 'WHERE DTT_ID=%d '
770
-            . 'GROUP BY REG_ID'
771
-            . ') AS most_recent_checkin_per_reg '
772
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
773
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
774
-            . 'WHERE '
775
-            . 'checkins.CHK_in=%d',
776
-            $DTT_ID,
777
-            $checked_in
778
-        );
779
-        return (int) $wpdb->get_var($query);
780
-    }
781
-
782
-
783
-    /**
784
-     *  Count registrations checked into (or out of) an event.
785
-     *
786
-     * @param int  $EVT_ID     event ID
787
-     * @param bool $checked_in whether to count registrations checked IN or OUT
788
-     * @return int
789
-     * @throws EE_Error
790
-     * @throws ReflectionException
791
-     * @throws ReflectionException
792
-     * @throws ReflectionException
793
-     */
794
-    public function count_registrations_checked_into_event(int $EVT_ID, bool $checked_in = true): int
795
-    {
796
-        global $wpdb;
797
-        // subquery to get latest checkin
798
-        $query = $wpdb->prepare(
799
-            'SELECT '
800
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
801
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
802
-            . '( SELECT '
803
-            . 'max( CHK_timestamp ) AS latest_checkin, '
804
-            . 'REG_ID AS REG_ID '
805
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
806
-            . 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
807
-            . 'ON c.DTT_ID=d.DTT_ID '
808
-            . 'WHERE d.EVT_ID=%d '
809
-            . 'GROUP BY REG_ID'
810
-            . ') AS most_recent_checkin_per_reg '
811
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
812
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
813
-            . 'WHERE '
814
-            . 'checkins.CHK_in=%d',
815
-            $EVT_ID,
816
-            $checked_in
817
-        );
818
-        return (int) $wpdb->get_var($query);
819
-    }
820
-
821
-
822
-    /**
823
-     * The purpose of this method is to retrieve an array of
824
-     * EE_Registration objects that represent the latest registration
825
-     * for each ATT_ID given in the function argument.
826
-     *
827
-     * @param array $attendee_ids
828
-     * @return EE_Registration[]|bool|null
829
-     * @throws EE_Error
830
-     * @throws ReflectionException
831
-     */
832
-    public function get_latest_registration_for_each_of_given_contacts(array $attendee_ids = [])
833
-    {
834
-        // first do a native wp_query to get the latest REG_ID's matching these attendees.
835
-        global $wpdb;
836
-        $registration_table = $wpdb->prefix . 'esp_registration';
837
-        $attendee_table     = $wpdb->posts;
838
-        $attendee_ids       = is_array($attendee_ids)
839
-            ? array_map('absint', $attendee_ids)
840
-            : [(int) $attendee_ids];
841
-        $ATT_IDs            = implode(',', $attendee_ids);
842
-        // first we do a query to get the registration ids
843
-        // (because a group by before order by causes the order by to be ignored.)
844
-        $registration_id_query = "
17
+	/**
18
+	 * The value of REG_count for a primary registrant
19
+	 */
20
+	const PRIMARY_REGISTRANT_COUNT = 1;
21
+
22
+	/**
23
+	 * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
24
+	 * Initial status for registrations when they are first created
25
+	 * Payments are NOT allowed.
26
+	 * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
27
+	 * information reg step NO space reserved. Registration is NOT active
28
+	 */
29
+	const status_id_incomplete = 'RIC';
30
+
31
+	/**
32
+	 * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
33
+	 * Payments are NOT allowed.
34
+	 * Event Admin must manually toggle STS_ID for it to change
35
+	 * No space reserved.
36
+	 * Registration is active
37
+	 */
38
+	const status_id_not_approved = 'RNA';
39
+
40
+	/**
41
+	 * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
42
+	 * Payments are allowed.
43
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
44
+	 * No space reserved.
45
+	 * Registration is active
46
+	 */
47
+	const status_id_pending_payment = 'RPP';
48
+
49
+	/**
50
+	 * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
51
+	 * Payments are allowed.
52
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
53
+	 * No space reserved.
54
+	 * Registration is active
55
+	 */
56
+	const status_id_wait_list = 'RWL';
57
+
58
+	/**
59
+	 * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
60
+	 * the TXN may or may not be completed ( paid in full )
61
+	 * Payments are allowed.
62
+	 * A space IS reserved.
63
+	 * Registration is active
64
+	 */
65
+	const status_id_approved = 'RAP';
66
+
67
+	/**
68
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
69
+	 * Payments are NOT allowed.
70
+	 * NO space reserved.
71
+	 * Registration is NOT active
72
+	 */
73
+	const status_id_cancelled = 'RCN';
74
+
75
+	/**
76
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
77
+	 * Payments are NOT allowed.
78
+	 * No space reserved.
79
+	 * Registration is NOT active
80
+	 */
81
+	const status_id_declined = 'RDC';
82
+
83
+
84
+	protected static ?EEM_Registration $_instance       = null;
85
+
86
+	protected ?TableAnalysis           $_table_analysis = null;
87
+
88
+	/**
89
+	 * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
90
+	 * are status codes (eg, approved, cancelled, etc)
91
+	 *
92
+	 * @var array|null
93
+	 */
94
+	private static array $_reg_status = [];
95
+
96
+
97
+	/**
98
+	 * private constructor to prevent direct creation
99
+	 *
100
+	 * @param string|null $timezone string representing the timezone we want to set for returned Date Time Strings (and
101
+	 *                              any incoming timezone data that gets saved). Note this just sends the timezone info
102
+	 *                              to the date time model field objects.  Default is NULL (and will be assumed using
103
+	 *                              the set timezone in the 'timezone_string' wp option)
104
+	 * @throws EE_Error
105
+	 * @throws ReflectionException
106
+	 */
107
+	protected function __construct(?string $timezone = '')
108
+	{
109
+		$this->_table_analysis         = EE_Registry::instance()->create('TableAnalysis', [], true);
110
+		$this->singular_item           = esc_html__('Registration', 'event_espresso');
111
+		$this->plural_item             = esc_html__('Registrations', 'event_espresso');
112
+		$this->_tables                 = [
113
+			'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
114
+		];
115
+		$this->_fields                 = [
116
+			'Registration' => [
117
+				'REG_ID'           => new EE_Primary_Key_Int_Field(
118
+					'REG_ID',
119
+					esc_html__('Registration ID', 'event_espresso')
120
+				),
121
+				'EVT_ID'           => new EE_Foreign_Key_Int_Field(
122
+					'EVT_ID',
123
+					esc_html__('Event ID', 'event_espresso'),
124
+					false,
125
+					0,
126
+					'Event'
127
+				),
128
+				'ATT_ID'           => new EE_Foreign_Key_Int_Field(
129
+					'ATT_ID',
130
+					esc_html__('Attendee ID', 'event_espresso'),
131
+					false,
132
+					0,
133
+					'Attendee'
134
+				),
135
+				'TXN_ID'           => new EE_Foreign_Key_Int_Field(
136
+					'TXN_ID',
137
+					esc_html__('Transaction ID', 'event_espresso'),
138
+					false,
139
+					0,
140
+					'Transaction'
141
+				),
142
+				'TKT_ID'           => new EE_Foreign_Key_Int_Field(
143
+					'TKT_ID',
144
+					esc_html__('Ticket ID', 'event_espresso'),
145
+					false,
146
+					0,
147
+					'Ticket'
148
+				),
149
+				'STS_ID'           => new EE_Foreign_Key_String_Field(
150
+					'STS_ID',
151
+					esc_html__('Status ID', 'event_espresso'),
152
+					false,
153
+					EEM_Registration::status_id_incomplete,
154
+					'Status'
155
+				),
156
+				'REG_date'         => new EE_Datetime_Field(
157
+					'REG_date',
158
+					esc_html__('Time registration occurred', 'event_espresso'),
159
+					false,
160
+					EE_Datetime_Field::now,
161
+					$timezone
162
+				),
163
+				'REG_final_price'  => new EE_Money_Field(
164
+					'REG_final_price',
165
+					esc_html__('Registration\'s share of the transaction total', 'event_espresso'),
166
+					false,
167
+					0
168
+				),
169
+				'REG_paid'         => new EE_Money_Field(
170
+					'REG_paid',
171
+					esc_html__('Amount paid to date towards registration', 'event_espresso'),
172
+					false,
173
+					0
174
+				),
175
+				'REG_session'      => new EE_Plain_Text_Field(
176
+					'REG_session',
177
+					esc_html__('Session ID of registration', 'event_espresso'),
178
+					false,
179
+					''
180
+				),
181
+				'REG_code'         => new EE_Plain_Text_Field(
182
+					'REG_code',
183
+					esc_html__('Unique Code for this registration', 'event_espresso'),
184
+					false,
185
+					''
186
+				),
187
+				'REG_url_link'     => new EE_Plain_Text_Field(
188
+					'REG_url_link',
189
+					esc_html__('String to be used in URL for identifying registration', 'event_espresso'),
190
+					false,
191
+					''
192
+				),
193
+				'REG_count'        => new EE_Integer_Field(
194
+					'REG_count',
195
+					esc_html__('Count of this registration in the group registration', 'event_espresso'),
196
+					true,
197
+					1
198
+				),
199
+				'REG_group_size'   => new EE_Integer_Field(
200
+					'REG_group_size',
201
+					esc_html__('Number of registrations on this group', 'event_espresso'),
202
+					false,
203
+					1
204
+				),
205
+				'REG_att_is_going' => new EE_Boolean_Field(
206
+					'REG_att_is_going',
207
+					esc_html__('Flag indicating the registrant plans on attending', 'event_espresso'),
208
+					false,
209
+					false
210
+				),
211
+				'REG_deleted'      => new EE_Trashed_Flag_Field(
212
+					'REG_deleted',
213
+					esc_html__('Flag indicating if registration has been archived or not.', 'event_espresso'),
214
+					false,
215
+					false
216
+				),
217
+			],
218
+		];
219
+		$this->_model_relations        = [
220
+			'Event'                => new EE_Belongs_To_Relation(),
221
+			'Attendee'             => new EE_Belongs_To_Relation(),
222
+			'Transaction'          => new EE_Belongs_To_Relation(),
223
+			'Ticket'               => new EE_Belongs_To_Relation(),
224
+			'Status'               => new EE_Belongs_To_Relation(),
225
+			'Answer'               => new EE_Has_Many_Relation(),
226
+			'Checkin'              => new EE_Has_Many_Relation(),
227
+			'Registration_Payment' => new EE_Has_Many_Relation(),
228
+			'Payment'              => new EE_HABTM_Relation('Registration_Payment'),
229
+			'Message'              => new EE_Has_Many_Any_Relation(false),
230
+			// allow deletes even if there are messages in the queue related
231
+		];
232
+		$this->_model_chain_to_wp_user = 'Event';
233
+		parent::__construct($timezone);
234
+	}
235
+
236
+
237
+	/**
238
+	 * a list of ALL valid registration statuses currently in use within the system
239
+	 * generated by combining the filterable active and inactive reg status arrays
240
+	 *
241
+	 * @return array
242
+	 */
243
+	public static function reg_statuses(): array
244
+	{
245
+		return array_unique(
246
+			array_merge(
247
+				EEM_Registration::active_reg_statuses(),
248
+				EEM_Registration::inactive_reg_statuses()
249
+			)
250
+		);
251
+	}
252
+
253
+
254
+	/**
255
+	 * reg_statuses_that_allow_payment
256
+	 * a filterable list of registration statuses that allow a registrant to make a payment
257
+	 *
258
+	 * @access public
259
+	 * @return array
260
+	 */
261
+	public static function reg_statuses_that_allow_payment(): array
262
+	{
263
+		return (array) apply_filters(
264
+			'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
265
+			[
266
+				EEM_Registration::status_id_approved,
267
+				EEM_Registration::status_id_pending_payment,
268
+			]
269
+		);
270
+	}
271
+
272
+
273
+	/**
274
+	 * active_reg_statuses
275
+	 * a filterable list of registration statuses that are considered active
276
+	 *
277
+	 * @access public
278
+	 * @return array
279
+	 */
280
+	public static function active_reg_statuses(): array
281
+	{
282
+		return (array) apply_filters(
283
+			'FHEE__EEM_Registration__active_reg_statuses',
284
+			[
285
+				EEM_Registration::status_id_approved,
286
+				EEM_Registration::status_id_pending_payment,
287
+				EEM_Registration::status_id_wait_list,
288
+				EEM_Registration::status_id_not_approved,
289
+			]
290
+		);
291
+	}
292
+
293
+
294
+	/**
295
+	 * inactive_reg_statuses
296
+	 * a filterable list of registration statuses that are not considered active
297
+	 *
298
+	 * @access public
299
+	 * @return array
300
+	 */
301
+	public static function inactive_reg_statuses(): array
302
+	{
303
+		return (array) apply_filters(
304
+			'FHEE__EEM_Registration__inactive_reg_statuses',
305
+			[
306
+				EEM_Registration::status_id_incomplete,
307
+				EEM_Registration::status_id_cancelled,
308
+				EEM_Registration::status_id_declined,
309
+			]
310
+		);
311
+	}
312
+
313
+
314
+	/**
315
+	 *    closed_reg_statuses
316
+	 *    a filterable list of registration statuses that are considered "closed"
317
+	 * meaning they should not be considered in any calculations involving monies owing
318
+	 *
319
+	 * @access public
320
+	 * @return array
321
+	 */
322
+	public static function closed_reg_statuses(): array
323
+	{
324
+		return (array) apply_filters(
325
+			'FHEE__EEM_Registration__closed_reg_statuses',
326
+			[
327
+				EEM_Registration::status_id_cancelled,
328
+				EEM_Registration::status_id_declined,
329
+				EEM_Registration::status_id_wait_list,
330
+			]
331
+		);
332
+	}
333
+
334
+
335
+	/**
336
+	 * get list of registration statuses
337
+	 *
338
+	 * @param array $exclude    The status ids to exclude from the returned results
339
+	 * @param bool  $translated If true will return the values as singular localized strings
340
+	 * @return array
341
+	 * @throws EE_Error
342
+	 * @throws ReflectionException
343
+	 */
344
+	public static function reg_status_array(array $exclude = [], bool $translated = false): array
345
+	{
346
+		if (empty(self::$_reg_status)) {
347
+			EEM_Registration::instance()->_get_registration_status_array($exclude);
348
+		}
349
+		return $translated
350
+			? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
351
+			: self::$_reg_status;
352
+	}
353
+
354
+
355
+	/**
356
+	 * get list of registration statuses
357
+	 *
358
+	 * @param array $exclude
359
+	 * @param bool  $recurse
360
+	 * @return void
361
+	 * @throws EE_Error
362
+	 * @throws ReflectionException
363
+	 */
364
+	private function _get_registration_status_array(array $exclude = [], bool $recurse = true)
365
+	{
366
+		// in the very rare circumstance that we are deleting a model's table's data
367
+		// and the table hasn't actually been created, this could have an error
368
+		/** @type WPDB $wpdb */
369
+		global $wpdb;
370
+		if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
371
+			$results           = $wpdb->get_results(
372
+				"SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
373
+			);
374
+			self::$_reg_status = [];
375
+			foreach ($results as $status) {
376
+				if (! in_array($status->STS_ID, $exclude, true)) {
377
+					self::$_reg_status[ $status->STS_ID ] = $status->STS_code;
378
+				}
379
+			}
380
+		}
381
+		// in case reg status codes have been deleted from db
382
+		if ($recurse && empty(self::$_reg_status)) {
383
+			EEH_Activation::insert_default_status_codes();
384
+			EEM_Registration::instance()->_get_registration_status_array($exclude, false);
385
+		}
386
+	}
387
+
388
+
389
+	/**
390
+	 * Gets the injected table analyzer, or throws an exception
391
+	 *
392
+	 * @return TableAnalysis
393
+	 * @throws EE_Error
394
+	 */
395
+	protected function _get_table_analysis(): TableAnalysis
396
+	{
397
+		if ($this->_table_analysis instanceof TableAnalysis) {
398
+			return $this->_table_analysis;
399
+		}
400
+		throw new EE_Error(
401
+			sprintf(
402
+				esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
403
+				get_class($this)
404
+			)
405
+		);
406
+	}
407
+
408
+
409
+	/**
410
+	 * This returns a wpdb->results array of all registration date month and years matching the incoming query params
411
+	 * and grouped by month and year.
412
+	 *
413
+	 * @param array $where_params
414
+	 * @return bool|stdClass[]
415
+	 * @throws EE_Error
416
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
417
+	 */
418
+	public function get_reg_months_and_years(array $where_params)
419
+	{
420
+		$query_params[0]          = $where_params;
421
+		$query_params['group_by'] = ['reg_year', 'reg_month'];
422
+		$query_params['order_by'] = ['REG_date' => 'DESC'];
423
+		$columns_to_select        = [
424
+			'reg_year'  => ['YEAR(REG_date)', '%s'],
425
+			'reg_month' => ['MONTHNAME(REG_date)', '%s'],
426
+		];
427
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
428
+	}
429
+
430
+
431
+	/**
432
+	 * retrieve ALL registrations for a particular Attendee from db
433
+	 *
434
+	 * @param int $ATT_ID
435
+	 * @return EE_Registration[]|bool|null
436
+	 * @throws EE_Error
437
+	 * @throws ReflectionException
438
+	 */
439
+	public function get_all_registrations_for_attendee(int $ATT_ID = 0): ?array
440
+	{
441
+		if (! $ATT_ID) {
442
+			return null;
443
+		}
444
+		return $this->get_all([['ATT_ID' => $ATT_ID]]);
445
+	}
446
+
447
+
448
+	/**
449
+	 * Gets a registration given their REG_url_link. Yes, this should usually
450
+	 * be passed via a GET parameter.
451
+	 *
452
+	 * @param string $REG_url_link
453
+	 * @return EE_Registration|null
454
+	 * @throws EE_Error
455
+	 */
456
+	public function get_registration_for_reg_url_link(string $REG_url_link): ?EE_Registration
457
+	{
458
+		if (! $REG_url_link) {
459
+			return null;
460
+		}
461
+		return $this->get_one([['REG_url_link' => $REG_url_link]]);
462
+	}
463
+
464
+
465
+	/**
466
+	 *        retrieve registration for a specific transaction attendee from db
467
+	 *
468
+	 * @access        public
469
+	 * @param int $TXN_ID
470
+	 * @param int $ATT_ID
471
+	 * @param int $att_nmbr    in case the ATT_ID is the same for multiple registrations (same details used) then the
472
+	 *                         attendee number is required
473
+	 * @return EE_Registration|null array on success, FALSE on fail
474
+	 * @throws EE_Error
475
+	 */
476
+	public function get_registration_for_transaction_attendee(int $TXN_ID = 0, int $ATT_ID = 0, int $att_nmbr = 0):
477
+	?EE_Registration {
478
+		return $this->get_one(
479
+			[
480
+				[
481
+					'TXN_ID' => $TXN_ID,
482
+					'ATT_ID' => $ATT_ID,
483
+				],
484
+				'limit' => [min($att_nmbr - 1, 0), 1],
485
+			]
486
+		);
487
+	}
488
+
489
+
490
+	/**
491
+	 *        get the number of registrations per day  for the Registration Admin page Reports Tab.
492
+	 *        (doesn't utilize models because it's a fairly specialized query)
493
+	 *
494
+	 * @access        public
495
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
496
+	 * @return EE_Registration[]|bool|null with properties regDate and total
497
+	 * @throws EE_Error
498
+	 */
499
+	public function get_registrations_per_day_report(string $period = '-1 month')
500
+	{
501
+		$sql_date = $this->convert_datetime_for_query(
502
+			'REG_date',
503
+			date('Y-m-d H:i:s', strtotime($period)),
504
+			'Y-m-d H:i:s',
505
+			'UTC'
506
+		);
507
+		$where    = [
508
+			'REG_date' => ['>=', $sql_date],
509
+			'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
510
+		];
511
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
512
+			$where['Event.EVT_wp_user'] = get_current_user_id();
513
+		}
514
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
515
+		return $this->_get_all_wpdb_results(
516
+			[
517
+				$where,
518
+				'group_by' => 'regDate',
519
+				'order_by' => ['REG_date' => 'ASC'],
520
+			],
521
+			OBJECT,
522
+			[
523
+				'regDate' => ['DATE(' . $query_interval . ')', '%s'],
524
+				'total'   => ['count(REG_ID)', '%d'],
525
+			]
526
+		);
527
+	}
528
+
529
+
530
+	/**
531
+	 * Get the number of registrations per day including the count of registrations for each Registration Status.
532
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
533
+	 *
534
+	 * @param string $period
535
+	 * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
536
+	 * @throws EE_Error
537
+	 *                    (i.e. RAP)
538
+	 * @throws EE_Error|ReflectionException
539
+	 */
540
+	public function get_registrations_per_day_and_per_status_report(string $period = '-1 month'): array
541
+	{
542
+		global $wpdb;
543
+		$registration_table = $wpdb->prefix . 'esp_registration';
544
+		$event_table        = $wpdb->posts;
545
+		$sql_date           = date('Y-m-d H:i:s', strtotime($period));
546
+		// prepare the query interval for displaying offset
547
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
548
+		// inner date query
549
+		$inner_date_query = "SELECT DISTINCT REG_date from $registration_table ";
550
+		$inner_where      = ' WHERE';
551
+		// exclude events not authored by user if permissions in effect
552
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
553
+			$inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
554
+			$inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
555
+		}
556
+		$inner_where      .= " REG_date >= '$sql_date'";
557
+		$inner_date_query .= $inner_where;
558
+		// start main query
559
+		$select       = "SELECT DATE($query_interval) as Registration_REG_date, ";
560
+		$join         = '';
561
+		$join_parts   = [];
562
+		$select_parts = [];
563
+		// loop through registration stati to do parts for each status.
564
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
565
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
566
+				continue;
567
+			}
568
+			$select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
569
+			$join_parts[]   =
570
+				"$registration_table AS $STS_code ON $STS_code.REG_date = dates.REG_date AND $STS_code.STS_ID = '$STS_ID'";
571
+		}
572
+		// setup the selects
573
+		$select .= implode(', ', $select_parts);
574
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
575
+		// setup the joins
576
+		$join .= implode(' LEFT JOIN ', $join_parts);
577
+		// now let's put it all together
578
+		$query = $select . $join . ' GROUP BY Registration_REG_date';
579
+		// and execute it
580
+		return $wpdb->get_results($query, ARRAY_A);
581
+	}
582
+
583
+
584
+	/**
585
+	 *        get the number of registrations per event  for the Registration Admin page Reports Tab
586
+	 *
587
+	 * @access        public
588
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
589
+	 * @return stdClass[] each with properties event_name, reg_limit, and total
590
+	 * @throws EE_Error
591
+	 */
592
+	public function get_registrations_per_event_report(string $period = '-1 month'): array
593
+	{
594
+		$date_sql = $this->convert_datetime_for_query(
595
+			'REG_date',
596
+			date('Y-m-d H:i:s', strtotime($period)),
597
+			'Y-m-d H:i:s',
598
+			'UTC'
599
+		);
600
+		$where    = [
601
+			'REG_date' => ['>=', $date_sql],
602
+			'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
603
+		];
604
+		if (
605
+			! EE_Registry::instance()->CAP->current_user_can(
606
+				'ee_read_others_registrations',
607
+				'reg_per_event_report'
608
+			)
609
+		) {
610
+			$where['Event.EVT_wp_user'] = get_current_user_id();
611
+		}
612
+		return $this->_get_all_wpdb_results(
613
+			[
614
+				$where,
615
+				'group_by' => 'Event.EVT_name',
616
+				'order_by' => 'Event.EVT_name',
617
+				'limit'    => [0, 24],
618
+			],
619
+			OBJECT,
620
+			[
621
+				'event_name' => ['Event_CPT.post_title', '%s'],
622
+				'total'      => ['COUNT(REG_ID)', '%s'],
623
+			]
624
+		);
625
+	}
626
+
627
+
628
+	/**
629
+	 * Get the number of registrations per event grouped by registration status.
630
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
631
+	 *
632
+	 * @param string $period
633
+	 * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
634
+	 *                    (i.e. RAP)
635
+	 * @throws EE_Error
636
+	 * @throws ReflectionException
637
+	 */
638
+	public function get_registrations_per_event_and_per_status_report(string $period = '-1 month'): array
639
+	{
640
+		global $wpdb;
641
+		$registration_table = $wpdb->prefix . 'esp_registration';
642
+		$event_table        = $wpdb->posts;
643
+		$sql_date           = date('Y-m-d H:i:s', strtotime($period));
644
+		// inner date query
645
+		$inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
646
+		$inner_where      = ' WHERE';
647
+		// exclude events not authored by user if permissions in effect
648
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
649
+			$inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
650
+			$inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
651
+		}
652
+		$inner_where      .= " REG_date >= '$sql_date'";
653
+		$inner_date_query .= $inner_where;
654
+		// build main query
655
+		$select       = 'SELECT Event.post_title as Registration_Event, ';
656
+		$join         = '';
657
+		$join_parts   = [];
658
+		$select_parts = [];
659
+		// loop through registration stati to do parts for each status.
660
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
661
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
662
+				continue;
663
+			}
664
+			$select_parts[] = "COUNT($STS_code.REG_ID) as $STS_ID";
665
+			$join_parts[]   =
666
+				"$registration_table AS $STS_code ON $STS_code.EVT_ID = dates.EVT_ID AND $STS_code.STS_ID = '$STS_ID' AND $STS_code.REG_date = dates.REG_date";
667
+		}
668
+		// setup the selects
669
+		$select .= implode(', ', $select_parts);
670
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
671
+		// setup remaining joins
672
+		$join .= implode(' LEFT JOIN ', $join_parts);
673
+		// now put it all together
674
+		$query = $select . $join . ' GROUP BY Registration_Event';
675
+		// and execute
676
+		return $wpdb->get_results($query, ARRAY_A);
677
+	}
678
+
679
+
680
+	/**
681
+	 * Returns the EE_Registration of the primary attendee on the transaction id provided
682
+	 *
683
+	 * @param int $TXN_ID
684
+	 * @return EE_Registration|null
685
+	 * @throws EE_Error
686
+	 */
687
+	public function get_primary_registration_for_transaction_ID(int $TXN_ID = 0): ?EE_Registration
688
+	{
689
+		if (! $TXN_ID) {
690
+			return null;
691
+		}
692
+		return $this->get_one(
693
+			[
694
+				[
695
+					'TXN_ID'    => $TXN_ID,
696
+					'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
697
+				],
698
+			]
699
+		);
700
+	}
701
+
702
+
703
+	/**
704
+	 *        get_event_registration_count
705
+	 *
706
+	 * @access public
707
+	 * @param int     $EVT_ID
708
+	 * @param boolean $for_incomplete_payments
709
+	 * @return int
710
+	 * @throws EE_Error
711
+	 */
712
+	public function get_event_registration_count(int $EVT_ID, bool $for_incomplete_payments = false): int
713
+	{
714
+		// we only count approved registrations towards registration limits
715
+		$query_params = [['EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved]];
716
+		if ($for_incomplete_payments) {
717
+			$query_params[0]['Transaction.STS_ID'] = ['!=', EEM_Transaction::complete_status_code];
718
+		}
719
+		return $this->count($query_params);
720
+	}
721
+
722
+
723
+	/**
724
+	 * Deletes all registrations with no transactions. Note that this needs to be very efficient
725
+	 * and so it uses wpdb directly. Also, we can't put a limit on this because MySQL doesn't allow a limit on a delete
726
+	 * when joining tables like this.
727
+	 *
728
+	 * @return int|bool number deleted
729
+	 * @throws EE_Error
730
+	 * @throws ReflectionException
731
+	 * @global WPDB $wpdb
732
+	 */
733
+	public function delete_registrations_with_no_transaction()
734
+	{
735
+		/** @type WPDB $wpdb */
736
+		global $wpdb;
737
+		return $wpdb->query(
738
+			'DELETE r FROM '
739
+			. $this->table()
740
+			. ' r LEFT JOIN '
741
+			. EEM_Transaction::instance()->table()
742
+			. ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL'
743
+		);
744
+	}
745
+
746
+
747
+	/**
748
+	 *  Count registrations checked into (or out of) a datetime
749
+	 *
750
+	 * @param int  $DTT_ID     datetime ID
751
+	 * @param bool $checked_in whether to count registrations checked IN or OUT
752
+	 * @return int
753
+	 * @throws EE_Error
754
+	 * @throws ReflectionException
755
+	 * @throws ReflectionException
756
+	 */
757
+	public function count_registrations_checked_into_datetime(int $DTT_ID, bool $checked_in = true): int
758
+	{
759
+		global $wpdb;
760
+		// subquery to get latest checkin
761
+		$query = $wpdb->prepare(
762
+			'SELECT '
763
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
764
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
765
+			. '( SELECT '
766
+			. 'max( CHK_timestamp ) AS latest_checkin, '
767
+			. 'REG_ID AS REG_ID '
768
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' '
769
+			. 'WHERE DTT_ID=%d '
770
+			. 'GROUP BY REG_ID'
771
+			. ') AS most_recent_checkin_per_reg '
772
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
773
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
774
+			. 'WHERE '
775
+			. 'checkins.CHK_in=%d',
776
+			$DTT_ID,
777
+			$checked_in
778
+		);
779
+		return (int) $wpdb->get_var($query);
780
+	}
781
+
782
+
783
+	/**
784
+	 *  Count registrations checked into (or out of) an event.
785
+	 *
786
+	 * @param int  $EVT_ID     event ID
787
+	 * @param bool $checked_in whether to count registrations checked IN or OUT
788
+	 * @return int
789
+	 * @throws EE_Error
790
+	 * @throws ReflectionException
791
+	 * @throws ReflectionException
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function count_registrations_checked_into_event(int $EVT_ID, bool $checked_in = true): int
795
+	{
796
+		global $wpdb;
797
+		// subquery to get latest checkin
798
+		$query = $wpdb->prepare(
799
+			'SELECT '
800
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
801
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
802
+			. '( SELECT '
803
+			. 'max( CHK_timestamp ) AS latest_checkin, '
804
+			. 'REG_ID AS REG_ID '
805
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
806
+			. 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
807
+			. 'ON c.DTT_ID=d.DTT_ID '
808
+			. 'WHERE d.EVT_ID=%d '
809
+			. 'GROUP BY REG_ID'
810
+			. ') AS most_recent_checkin_per_reg '
811
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
812
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
813
+			. 'WHERE '
814
+			. 'checkins.CHK_in=%d',
815
+			$EVT_ID,
816
+			$checked_in
817
+		);
818
+		return (int) $wpdb->get_var($query);
819
+	}
820
+
821
+
822
+	/**
823
+	 * The purpose of this method is to retrieve an array of
824
+	 * EE_Registration objects that represent the latest registration
825
+	 * for each ATT_ID given in the function argument.
826
+	 *
827
+	 * @param array $attendee_ids
828
+	 * @return EE_Registration[]|bool|null
829
+	 * @throws EE_Error
830
+	 * @throws ReflectionException
831
+	 */
832
+	public function get_latest_registration_for_each_of_given_contacts(array $attendee_ids = [])
833
+	{
834
+		// first do a native wp_query to get the latest REG_ID's matching these attendees.
835
+		global $wpdb;
836
+		$registration_table = $wpdb->prefix . 'esp_registration';
837
+		$attendee_table     = $wpdb->posts;
838
+		$attendee_ids       = is_array($attendee_ids)
839
+			? array_map('absint', $attendee_ids)
840
+			: [(int) $attendee_ids];
841
+		$ATT_IDs            = implode(',', $attendee_ids);
842
+		// first we do a query to get the registration ids
843
+		// (because a group by before order by causes the order by to be ignored.)
844
+		$registration_id_query = "
845 845
 			SELECT registrations.registration_ids as registration_id
846 846
 			FROM (
847 847
 				SELECT
@@ -855,61 +855,61 @@  discard block
 block discarded – undo
855 855
 			  ) AS registrations
856 856
 			  GROUP BY registrations.attendee_ids
857 857
 		";
858
-        $registration_ids      = $wpdb->get_results($registration_id_query, ARRAY_A);
859
-        if (empty($registration_ids)) {
860
-            return [];
861
-        }
862
-        $ids_for_model_query = [];
863
-        // let's flatten the ids so they can be used in the model query.
864
-        foreach ($registration_ids as $registration_id) {
865
-            if (isset($registration_id['registration_id'])) {
866
-                $ids_for_model_query[] = $registration_id['registration_id'];
867
-            }
868
-        }
869
-        // construct query
870
-        $_where = [
871
-            'REG_ID' => ['IN', $ids_for_model_query],
872
-        ];
873
-        return $this->get_all([$_where]);
874
-    }
875
-
876
-
877
-    /**
878
-     * returns a count of registrations for the supplied event having the status as specified
879
-     *
880
-     * @param int          $EVT_ID
881
-     * @param array|string $statuses
882
-     * @return int
883
-     * @throws InvalidArgumentException
884
-     * @throws InvalidStatusException
885
-     * @throws EE_Error
886
-     */
887
-    public function event_reg_count_for_statuses(int $EVT_ID, $statuses = []): int
888
-    {
889
-        $EVT_ID = absint($EVT_ID);
890
-        if (! $EVT_ID) {
891
-            throw new InvalidArgumentException(
892
-                esc_html__('An invalid Event ID was supplied.', 'event_espresso')
893
-            );
894
-        }
895
-        $statuses = is_array($statuses) ? $statuses : [$statuses];
896
-        $statuses = ! empty($statuses) ? $statuses : [EEM_Registration::status_id_approved];
897
-
898
-        $valid_reg_statuses = EEM_Registration::reg_statuses();
899
-        foreach ($statuses as $status) {
900
-            if (! in_array($status, $valid_reg_statuses, true)) {
901
-                throw new InvalidStatusException($status, esc_html__('Registration', 'event_espresso'));
902
-            }
903
-        }
904
-        return $this->count(
905
-            [
906
-                [
907
-                    'EVT_ID' => $EVT_ID,
908
-                    'STS_ID' => ['IN', $statuses],
909
-                ],
910
-            ],
911
-            'REG_ID',
912
-            true
913
-        );
914
-    }
858
+		$registration_ids      = $wpdb->get_results($registration_id_query, ARRAY_A);
859
+		if (empty($registration_ids)) {
860
+			return [];
861
+		}
862
+		$ids_for_model_query = [];
863
+		// let's flatten the ids so they can be used in the model query.
864
+		foreach ($registration_ids as $registration_id) {
865
+			if (isset($registration_id['registration_id'])) {
866
+				$ids_for_model_query[] = $registration_id['registration_id'];
867
+			}
868
+		}
869
+		// construct query
870
+		$_where = [
871
+			'REG_ID' => ['IN', $ids_for_model_query],
872
+		];
873
+		return $this->get_all([$_where]);
874
+	}
875
+
876
+
877
+	/**
878
+	 * returns a count of registrations for the supplied event having the status as specified
879
+	 *
880
+	 * @param int          $EVT_ID
881
+	 * @param array|string $statuses
882
+	 * @return int
883
+	 * @throws InvalidArgumentException
884
+	 * @throws InvalidStatusException
885
+	 * @throws EE_Error
886
+	 */
887
+	public function event_reg_count_for_statuses(int $EVT_ID, $statuses = []): int
888
+	{
889
+		$EVT_ID = absint($EVT_ID);
890
+		if (! $EVT_ID) {
891
+			throw new InvalidArgumentException(
892
+				esc_html__('An invalid Event ID was supplied.', 'event_espresso')
893
+			);
894
+		}
895
+		$statuses = is_array($statuses) ? $statuses : [$statuses];
896
+		$statuses = ! empty($statuses) ? $statuses : [EEM_Registration::status_id_approved];
897
+
898
+		$valid_reg_statuses = EEM_Registration::reg_statuses();
899
+		foreach ($statuses as $status) {
900
+			if (! in_array($status, $valid_reg_statuses, true)) {
901
+				throw new InvalidStatusException($status, esc_html__('Registration', 'event_espresso'));
902
+			}
903
+		}
904
+		return $this->count(
905
+			[
906
+				[
907
+					'EVT_ID' => $EVT_ID,
908
+					'STS_ID' => ['IN', $statuses],
909
+				],
910
+			],
911
+			'REG_ID',
912
+			true
913
+		);
914
+	}
915 915
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
                 ),
217 217
             ],
218 218
         ];
219
-        $this->_model_relations        = [
219
+        $this->_model_relations = [
220 220
             'Event'                => new EE_Belongs_To_Relation(),
221 221
             'Attendee'             => new EE_Belongs_To_Relation(),
222 222
             'Transaction'          => new EE_Belongs_To_Relation(),
@@ -367,14 +367,14 @@  discard block
 block discarded – undo
367 367
         // and the table hasn't actually been created, this could have an error
368 368
         /** @type WPDB $wpdb */
369 369
         global $wpdb;
370
-        if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
370
+        if ($this->_get_table_analysis()->tableExists($wpdb->prefix.'esp_status')) {
371 371
             $results           = $wpdb->get_results(
372 372
                 "SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
373 373
             );
374 374
             self::$_reg_status = [];
375 375
             foreach ($results as $status) {
376
-                if (! in_array($status->STS_ID, $exclude, true)) {
377
-                    self::$_reg_status[ $status->STS_ID ] = $status->STS_code;
376
+                if ( ! in_array($status->STS_ID, $exclude, true)) {
377
+                    self::$_reg_status[$status->STS_ID] = $status->STS_code;
378 378
                 }
379 379
             }
380 380
         }
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
      */
439 439
     public function get_all_registrations_for_attendee(int $ATT_ID = 0): ?array
440 440
     {
441
-        if (! $ATT_ID) {
441
+        if ( ! $ATT_ID) {
442 442
             return null;
443 443
         }
444 444
         return $this->get_all([['ATT_ID' => $ATT_ID]]);
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
      */
456 456
     public function get_registration_for_reg_url_link(string $REG_url_link): ?EE_Registration
457 457
     {
458
-        if (! $REG_url_link) {
458
+        if ( ! $REG_url_link) {
459 459
             return null;
460 460
         }
461 461
         return $this->get_one([['REG_url_link' => $REG_url_link]]);
@@ -504,11 +504,11 @@  discard block
 block discarded – undo
504 504
             'Y-m-d H:i:s',
505 505
             'UTC'
506 506
         );
507
-        $where    = [
507
+        $where = [
508 508
             'REG_date' => ['>=', $sql_date],
509 509
             'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
510 510
         ];
511
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
511
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
512 512
             $where['Event.EVT_wp_user'] = get_current_user_id();
513 513
         }
514 514
         $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
             ],
521 521
             OBJECT,
522 522
             [
523
-                'regDate' => ['DATE(' . $query_interval . ')', '%s'],
523
+                'regDate' => ['DATE('.$query_interval.')', '%s'],
524 524
                 'total'   => ['count(REG_ID)', '%d'],
525 525
             ]
526 526
         );
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
     public function get_registrations_per_day_and_per_status_report(string $period = '-1 month'): array
541 541
     {
542 542
         global $wpdb;
543
-        $registration_table = $wpdb->prefix . 'esp_registration';
543
+        $registration_table = $wpdb->prefix.'esp_registration';
544 544
         $event_table        = $wpdb->posts;
545 545
         $sql_date           = date('Y-m-d H:i:s', strtotime($period));
546 546
         // prepare the query interval for displaying offset
@@ -549,9 +549,9 @@  discard block
 block discarded – undo
549 549
         $inner_date_query = "SELECT DISTINCT REG_date from $registration_table ";
550 550
         $inner_where      = ' WHERE';
551 551
         // exclude events not authored by user if permissions in effect
552
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
552
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
553 553
             $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
554
-            $inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
554
+            $inner_where      .= ' post_author = '.get_current_user_id().' AND';
555 555
         }
556 556
         $inner_where      .= " REG_date >= '$sql_date'";
557 557
         $inner_date_query .= $inner_where;
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
         // setup the joins
576 576
         $join .= implode(' LEFT JOIN ', $join_parts);
577 577
         // now let's put it all together
578
-        $query = $select . $join . ' GROUP BY Registration_REG_date';
578
+        $query = $select.$join.' GROUP BY Registration_REG_date';
579 579
         // and execute it
580 580
         return $wpdb->get_results($query, ARRAY_A);
581 581
     }
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
             'Y-m-d H:i:s',
598 598
             'UTC'
599 599
         );
600
-        $where    = [
600
+        $where = [
601 601
             'REG_date' => ['>=', $date_sql],
602 602
             'STS_ID'   => ['!=', EEM_Registration::status_id_incomplete],
603 603
         ];
@@ -638,16 +638,16 @@  discard block
 block discarded – undo
638 638
     public function get_registrations_per_event_and_per_status_report(string $period = '-1 month'): array
639 639
     {
640 640
         global $wpdb;
641
-        $registration_table = $wpdb->prefix . 'esp_registration';
641
+        $registration_table = $wpdb->prefix.'esp_registration';
642 642
         $event_table        = $wpdb->posts;
643 643
         $sql_date           = date('Y-m-d H:i:s', strtotime($period));
644 644
         // inner date query
645 645
         $inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
646 646
         $inner_where      = ' WHERE';
647 647
         // exclude events not authored by user if permissions in effect
648
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
648
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
649 649
             $inner_date_query .= "LEFT JOIN $event_table ON ID = EVT_ID";
650
-            $inner_where      .= ' post_author = ' . get_current_user_id() . ' AND';
650
+            $inner_where      .= ' post_author = '.get_current_user_id().' AND';
651 651
         }
652 652
         $inner_where      .= " REG_date >= '$sql_date'";
653 653
         $inner_date_query .= $inner_where;
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
         // setup remaining joins
672 672
         $join .= implode(' LEFT JOIN ', $join_parts);
673 673
         // now put it all together
674
-        $query = $select . $join . ' GROUP BY Registration_Event';
674
+        $query = $select.$join.' GROUP BY Registration_Event';
675 675
         // and execute
676 676
         return $wpdb->get_results($query, ARRAY_A);
677 677
     }
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
      */
687 687
     public function get_primary_registration_for_transaction_ID(int $TXN_ID = 0): ?EE_Registration
688 688
     {
689
-        if (! $TXN_ID) {
689
+        if ( ! $TXN_ID) {
690 690
             return null;
691 691
         }
692 692
         return $this->get_one(
@@ -761,11 +761,11 @@  discard block
 block discarded – undo
761 761
         $query = $wpdb->prepare(
762 762
             'SELECT '
763 763
             . 'COUNT( DISTINCT checkins.REG_ID ) '
764
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
764
+            . 'FROM '.EEM_Checkin::instance()->table().' AS checkins INNER JOIN'
765 765
             . '( SELECT '
766 766
             . 'max( CHK_timestamp ) AS latest_checkin, '
767 767
             . 'REG_ID AS REG_ID '
768
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' '
768
+            . 'FROM '.EEM_Checkin::instance()->table().' '
769 769
             . 'WHERE DTT_ID=%d '
770 770
             . 'GROUP BY REG_ID'
771 771
             . ') AS most_recent_checkin_per_reg '
@@ -798,12 +798,12 @@  discard block
 block discarded – undo
798 798
         $query = $wpdb->prepare(
799 799
             'SELECT '
800 800
             . 'COUNT( DISTINCT checkins.REG_ID ) '
801
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
801
+            . 'FROM '.EEM_Checkin::instance()->table().' AS checkins INNER JOIN'
802 802
             . '( SELECT '
803 803
             . 'max( CHK_timestamp ) AS latest_checkin, '
804 804
             . 'REG_ID AS REG_ID '
805
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
806
-            . 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
805
+            . 'FROM '.EEM_Checkin::instance()->table().' AS c '
806
+            . 'INNER JOIN '.EEM_Datetime::instance()->table().' AS d '
807 807
             . 'ON c.DTT_ID=d.DTT_ID '
808 808
             . 'WHERE d.EVT_ID=%d '
809 809
             . 'GROUP BY REG_ID'
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
     {
834 834
         // first do a native wp_query to get the latest REG_ID's matching these attendees.
835 835
         global $wpdb;
836
-        $registration_table = $wpdb->prefix . 'esp_registration';
836
+        $registration_table = $wpdb->prefix.'esp_registration';
837 837
         $attendee_table     = $wpdb->posts;
838 838
         $attendee_ids       = is_array($attendee_ids)
839 839
             ? array_map('absint', $attendee_ids)
@@ -855,7 +855,7 @@  discard block
 block discarded – undo
855 855
 			  ) AS registrations
856 856
 			  GROUP BY registrations.attendee_ids
857 857
 		";
858
-        $registration_ids      = $wpdb->get_results($registration_id_query, ARRAY_A);
858
+        $registration_ids = $wpdb->get_results($registration_id_query, ARRAY_A);
859 859
         if (empty($registration_ids)) {
860 860
             return [];
861 861
         }
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
     public function event_reg_count_for_statuses(int $EVT_ID, $statuses = []): int
888 888
     {
889 889
         $EVT_ID = absint($EVT_ID);
890
-        if (! $EVT_ID) {
890
+        if ( ! $EVT_ID) {
891 891
             throw new InvalidArgumentException(
892 892
                 esc_html__('An invalid Event ID was supplied.', 'event_espresso')
893 893
             );
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
 
898 898
         $valid_reg_statuses = EEM_Registration::reg_statuses();
899 899
         foreach ($statuses as $status) {
900
-            if (! in_array($status, $valid_reg_statuses, true)) {
900
+            if ( ! in_array($status, $valid_reg_statuses, true)) {
901 901
                 throw new InvalidStatusException($status, esc_html__('Registration', 'event_espresso'));
902 902
             }
903 903
         }
Please login to merge, or discard this patch.
core/db_models/EEM_Term.model.php 2 patches
Indentation   +242 added lines, -242 removed lines patch added patch discarded remove patch
@@ -13,262 +13,262 @@
 block discarded – undo
13 13
  */
14 14
 class EEM_Term extends EEM_Base
15 15
 {
16
-    // private instance of the Attendee object
17
-    protected static $_instance = null;
16
+	// private instance of the Attendee object
17
+	protected static $_instance = null;
18 18
 
19 19
 
20
-    /**
21
-     * @param string|null $timezone
22
-     * @throws EE_Error
23
-     */
24
-    protected function __construct(?string $timezone = '')
25
-    {
26
-        $this->singular_item                                            = esc_html__('Term', 'event_espresso');
27
-        $this->plural_item                                              = esc_html__('Terms', 'event_espresso');
28
-        $this->_tables                                                  = [
29
-            'Term' => new EE_Primary_Table('terms', 'term_id'),
30
-        ];
31
-        $this->_fields                                                  = [
32
-            'Term' => [
33
-                'term_id'    => new EE_Primary_Key_Int_Field('term_id', esc_html__('Term ID', 'event_espresso')),
34
-                'name'       => new EE_Plain_Text_Field('name', esc_html__('Term Name', 'event_espresso'), false, ''),
35
-                'slug'       => new EE_Slug_Field('slug', esc_html__('Term Slug', 'event_espresso'), false),
36
-                'term_group' => new EE_Integer_Field(
37
-                    'term_group', esc_html__("Term Group", "event_espresso"), false, 0
38
-                ),
39
-            ],
40
-        ];
41
-        $this->_model_relations                                         = [
42
-            'Term_Taxonomy' => new EE_Has_Many_Relation(),
43
-        ];
44
-        $this->_wp_core_model                                           = true;
45
-        $path_to_tax_model                                              = 'Term_Taxonomy';
46
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
47
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
48
-            new EE_Restriction_Generator_Taxonomy_Protected(
49
-                $path_to_tax_model
50
-            );
51
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = false;
52
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = false;
53
-        $path_to_tax_model                                              = $path_to_tax_model . '.';
54
-        // add cap restrictions for editing relating to the "ee_edit_*"
55
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
56
-            [
57
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => ['!=', 'espresso_event_categories'],
58
-            ]
59
-        );
60
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
61
-            [
62
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => ['!=', 'espresso_venue_categories'],
63
-            ]
64
-        );
65
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type']     = new EE_Default_Where_Conditions(
66
-            [
67
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => ['!=', 'espresso_event_type'],
68
-            ]
69
-        );
70
-        // add cap restrictions for deleting relating to the "ee_deleting_*"
71
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
72
-            [
73
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => ['!=', 'espresso_event_categories'],
74
-            ]
75
-        );
76
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
77
-            [
78
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => ['!=', 'espresso_venue_categories'],
79
-            ]
80
-        );
81
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type']     = new EE_Default_Where_Conditions(
82
-            [
83
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => ['!=', 'espresso_event_type'],
84
-            ]
85
-        );
86
-        parent::__construct($timezone);
87
-        add_filter('FHEE__Read__create_model_query_params', ['EEM_Term', 'rest_api_query_params'], 10, 3);
88
-    }
20
+	/**
21
+	 * @param string|null $timezone
22
+	 * @throws EE_Error
23
+	 */
24
+	protected function __construct(?string $timezone = '')
25
+	{
26
+		$this->singular_item                                            = esc_html__('Term', 'event_espresso');
27
+		$this->plural_item                                              = esc_html__('Terms', 'event_espresso');
28
+		$this->_tables                                                  = [
29
+			'Term' => new EE_Primary_Table('terms', 'term_id'),
30
+		];
31
+		$this->_fields                                                  = [
32
+			'Term' => [
33
+				'term_id'    => new EE_Primary_Key_Int_Field('term_id', esc_html__('Term ID', 'event_espresso')),
34
+				'name'       => new EE_Plain_Text_Field('name', esc_html__('Term Name', 'event_espresso'), false, ''),
35
+				'slug'       => new EE_Slug_Field('slug', esc_html__('Term Slug', 'event_espresso'), false),
36
+				'term_group' => new EE_Integer_Field(
37
+					'term_group', esc_html__("Term Group", "event_espresso"), false, 0
38
+				),
39
+			],
40
+		];
41
+		$this->_model_relations                                         = [
42
+			'Term_Taxonomy' => new EE_Has_Many_Relation(),
43
+		];
44
+		$this->_wp_core_model                                           = true;
45
+		$path_to_tax_model                                              = 'Term_Taxonomy';
46
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
47
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
48
+			new EE_Restriction_Generator_Taxonomy_Protected(
49
+				$path_to_tax_model
50
+			);
51
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = false;
52
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = false;
53
+		$path_to_tax_model                                              = $path_to_tax_model . '.';
54
+		// add cap restrictions for editing relating to the "ee_edit_*"
55
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
56
+			[
57
+				$path_to_tax_model . 'taxonomy*ee_edit_event_category' => ['!=', 'espresso_event_categories'],
58
+			]
59
+		);
60
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
61
+			[
62
+				$path_to_tax_model . 'taxonomy*ee_edit_venue_category' => ['!=', 'espresso_venue_categories'],
63
+			]
64
+		);
65
+		$this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type']     = new EE_Default_Where_Conditions(
66
+			[
67
+				$path_to_tax_model . 'taxonomy*ee_edit_event_type' => ['!=', 'espresso_event_type'],
68
+			]
69
+		);
70
+		// add cap restrictions for deleting relating to the "ee_deleting_*"
71
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
72
+			[
73
+				$path_to_tax_model . 'taxonomy*ee_delete_event_category' => ['!=', 'espresso_event_categories'],
74
+			]
75
+		);
76
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
77
+			[
78
+				$path_to_tax_model . 'taxonomy*ee_delete_venue_category' => ['!=', 'espresso_venue_categories'],
79
+			]
80
+		);
81
+		$this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type']     = new EE_Default_Where_Conditions(
82
+			[
83
+				$path_to_tax_model . 'taxonomy*ee_delete_event_type' => ['!=', 'espresso_event_type'],
84
+			]
85
+		);
86
+		parent::__construct($timezone);
87
+		add_filter('FHEE__Read__create_model_query_params', ['EEM_Term', 'rest_api_query_params'], 10, 3);
88
+	}
89 89
 
90 90
 
91
-    /**
92
-     * retrieves a list of all EE event categories
93
-     *
94
-     * @access public
95
-     * @param bool $show_uncategorized
96
-     * @return \EE_Base_Class[]
97
-     */
98
-    public function get_all_ee_categories($show_uncategorized = false)
99
-    {
100
-        $where_params = [
101
-            'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
102
-            'NOT'                    => ['name' => esc_html__('Uncategorized', 'event_espresso')],
103
-        ];
104
-        if ($show_uncategorized) {
105
-            unset($where_params['NOT']);
106
-        }
107
-        return EEM_Term::instance()->get_all(
108
-            [
109
-                $where_params,
110
-                'order_by' => ['name' => 'ASC'],
111
-            ]
112
-        );
113
-    }
91
+	/**
92
+	 * retrieves a list of all EE event categories
93
+	 *
94
+	 * @access public
95
+	 * @param bool $show_uncategorized
96
+	 * @return \EE_Base_Class[]
97
+	 */
98
+	public function get_all_ee_categories($show_uncategorized = false)
99
+	{
100
+		$where_params = [
101
+			'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
102
+			'NOT'                    => ['name' => esc_html__('Uncategorized', 'event_espresso')],
103
+		];
104
+		if ($show_uncategorized) {
105
+			unset($where_params['NOT']);
106
+		}
107
+		return EEM_Term::instance()->get_all(
108
+			[
109
+				$where_params,
110
+				'order_by' => ['name' => 'ASC'],
111
+			]
112
+		);
113
+	}
114 114
 
115 115
 
116
-    /**
117
-     * retrieves a list of all post_tags associated with an EE CPT
118
-     *
119
-     * @access public
120
-     * @param string $post_type
121
-     * @return array
122
-     */
123
-    public function get_all_CPT_post_tags($post_type = '')
124
-    {
125
-        switch ($post_type) {
126
-            case 'espresso_events':
127
-                return $this->get_all_event_post_tags();
128
-                break;
129
-            case 'espresso_venues':
130
-                return $this->get_all_venue_post_tags();
131
-                break;
132
-            default:
133
-                $event_tags = $this->get_all_event_post_tags();
134
-                $venue_tags = $this->get_all_venue_post_tags();
135
-                return array_merge($event_tags, $venue_tags);
136
-        }
137
-    }
116
+	/**
117
+	 * retrieves a list of all post_tags associated with an EE CPT
118
+	 *
119
+	 * @access public
120
+	 * @param string $post_type
121
+	 * @return array
122
+	 */
123
+	public function get_all_CPT_post_tags($post_type = '')
124
+	{
125
+		switch ($post_type) {
126
+			case 'espresso_events':
127
+				return $this->get_all_event_post_tags();
128
+				break;
129
+			case 'espresso_venues':
130
+				return $this->get_all_venue_post_tags();
131
+				break;
132
+			default:
133
+				$event_tags = $this->get_all_event_post_tags();
134
+				$venue_tags = $this->get_all_venue_post_tags();
135
+				return array_merge($event_tags, $venue_tags);
136
+		}
137
+	}
138 138
 
139 139
 
140
-    /**
141
-     * returns an EE_Term object for the given tag
142
-     * if it has been utilized by any EE_Events or EE_Venues
143
-     *
144
-     * @param string $tag
145
-     * @return EE_Term|null
146
-     * @throws EE_Error
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidDataTypeException
149
-     * @throws InvalidInterfaceException
150
-     */
151
-    public function get_post_tag_for_event_or_venue($tag)
152
-    {
153
-        $post_tag_results = $this->get_all_wpdb_results(
154
-            [
155
-                [
156
-                    'slug'                   => $tag,
157
-                    'Term_Taxonomy.taxonomy' => 'post_tag',
158
-                    'OR'                     => [
159
-                        'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
160
-                        'Term_Taxonomy.Event.post_type' => 'espresso_events',
161
-                    ],
162
-                ],
163
-                'default_where_conditions' => 'none',
164
-                'extra_selects'            => [
165
-                    'event_post_type' => ['Term_Taxonomy___Event_CPT.post_type', '%s'],
166
-                    'venue_post_type' => ['Term_Taxonomy___Venue_CPT.post_type', '%s'],
167
-                ],
168
-                'group_by'                 => [
169
-                    'event_post_type',
170
-                    'venue_post_type',
171
-                ],
172
-                'limit'                    => 2,
173
-            ]
174
-        );
175
-        if (! $post_tag_results) {
176
-            return null;
177
-        }
140
+	/**
141
+	 * returns an EE_Term object for the given tag
142
+	 * if it has been utilized by any EE_Events or EE_Venues
143
+	 *
144
+	 * @param string $tag
145
+	 * @return EE_Term|null
146
+	 * @throws EE_Error
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws InvalidInterfaceException
150
+	 */
151
+	public function get_post_tag_for_event_or_venue($tag)
152
+	{
153
+		$post_tag_results = $this->get_all_wpdb_results(
154
+			[
155
+				[
156
+					'slug'                   => $tag,
157
+					'Term_Taxonomy.taxonomy' => 'post_tag',
158
+					'OR'                     => [
159
+						'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
160
+						'Term_Taxonomy.Event.post_type' => 'espresso_events',
161
+					],
162
+				],
163
+				'default_where_conditions' => 'none',
164
+				'extra_selects'            => [
165
+					'event_post_type' => ['Term_Taxonomy___Event_CPT.post_type', '%s'],
166
+					'venue_post_type' => ['Term_Taxonomy___Venue_CPT.post_type', '%s'],
167
+				],
168
+				'group_by'                 => [
169
+					'event_post_type',
170
+					'venue_post_type',
171
+				],
172
+				'limit'                    => 2,
173
+			]
174
+		);
175
+		if (! $post_tag_results) {
176
+			return null;
177
+		}
178 178
 
179
-        $post_types = [];
180
-        foreach ((array) $post_tag_results as $row) {
181
-            if ($row['event_post_type'] === 'espresso_events') {
182
-                $post_types[] = EEM_Event::instance()->post_type();
183
-            } elseif ($row['venue_post_type'] === 'espresso_venues') {
184
-                $post_types[] = EEM_Venue::instance()->post_type();
185
-            }
186
-        }
187
-        $post_tag_row = reset($post_tag_results);
188
-        $post_tag     = $this->instantiate_class_from_array_or_object($post_tag_row);
189
-        if (! $post_tag instanceof EE_Term) {
190
-            return null;
191
-        }
179
+		$post_types = [];
180
+		foreach ((array) $post_tag_results as $row) {
181
+			if ($row['event_post_type'] === 'espresso_events') {
182
+				$post_types[] = EEM_Event::instance()->post_type();
183
+			} elseif ($row['venue_post_type'] === 'espresso_venues') {
184
+				$post_types[] = EEM_Venue::instance()->post_type();
185
+			}
186
+		}
187
+		$post_tag_row = reset($post_tag_results);
188
+		$post_tag     = $this->instantiate_class_from_array_or_object($post_tag_row);
189
+		if (! $post_tag instanceof EE_Term) {
190
+			return null;
191
+		}
192 192
 
193
-        if ($post_tag->post_type === null) {
194
-            $post_tag->post_type = [];
195
-        }
196
-        $post_tag->post_type = array_merge($post_tag->post_type, array_unique($post_types));
197
-        return $post_tag;
198
-    }
193
+		if ($post_tag->post_type === null) {
194
+			$post_tag->post_type = [];
195
+		}
196
+		$post_tag->post_type = array_merge($post_tag->post_type, array_unique($post_types));
197
+		return $post_tag;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * get_all_event_post_tags
203
-     *
204
-     * @return EE_Base_Class[]
205
-     */
206
-    public function get_all_event_post_tags()
207
-    {
208
-        $post_tags = EEM_Term::instance()->get_all(
209
-            [
210
-                [
211
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
212
-                    'Term_Taxonomy.Event.post_type' => 'espresso_events',
213
-                ],
214
-                'order_by'   => ['name' => 'ASC'],
215
-                'force_join' => ['Term_Taxonomy.Event'],
216
-            ]
217
-        );
218
-        foreach ($post_tags as $key => $post_tag) {
219
-            if (! isset($post_tags[ $key ]->post_type)) {
220
-                $post_tags[ $key ]->post_type = [];
221
-            }
222
-            $post_tags[ $key ]->post_type[] = 'espresso_events';
223
-        }
224
-        return $post_tags;
225
-    }
201
+	/**
202
+	 * get_all_event_post_tags
203
+	 *
204
+	 * @return EE_Base_Class[]
205
+	 */
206
+	public function get_all_event_post_tags()
207
+	{
208
+		$post_tags = EEM_Term::instance()->get_all(
209
+			[
210
+				[
211
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
212
+					'Term_Taxonomy.Event.post_type' => 'espresso_events',
213
+				],
214
+				'order_by'   => ['name' => 'ASC'],
215
+				'force_join' => ['Term_Taxonomy.Event'],
216
+			]
217
+		);
218
+		foreach ($post_tags as $key => $post_tag) {
219
+			if (! isset($post_tags[ $key ]->post_type)) {
220
+				$post_tags[ $key ]->post_type = [];
221
+			}
222
+			$post_tags[ $key ]->post_type[] = 'espresso_events';
223
+		}
224
+		return $post_tags;
225
+	}
226 226
 
227 227
 
228
-    /**
229
-     * get_all_venue_post_tags
230
-     *
231
-     * @return EE_Base_Class[]
232
-     */
233
-    public function get_all_venue_post_tags()
234
-    {
235
-        $post_tags = EEM_Term::instance()->get_all(
236
-            [
237
-                [
238
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
239
-                    'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
240
-                ],
241
-                'order_by'   => ['name' => 'ASC'],
242
-                'force_join' => ['Term_Taxonomy'],
243
-            ]
244
-        );
245
-        foreach ($post_tags as $key => $post_tag) {
246
-            if (! isset($post_tags[ $key ]->post_type)) {
247
-                $post_tags[ $key ]->post_type = [];
248
-            }
249
-            $post_tags[ $key ]->post_type[] = 'espresso_venues';
250
-        }
251
-        return $post_tags;
252
-    }
228
+	/**
229
+	 * get_all_venue_post_tags
230
+	 *
231
+	 * @return EE_Base_Class[]
232
+	 */
233
+	public function get_all_venue_post_tags()
234
+	{
235
+		$post_tags = EEM_Term::instance()->get_all(
236
+			[
237
+				[
238
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
239
+					'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
240
+				],
241
+				'order_by'   => ['name' => 'ASC'],
242
+				'force_join' => ['Term_Taxonomy'],
243
+			]
244
+		);
245
+		foreach ($post_tags as $key => $post_tag) {
246
+			if (! isset($post_tags[ $key ]->post_type)) {
247
+				$post_tags[ $key ]->post_type = [];
248
+			}
249
+			$post_tags[ $key ]->post_type[] = 'espresso_venues';
250
+		}
251
+		return $post_tags;
252
+	}
253 253
 
254 254
 
255
-    /**
256
-     * Makes sure that during REST API queries, we only return terms
257
-     * for term taxonomies which should be shown in the rest api
258
-     *
259
-     * @param array    $model_query_params
260
-     * @param array    $querystring_query_params
261
-     * @param EEM_Base $model
262
-     * @return array
263
-     */
264
-    public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
265
-    {
266
-        if ($model === EEM_Term::instance()) {
267
-            $taxonomies = get_taxonomies(['show_in_rest' => true]);
268
-            if (! empty($taxonomies)) {
269
-                $model_query_params[0]['Term_Taxonomy.taxonomy'] = ['IN', $taxonomies];
270
-            }
271
-        }
272
-        return $model_query_params;
273
-    }
255
+	/**
256
+	 * Makes sure that during REST API queries, we only return terms
257
+	 * for term taxonomies which should be shown in the rest api
258
+	 *
259
+	 * @param array    $model_query_params
260
+	 * @param array    $querystring_query_params
261
+	 * @param EEM_Base $model
262
+	 * @return array
263
+	 */
264
+	public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
265
+	{
266
+		if ($model === EEM_Term::instance()) {
267
+			$taxonomies = get_taxonomies(['show_in_rest' => true]);
268
+			if (! empty($taxonomies)) {
269
+				$model_query_params[0]['Term_Taxonomy.taxonomy'] = ['IN', $taxonomies];
270
+			}
271
+		}
272
+		return $model_query_params;
273
+	}
274 274
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -43,44 +43,44 @@  discard block
 block discarded – undo
43 43
         ];
44 44
         $this->_wp_core_model                                           = true;
45 45
         $path_to_tax_model                                              = 'Term_Taxonomy';
46
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Public();
47
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
46
+        $this->_cap_restriction_generators[EEM_Base::caps_read]       = new EE_Restriction_Generator_Public();
47
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
48 48
             new EE_Restriction_Generator_Taxonomy_Protected(
49 49
                 $path_to_tax_model
50 50
             );
51
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = false;
52
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = false;
53
-        $path_to_tax_model                                              = $path_to_tax_model . '.';
51
+        $this->_cap_restriction_generators[EEM_Base::caps_edit]       = false;
52
+        $this->_cap_restriction_generators[EEM_Base::caps_delete]     = false;
53
+        $path_to_tax_model                                              = $path_to_tax_model.'.';
54 54
         // add cap restrictions for editing relating to the "ee_edit_*"
55
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
55
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
56 56
             [
57
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => ['!=', 'espresso_event_categories'],
57
+                $path_to_tax_model.'taxonomy*ee_edit_event_category' => ['!=', 'espresso_event_categories'],
58 58
             ]
59 59
         );
60
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
60
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
61 61
             [
62
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => ['!=', 'espresso_venue_categories'],
62
+                $path_to_tax_model.'taxonomy*ee_edit_venue_category' => ['!=', 'espresso_venue_categories'],
63 63
             ]
64 64
         );
65
-        $this->_cap_restrictions[ EEM_Base::caps_edit ]['ee_edit_event_type']     = new EE_Default_Where_Conditions(
65
+        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
66 66
             [
67
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => ['!=', 'espresso_event_type'],
67
+                $path_to_tax_model.'taxonomy*ee_edit_event_type' => ['!=', 'espresso_event_type'],
68 68
             ]
69 69
         );
70 70
         // add cap restrictions for deleting relating to the "ee_deleting_*"
71
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
71
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
72 72
             [
73
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => ['!=', 'espresso_event_categories'],
73
+                $path_to_tax_model.'taxonomy*ee_delete_event_category' => ['!=', 'espresso_event_categories'],
74 74
             ]
75 75
         );
76
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
76
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
77 77
             [
78
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => ['!=', 'espresso_venue_categories'],
78
+                $path_to_tax_model.'taxonomy*ee_delete_venue_category' => ['!=', 'espresso_venue_categories'],
79 79
             ]
80 80
         );
81
-        $this->_cap_restrictions[ EEM_Base::caps_delete ]['ee_delete_event_type']     = new EE_Default_Where_Conditions(
81
+        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
82 82
             [
83
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => ['!=', 'espresso_event_type'],
83
+                $path_to_tax_model.'taxonomy*ee_delete_event_type' => ['!=', 'espresso_event_type'],
84 84
             ]
85 85
         );
86 86
         parent::__construct($timezone);
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
                 'limit'                    => 2,
173 173
             ]
174 174
         );
175
-        if (! $post_tag_results) {
175
+        if ( ! $post_tag_results) {
176 176
             return null;
177 177
         }
178 178
 
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
         }
187 187
         $post_tag_row = reset($post_tag_results);
188 188
         $post_tag     = $this->instantiate_class_from_array_or_object($post_tag_row);
189
-        if (! $post_tag instanceof EE_Term) {
189
+        if ( ! $post_tag instanceof EE_Term) {
190 190
             return null;
191 191
         }
192 192
 
@@ -216,10 +216,10 @@  discard block
 block discarded – undo
216 216
             ]
217 217
         );
218 218
         foreach ($post_tags as $key => $post_tag) {
219
-            if (! isset($post_tags[ $key ]->post_type)) {
220
-                $post_tags[ $key ]->post_type = [];
219
+            if ( ! isset($post_tags[$key]->post_type)) {
220
+                $post_tags[$key]->post_type = [];
221 221
             }
222
-            $post_tags[ $key ]->post_type[] = 'espresso_events';
222
+            $post_tags[$key]->post_type[] = 'espresso_events';
223 223
         }
224 224
         return $post_tags;
225 225
     }
@@ -243,10 +243,10 @@  discard block
 block discarded – undo
243 243
             ]
244 244
         );
245 245
         foreach ($post_tags as $key => $post_tag) {
246
-            if (! isset($post_tags[ $key ]->post_type)) {
247
-                $post_tags[ $key ]->post_type = [];
246
+            if ( ! isset($post_tags[$key]->post_type)) {
247
+                $post_tags[$key]->post_type = [];
248 248
             }
249
-            $post_tags[ $key ]->post_type[] = 'espresso_venues';
249
+            $post_tags[$key]->post_type[] = 'espresso_venues';
250 250
         }
251 251
         return $post_tags;
252 252
     }
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
     {
266 266
         if ($model === EEM_Term::instance()) {
267 267
             $taxonomies = get_taxonomies(['show_in_rest' => true]);
268
-            if (! empty($taxonomies)) {
268
+            if ( ! empty($taxonomies)) {
269 269
                 $model_query_params[0]['Term_Taxonomy.taxonomy'] = ['IN', $taxonomies];
270 270
             }
271 271
         }
Please login to merge, or discard this patch.
core/db_models/EEM_CPT_Base.model.php 2 patches
Indentation   +560 added lines, -560 removed lines patch added patch discarded remove patch
@@ -14,564 +14,564 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
16 16
 {
17
-    const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
-
19
-    /**
20
-     * @var string post_status_publish - the wp post status for published cpts
21
-     */
22
-    const post_status_publish = 'publish';
23
-
24
-    /**
25
-     * @var string post_status_future - the wp post status for scheduled cpts
26
-     */
27
-    const post_status_future = 'future';
28
-
29
-    /**
30
-     * @var string post_status_draft - the wp post status for draft cpts
31
-     */
32
-    const post_status_draft = 'draft';
33
-
34
-    /**
35
-     * @var string post_status_pending - the wp post status for pending cpts
36
-     */
37
-    const post_status_pending = 'pending';
38
-
39
-    /**
40
-     * @var string post_status_private - the wp post status for private cpts
41
-     */
42
-    const post_status_private = 'private';
43
-
44
-    /**
45
-     * @var string post_status_trashed - the wp post status for trashed cpts
46
-     */
47
-    const post_status_trashed = 'trash';
48
-
49
-    /**
50
-     * This is an array of custom statuses for the given CPT model (modified by children)
51
-     * format:
52
-     * array(
53
-     *        'status_name' => array(
54
-     *            'label' => esc_html__('Status Name', 'event_espresso'),
55
-     *            'public' => TRUE //whether a public status or not.
56
-     *        )
57
-     * )
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_custom_stati = [];
62
-
63
-
64
-    /**
65
-     * @param string|null $timezone
66
-     * @throws EE_Error
67
-     */
68
-    protected function __construct(?string $timezone = '')
69
-    {
70
-        // adds a relationship to Term_Taxonomy for all these models. For this to work
71
-        // Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
72
-        // eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
73
-        // with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
74
-        // must also be new EE_HABTM_Relation('Term_Relationship');
75
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
76
-        $primary_table_name                      = null;
77
-        // add  the common _status field to all CPT primary tables.
78
-        foreach ($this->_tables as $alias => $table_obj) {
79
-            if ($table_obj instanceof EE_Primary_Table) {
80
-                $primary_table_name = $alias;
81
-            }
82
-        }
83
-        // set default wp post statuses if child has not already set.
84
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
86
-                'post_status',
87
-                esc_html__("Event Status", "event_espresso"),
88
-                false,
89
-                'draft'
90
-            );
91
-        }
92
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
94
-                'to_ping',
95
-                esc_html__('To Ping', 'event_espresso'),
96
-                false,
97
-                ''
98
-            );
99
-        }
100
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
102
-                'pinged',
103
-                esc_html__('Pinged', 'event_espresso'),
104
-                false,
105
-                ''
106
-            );
107
-        }
108
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
110
-                'comment_status',
111
-                esc_html__('Comment Status', 'event_espresso'),
112
-                false,
113
-                'open'
114
-            );
115
-        }
116
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
118
-                'ping_status',
119
-                esc_html__('Ping Status', 'event_espresso'),
120
-                false,
121
-                'open'
122
-            );
123
-        }
124
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126
-                'post_content_filtered',
127
-                esc_html__('Post Content Filtered', 'event_espresso'),
128
-                false,
129
-                ''
130
-            );
131
-        }
132
-        if (! isset($this->_model_relations['Post_Meta'])) {
133
-            // don't block deletes though because we want to maintain the current behaviour
134
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135
-        }
136
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137
-            // nothing was set during child constructor, so set default
138
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139
-        }
140
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141
-            // nothing was set during child constructor, so set default
142
-            // it's ok for child classes to specify this, but generally this is more DRY
143
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
144
-        }
145
-        parent::__construct($timezone);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return array
151
-     */
152
-    public function public_event_stati()
153
-    {
154
-        // @see wp-includes/post.php
155
-        return get_post_stati(['public' => true]);
156
-    }
157
-
158
-
159
-    /**
160
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
161
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
162
-     *
163
-     * @return string
164
-     * @throws EE_Error
165
-     */
166
-    public function deleted_field_name()
167
-    {
168
-        throw new EE_Error(
169
-            sprintf(
170
-                esc_html__(
171
-                    '%1$s should not call deleted_field_name()! It should instead use post_status_field_name',
172
-                    "event_espresso"
173
-                ),
174
-                get_called_class()
175
-            )
176
-        );
177
-    }
178
-
179
-
180
-    /**
181
-     * Gets the field's name that sets the post status
182
-     *
183
-     * @return string
184
-     * @throws EE_Error
185
-     */
186
-    public function post_status_field_name()
187
-    {
188
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
189
-        if ($field) {
190
-            return $field->get_name();
191
-        } else {
192
-            throw new EE_Error(
193
-                sprintf(
194
-                    esc_html__(
195
-                        'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
196
-                        'event_espresso'
197
-                    ),
198
-                    get_called_class(),
199
-                    get_called_class()
200
-                )
201
-            );
202
-        }
203
-    }
204
-
205
-
206
-    /**
207
-     * Alters the query params so that only trashed/soft-deleted items are considered
208
-     *
209
-     * @param array $query_params @see
210
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
-     * @return array @see
212
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
-     */
214
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
215
-    {
216
-        $post_status_field_name                     = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
-        return $query_params;
219
-    }
220
-
221
-
222
-    /**
223
-     * Alters the query params so each item's deleted status is ignored.
224
-     *
225
-     * @param array $query_params
226
-     * @return array
227
-     */
228
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
229
-    {
230
-        $query_params['default_where_conditions'] = 'minimum';
231
-        return $query_params;
232
-    }
233
-
234
-
235
-    /**
236
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
-     *
238
-     * @param boolean $delete true to indicate deletion, false to indicate restoration
239
-     * @param array   $query_params
240
-     * @return boolean success
241
-     * @throws EE_Error
242
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
243
-     */
244
-    public function delete_or_restore($delete = true, $query_params = [])
245
-    {
246
-        $post_status_field_name = $this->post_status_field_name();
247
-        $query_params           = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
-        $new_status             = $delete ? self::post_status_trashed : 'draft';
249
-        return (bool) $this->update([$post_status_field_name => $new_status], $query_params);
250
-    }
251
-
252
-
253
-    /**
254
-     * meta_table
255
-     * returns first EE_Secondary_Table table name
256
-     *
257
-     * @access public
258
-     * @return string
259
-     */
260
-    public function meta_table()
261
-    {
262
-        $meta_table = $this->_get_other_tables();
263
-        $meta_table = reset($meta_table);
264
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
265
-    }
266
-
267
-
268
-    /**
269
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
270
-     *
271
-     * @param bool $all  triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
272
-     *                   db only fields)
273
-     * @return array
274
-     */
275
-    public function get_meta_table_fields($all = false)
276
-    {
277
-        $all_fields = $fields_to_return = [];
278
-        foreach ($this->_tables as $alias => $table_obj) {
279
-            if ($table_obj instanceof EE_Secondary_Table) {
280
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281
-            }
282
-        }
283
-        if (! $all) {
284
-            foreach ($all_fields as $name => $obj) {
285
-                if ($obj instanceof EE_DB_Only_Field_Base) {
286
-                    continue;
287
-                }
288
-                $fields_to_return[] = $name;
289
-            }
290
-        } else {
291
-            $fields_to_return = array_keys($all_fields);
292
-        }
293
-        return $fields_to_return;
294
-    }
295
-
296
-
297
-    /**
298
-     * Adds an event category with the specified name and description to the specified
299
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
300
-     * and adds an entry in the term_relationship if necessary.
301
-     *
302
-     * @param EE_CPT_Base $cpt_model_object
303
-     * @param string      $category_name (used to derive the term slug too)
304
-     * @param string      $category_description
305
-     * @param int         $parent_term_taxonomy_id
306
-     * @return EE_Term_Taxonomy
307
-     */
308
-    public function add_event_category(
309
-        EE_CPT_Base $cpt_model_object,
310
-        $category_name,
311
-        $category_description = '',
312
-        $parent_term_taxonomy_id = null
313
-    ) {
314
-        // create term
315
-        require_once(EE_MODELS . 'EEM_Term.model.php');
316
-        // first, check for a term by the same name or slug
317
-        $category_slug = sanitize_title($category_name);
318
-        $term          = EEM_Term::instance()->get_one(
319
-            [
320
-                [
321
-                    'OR'                     => [
322
-                        'name' => $category_name,
323
-                        'slug' => $category_slug,
324
-                    ],
325
-                    'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
326
-                ],
327
-            ]
328
-        );
329
-        if (! $term) {
330
-            $term = EE_Term::new_instance(
331
-                [
332
-                    'name' => $category_name,
333
-                    'slug' => $category_slug,
334
-                ]
335
-            );
336
-            $term->save();
337
-        }
338
-        // make sure there's a term-taxonomy entry too
339
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
340
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341
-            [
342
-                [
343
-                    'term_id'  => $term->ID(),
344
-                    'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
345
-                ],
346
-            ]
347
-        );
348
-        /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if (! $term_taxonomy) {
350
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(
351
-                [
352
-                    'term_id'     => $term->ID(),
353
-                    'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
354
-                    'description' => $category_description,
355
-                    'term_count'  => 1,
356
-                    'parent'      => $parent_term_taxonomy_id,
357
-                ]
358
-            );
359
-            $term_taxonomy->save();
360
-        } else {
361
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
362
-            $term_taxonomy->save();
363
-        }
364
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
365
-    }
366
-
367
-
368
-    /**
369
-     * Removed the category specified by name as having a relation to this event.
370
-     * Does not remove the term or term_taxonomy.
371
-     *
372
-     * @param EE_CPT_Base $cpt_model_object_event
373
-     * @param string      $category_name name of the event category (term)
374
-     * @return bool
375
-     */
376
-    public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
377
-    {
378
-        // find the term_taxonomy by that name
379
-        $term_taxonomy = $this->get_first_related(
380
-            $cpt_model_object_event,
381
-            'Term_Taxonomy',
382
-            [['Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY]]
383
-        );
384
-        /** @var $term_taxonomy EE_Term_Taxonomy */
385
-        if ($term_taxonomy) {
386
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
387
-            $term_taxonomy->save();
388
-        }
389
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
390
-    }
391
-
392
-
393
-    /**
394
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
395
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
396
-     *
397
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
398
-     * @access public
399
-     * @param int          $id   the ID for the cpt we want the feature image for
400
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
401
-     *                           representing width and height in pixels (i.e. array(32,32) ).
402
-     * @param string|array $attr Optional. Query string or array of attributes.
403
-     * @return string HTML image element
404
-     */
405
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
406
-    {
407
-        return get_the_post_thumbnail($id, $size, $attr);
408
-    }
409
-
410
-
411
-    /**
412
-     * Just a handy way to get the list of post statuses currently registered with WP.
413
-     *
414
-     * @return array
415
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
416
-     */
417
-    public function get_post_statuses()
418
-    {
419
-        global $wp_post_statuses;
420
-        $statuses = [];
421
-        foreach ($wp_post_statuses as $post_status => $args_object) {
422
-            $statuses[ $post_status ] = $args_object->label;
423
-        }
424
-        return $statuses;
425
-    }
426
-
427
-
428
-    /**
429
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
430
-     *
431
-     * @return array array of statuses.
432
-     */
433
-    public function get_status_array()
434
-    {
435
-        $statuses = $this->get_post_statuses();
436
-        // first the global filter
437
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438
-        // now the class specific filter
439
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
440
-        return $statuses;
441
-    }
442
-
443
-
444
-    /**
445
-     * this returns the post statuses that are NOT the default wordpress status
446
-     *
447
-     * @return array
448
-     */
449
-    public function get_custom_post_statuses()
450
-    {
451
-        $new_stati = [];
452
-        foreach ($this->_custom_stati as $status => $props) {
453
-            $new_stati[ $status ] = $props['label'];
454
-        }
455
-        return $new_stati;
456
-    }
457
-
458
-
459
-    /**
460
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
461
-     * are a row from the posts table. If we're missing any fields required for the model,
462
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
463
-     * make sure you are attaching all the model's fields onto the post)
464
-     *
465
-     * @param WP_Post|array $post
466
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
467
-     */
468
-    public function instantiate_class_from_post_object_orig($post)
469
-    {
470
-        $post                               = (array) $post;
471
-        $has_all_necessary_fields_for_table = true;
472
-        // check if the post has fields on the meta table already
473
-        foreach ($this->_get_other_tables() as $table_obj) {
474
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475
-            foreach ($fields_for_that_table as $field_obj) {
476
-                if (
477
-                    ! isset($post[ $field_obj->get_table_column() ])
478
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
479
-                ) {
480
-                    $has_all_necessary_fields_for_table = false;
481
-                }
482
-            }
483
-        }
484
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if (! $has_all_necessary_fields_for_table) {
486
-            return $this->get_one_by_ID($post['ID']);
487
-        } else {
488
-            return $this->instantiate_class_from_array_or_object($post);
489
-        }
490
-    }
491
-
492
-
493
-    /**
494
-     * @param null $post
495
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
496
-     */
497
-    public function instantiate_class_from_post_object($post = null)
498
-    {
499
-        if (empty($post)) {
500
-            global $post;
501
-        }
502
-        $post                         = (array) $post;
503
-        $tables_needing_to_be_queried = [];
504
-        // check if the post has fields on the meta table already
505
-        foreach ($this->get_tables() as $table_obj) {
506
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507
-            foreach ($fields_for_that_table as $field_obj) {
508
-                if (
509
-                    ! isset($post[ $field_obj->get_table_column() ])
510
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
511
-                ) {
512
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
513
-                }
514
-            }
515
-        }
516
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
517
-        if ($tables_needing_to_be_queried) {
518
-            if (
519
-                count($tables_needing_to_be_queried) == 1
520
-                && reset($tables_needing_to_be_queried)
521
-                   instanceof
522
-                   EE_Secondary_Table
523
-            ) {
524
-                // so we're only missing data from a secondary table. Well that's not too hard to query for
525
-                $table_to_query = reset($tables_needing_to_be_queried);
526
-                $missing_data   = $this->_do_wpdb_query(
527
-                    'get_row',
528
-                    [
529
-                        'SELECT * FROM '
530
-                        . $table_to_query->get_table_name()
531
-                        . ' WHERE '
532
-                        . $table_to_query->get_fk_on_table()
533
-                        . ' = '
534
-                        . $post['ID'],
535
-                        ARRAY_A,
536
-                    ]
537
-                );
538
-                if (! empty($missing_data)) {
539
-                    $post = array_merge($post, $missing_data);
540
-                }
541
-            } else {
542
-                return $this->get_one_by_ID($post['ID']);
543
-            }
544
-        }
545
-        return $this->instantiate_class_from_array_or_object($post);
546
-    }
547
-
548
-
549
-    /**
550
-     * Gets the post type associated with this
551
-     *
552
-     * @return string
553
-     * @throws EE_Error
554
-     */
555
-    public function post_type()
556
-    {
557
-        $post_type_field = null;
558
-        foreach ($this->field_settings(true) as $field_obj) {
559
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
560
-                $post_type_field = $field_obj;
561
-                break;
562
-            }
563
-        }
564
-        if ($post_type_field == null) {
565
-            throw new EE_Error(
566
-                sprintf(
567
-                    esc_html__(
568
-                        "CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
569
-                        "event_espresso"
570
-                    ),
571
-                    get_class($this)
572
-                )
573
-            );
574
-        }
575
-        return $post_type_field->get_default_value();
576
-    }
17
+	const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
18
+
19
+	/**
20
+	 * @var string post_status_publish - the wp post status for published cpts
21
+	 */
22
+	const post_status_publish = 'publish';
23
+
24
+	/**
25
+	 * @var string post_status_future - the wp post status for scheduled cpts
26
+	 */
27
+	const post_status_future = 'future';
28
+
29
+	/**
30
+	 * @var string post_status_draft - the wp post status for draft cpts
31
+	 */
32
+	const post_status_draft = 'draft';
33
+
34
+	/**
35
+	 * @var string post_status_pending - the wp post status for pending cpts
36
+	 */
37
+	const post_status_pending = 'pending';
38
+
39
+	/**
40
+	 * @var string post_status_private - the wp post status for private cpts
41
+	 */
42
+	const post_status_private = 'private';
43
+
44
+	/**
45
+	 * @var string post_status_trashed - the wp post status for trashed cpts
46
+	 */
47
+	const post_status_trashed = 'trash';
48
+
49
+	/**
50
+	 * This is an array of custom statuses for the given CPT model (modified by children)
51
+	 * format:
52
+	 * array(
53
+	 *        'status_name' => array(
54
+	 *            'label' => esc_html__('Status Name', 'event_espresso'),
55
+	 *            'public' => TRUE //whether a public status or not.
56
+	 *        )
57
+	 * )
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_custom_stati = [];
62
+
63
+
64
+	/**
65
+	 * @param string|null $timezone
66
+	 * @throws EE_Error
67
+	 */
68
+	protected function __construct(?string $timezone = '')
69
+	{
70
+		// adds a relationship to Term_Taxonomy for all these models. For this to work
71
+		// Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
72
+		// eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
73
+		// with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
74
+		// must also be new EE_HABTM_Relation('Term_Relationship');
75
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
76
+		$primary_table_name                      = null;
77
+		// add  the common _status field to all CPT primary tables.
78
+		foreach ($this->_tables as $alias => $table_obj) {
79
+			if ($table_obj instanceof EE_Primary_Table) {
80
+				$primary_table_name = $alias;
81
+			}
82
+		}
83
+		// set default wp post statuses if child has not already set.
84
+		if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
+			$this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
86
+				'post_status',
87
+				esc_html__("Event Status", "event_espresso"),
88
+				false,
89
+				'draft'
90
+			);
91
+		}
92
+		if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
+			$this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
94
+				'to_ping',
95
+				esc_html__('To Ping', 'event_espresso'),
96
+				false,
97
+				''
98
+			);
99
+		}
100
+		if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
+			$this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
102
+				'pinged',
103
+				esc_html__('Pinged', 'event_espresso'),
104
+				false,
105
+				''
106
+			);
107
+		}
108
+		if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
+			$this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
110
+				'comment_status',
111
+				esc_html__('Comment Status', 'event_espresso'),
112
+				false,
113
+				'open'
114
+			);
115
+		}
116
+		if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
+			$this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
118
+				'ping_status',
119
+				esc_html__('Ping Status', 'event_espresso'),
120
+				false,
121
+				'open'
122
+			);
123
+		}
124
+		if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
+			$this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126
+				'post_content_filtered',
127
+				esc_html__('Post Content Filtered', 'event_espresso'),
128
+				false,
129
+				''
130
+			);
131
+		}
132
+		if (! isset($this->_model_relations['Post_Meta'])) {
133
+			// don't block deletes though because we want to maintain the current behaviour
134
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135
+		}
136
+		if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137
+			// nothing was set during child constructor, so set default
138
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139
+		}
140
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141
+			// nothing was set during child constructor, so set default
142
+			// it's ok for child classes to specify this, but generally this is more DRY
143
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
144
+		}
145
+		parent::__construct($timezone);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return array
151
+	 */
152
+	public function public_event_stati()
153
+	{
154
+		// @see wp-includes/post.php
155
+		return get_post_stati(['public' => true]);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
161
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
162
+	 *
163
+	 * @return string
164
+	 * @throws EE_Error
165
+	 */
166
+	public function deleted_field_name()
167
+	{
168
+		throw new EE_Error(
169
+			sprintf(
170
+				esc_html__(
171
+					'%1$s should not call deleted_field_name()! It should instead use post_status_field_name',
172
+					"event_espresso"
173
+				),
174
+				get_called_class()
175
+			)
176
+		);
177
+	}
178
+
179
+
180
+	/**
181
+	 * Gets the field's name that sets the post status
182
+	 *
183
+	 * @return string
184
+	 * @throws EE_Error
185
+	 */
186
+	public function post_status_field_name()
187
+	{
188
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
189
+		if ($field) {
190
+			return $field->get_name();
191
+		} else {
192
+			throw new EE_Error(
193
+				sprintf(
194
+					esc_html__(
195
+						'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
196
+						'event_espresso'
197
+					),
198
+					get_called_class(),
199
+					get_called_class()
200
+				)
201
+			);
202
+		}
203
+	}
204
+
205
+
206
+	/**
207
+	 * Alters the query params so that only trashed/soft-deleted items are considered
208
+	 *
209
+	 * @param array $query_params @see
210
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
211
+	 * @return array @see
212
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
+	 */
214
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
215
+	{
216
+		$post_status_field_name                     = $this->post_status_field_name();
217
+		$query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
+		return $query_params;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Alters the query params so each item's deleted status is ignored.
224
+	 *
225
+	 * @param array $query_params
226
+	 * @return array
227
+	 */
228
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
229
+	{
230
+		$query_params['default_where_conditions'] = 'minimum';
231
+		return $query_params;
232
+	}
233
+
234
+
235
+	/**
236
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
+	 *
238
+	 * @param boolean $delete true to indicate deletion, false to indicate restoration
239
+	 * @param array   $query_params
240
+	 * @return boolean success
241
+	 * @throws EE_Error
242
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
243
+	 */
244
+	public function delete_or_restore($delete = true, $query_params = [])
245
+	{
246
+		$post_status_field_name = $this->post_status_field_name();
247
+		$query_params           = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
248
+		$new_status             = $delete ? self::post_status_trashed : 'draft';
249
+		return (bool) $this->update([$post_status_field_name => $new_status], $query_params);
250
+	}
251
+
252
+
253
+	/**
254
+	 * meta_table
255
+	 * returns first EE_Secondary_Table table name
256
+	 *
257
+	 * @access public
258
+	 * @return string
259
+	 */
260
+	public function meta_table()
261
+	{
262
+		$meta_table = $this->_get_other_tables();
263
+		$meta_table = reset($meta_table);
264
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
265
+	}
266
+
267
+
268
+	/**
269
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
270
+	 *
271
+	 * @param bool $all  triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
272
+	 *                   db only fields)
273
+	 * @return array
274
+	 */
275
+	public function get_meta_table_fields($all = false)
276
+	{
277
+		$all_fields = $fields_to_return = [];
278
+		foreach ($this->_tables as $alias => $table_obj) {
279
+			if ($table_obj instanceof EE_Secondary_Table) {
280
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281
+			}
282
+		}
283
+		if (! $all) {
284
+			foreach ($all_fields as $name => $obj) {
285
+				if ($obj instanceof EE_DB_Only_Field_Base) {
286
+					continue;
287
+				}
288
+				$fields_to_return[] = $name;
289
+			}
290
+		} else {
291
+			$fields_to_return = array_keys($all_fields);
292
+		}
293
+		return $fields_to_return;
294
+	}
295
+
296
+
297
+	/**
298
+	 * Adds an event category with the specified name and description to the specified
299
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
300
+	 * and adds an entry in the term_relationship if necessary.
301
+	 *
302
+	 * @param EE_CPT_Base $cpt_model_object
303
+	 * @param string      $category_name (used to derive the term slug too)
304
+	 * @param string      $category_description
305
+	 * @param int         $parent_term_taxonomy_id
306
+	 * @return EE_Term_Taxonomy
307
+	 */
308
+	public function add_event_category(
309
+		EE_CPT_Base $cpt_model_object,
310
+		$category_name,
311
+		$category_description = '',
312
+		$parent_term_taxonomy_id = null
313
+	) {
314
+		// create term
315
+		require_once(EE_MODELS . 'EEM_Term.model.php');
316
+		// first, check for a term by the same name or slug
317
+		$category_slug = sanitize_title($category_name);
318
+		$term          = EEM_Term::instance()->get_one(
319
+			[
320
+				[
321
+					'OR'                     => [
322
+						'name' => $category_name,
323
+						'slug' => $category_slug,
324
+					],
325
+					'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
326
+				],
327
+			]
328
+		);
329
+		if (! $term) {
330
+			$term = EE_Term::new_instance(
331
+				[
332
+					'name' => $category_name,
333
+					'slug' => $category_slug,
334
+				]
335
+			);
336
+			$term->save();
337
+		}
338
+		// make sure there's a term-taxonomy entry too
339
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
340
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341
+			[
342
+				[
343
+					'term_id'  => $term->ID(),
344
+					'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
345
+				],
346
+			]
347
+		);
348
+		/** @var $term_taxonomy EE_Term_Taxonomy */
349
+		if (! $term_taxonomy) {
350
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(
351
+				[
352
+					'term_id'     => $term->ID(),
353
+					'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
354
+					'description' => $category_description,
355
+					'term_count'  => 1,
356
+					'parent'      => $parent_term_taxonomy_id,
357
+				]
358
+			);
359
+			$term_taxonomy->save();
360
+		} else {
361
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
362
+			$term_taxonomy->save();
363
+		}
364
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
365
+	}
366
+
367
+
368
+	/**
369
+	 * Removed the category specified by name as having a relation to this event.
370
+	 * Does not remove the term or term_taxonomy.
371
+	 *
372
+	 * @param EE_CPT_Base $cpt_model_object_event
373
+	 * @param string      $category_name name of the event category (term)
374
+	 * @return bool
375
+	 */
376
+	public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
377
+	{
378
+		// find the term_taxonomy by that name
379
+		$term_taxonomy = $this->get_first_related(
380
+			$cpt_model_object_event,
381
+			'Term_Taxonomy',
382
+			[['Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY]]
383
+		);
384
+		/** @var $term_taxonomy EE_Term_Taxonomy */
385
+		if ($term_taxonomy) {
386
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
387
+			$term_taxonomy->save();
388
+		}
389
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
390
+	}
391
+
392
+
393
+	/**
394
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
395
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
396
+	 *
397
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
398
+	 * @access public
399
+	 * @param int          $id   the ID for the cpt we want the feature image for
400
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
401
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
402
+	 * @param string|array $attr Optional. Query string or array of attributes.
403
+	 * @return string HTML image element
404
+	 */
405
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
406
+	{
407
+		return get_the_post_thumbnail($id, $size, $attr);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Just a handy way to get the list of post statuses currently registered with WP.
413
+	 *
414
+	 * @return array
415
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
416
+	 */
417
+	public function get_post_statuses()
418
+	{
419
+		global $wp_post_statuses;
420
+		$statuses = [];
421
+		foreach ($wp_post_statuses as $post_status => $args_object) {
422
+			$statuses[ $post_status ] = $args_object->label;
423
+		}
424
+		return $statuses;
425
+	}
426
+
427
+
428
+	/**
429
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
430
+	 *
431
+	 * @return array array of statuses.
432
+	 */
433
+	public function get_status_array()
434
+	{
435
+		$statuses = $this->get_post_statuses();
436
+		// first the global filter
437
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438
+		// now the class specific filter
439
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
440
+		return $statuses;
441
+	}
442
+
443
+
444
+	/**
445
+	 * this returns the post statuses that are NOT the default wordpress status
446
+	 *
447
+	 * @return array
448
+	 */
449
+	public function get_custom_post_statuses()
450
+	{
451
+		$new_stati = [];
452
+		foreach ($this->_custom_stati as $status => $props) {
453
+			$new_stati[ $status ] = $props['label'];
454
+		}
455
+		return $new_stati;
456
+	}
457
+
458
+
459
+	/**
460
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
461
+	 * are a row from the posts table. If we're missing any fields required for the model,
462
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
463
+	 * make sure you are attaching all the model's fields onto the post)
464
+	 *
465
+	 * @param WP_Post|array $post
466
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
467
+	 */
468
+	public function instantiate_class_from_post_object_orig($post)
469
+	{
470
+		$post                               = (array) $post;
471
+		$has_all_necessary_fields_for_table = true;
472
+		// check if the post has fields on the meta table already
473
+		foreach ($this->_get_other_tables() as $table_obj) {
474
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475
+			foreach ($fields_for_that_table as $field_obj) {
476
+				if (
477
+					! isset($post[ $field_obj->get_table_column() ])
478
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
479
+				) {
480
+					$has_all_necessary_fields_for_table = false;
481
+				}
482
+			}
483
+		}
484
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
485
+		if (! $has_all_necessary_fields_for_table) {
486
+			return $this->get_one_by_ID($post['ID']);
487
+		} else {
488
+			return $this->instantiate_class_from_array_or_object($post);
489
+		}
490
+	}
491
+
492
+
493
+	/**
494
+	 * @param null $post
495
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
496
+	 */
497
+	public function instantiate_class_from_post_object($post = null)
498
+	{
499
+		if (empty($post)) {
500
+			global $post;
501
+		}
502
+		$post                         = (array) $post;
503
+		$tables_needing_to_be_queried = [];
504
+		// check if the post has fields on the meta table already
505
+		foreach ($this->get_tables() as $table_obj) {
506
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507
+			foreach ($fields_for_that_table as $field_obj) {
508
+				if (
509
+					! isset($post[ $field_obj->get_table_column() ])
510
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
511
+				) {
512
+					$tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
513
+				}
514
+			}
515
+		}
516
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
517
+		if ($tables_needing_to_be_queried) {
518
+			if (
519
+				count($tables_needing_to_be_queried) == 1
520
+				&& reset($tables_needing_to_be_queried)
521
+				   instanceof
522
+				   EE_Secondary_Table
523
+			) {
524
+				// so we're only missing data from a secondary table. Well that's not too hard to query for
525
+				$table_to_query = reset($tables_needing_to_be_queried);
526
+				$missing_data   = $this->_do_wpdb_query(
527
+					'get_row',
528
+					[
529
+						'SELECT * FROM '
530
+						. $table_to_query->get_table_name()
531
+						. ' WHERE '
532
+						. $table_to_query->get_fk_on_table()
533
+						. ' = '
534
+						. $post['ID'],
535
+						ARRAY_A,
536
+					]
537
+				);
538
+				if (! empty($missing_data)) {
539
+					$post = array_merge($post, $missing_data);
540
+				}
541
+			} else {
542
+				return $this->get_one_by_ID($post['ID']);
543
+			}
544
+		}
545
+		return $this->instantiate_class_from_array_or_object($post);
546
+	}
547
+
548
+
549
+	/**
550
+	 * Gets the post type associated with this
551
+	 *
552
+	 * @return string
553
+	 * @throws EE_Error
554
+	 */
555
+	public function post_type()
556
+	{
557
+		$post_type_field = null;
558
+		foreach ($this->field_settings(true) as $field_obj) {
559
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
560
+				$post_type_field = $field_obj;
561
+				break;
562
+			}
563
+		}
564
+		if ($post_type_field == null) {
565
+			throw new EE_Error(
566
+				sprintf(
567
+					esc_html__(
568
+						"CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
569
+						"event_espresso"
570
+					),
571
+					get_class($this)
572
+				)
573
+			);
574
+		}
575
+		return $post_type_field->get_default_value();
576
+	}
577 577
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -81,63 +81,63 @@  discard block
 block discarded – undo
81 81
             }
82 82
         }
83 83
         // set default wp post statuses if child has not already set.
84
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
85
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
84
+        if ( ! isset($this->_fields[$primary_table_name]['status'])) {
85
+            $this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field(
86 86
                 'post_status',
87 87
                 esc_html__("Event Status", "event_espresso"),
88 88
                 false,
89 89
                 'draft'
90 90
             );
91 91
         }
92
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
93
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
92
+        if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
93
+            $this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field(
94 94
                 'to_ping',
95 95
                 esc_html__('To Ping', 'event_espresso'),
96 96
                 false,
97 97
                 ''
98 98
             );
99 99
         }
100
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
101
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
100
+        if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
101
+            $this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field(
102 102
                 'pinged',
103 103
                 esc_html__('Pinged', 'event_espresso'),
104 104
                 false,
105 105
                 ''
106 106
             );
107 107
         }
108
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
109
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
108
+        if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
109
+            $this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field(
110 110
                 'comment_status',
111 111
                 esc_html__('Comment Status', 'event_espresso'),
112 112
                 false,
113 113
                 'open'
114 114
             );
115 115
         }
116
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
117
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
116
+        if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
117
+            $this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field(
118 118
                 'ping_status',
119 119
                 esc_html__('Ping Status', 'event_espresso'),
120 120
                 false,
121 121
                 'open'
122 122
             );
123 123
         }
124
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
125
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
124
+        if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
125
+            $this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field(
126 126
                 'post_content_filtered',
127 127
                 esc_html__('Post Content Filtered', 'event_espresso'),
128 128
                 false,
129 129
                 ''
130 130
             );
131 131
         }
132
-        if (! isset($this->_model_relations['Post_Meta'])) {
132
+        if ( ! isset($this->_model_relations['Post_Meta'])) {
133 133
             // don't block deletes though because we want to maintain the current behaviour
134 134
             $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
135 135
         }
136
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
136
+        if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
137 137
             // nothing was set during child constructor, so set default
138 138
             $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
139 139
         }
140
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
140
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
141 141
             // nothing was set during child constructor, so set default
142 142
             // it's ok for child classes to specify this, but generally this is more DRY
143 143
             $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
     protected function _alter_query_params_so_only_trashed_items_included($query_params)
215 215
     {
216 216
         $post_status_field_name                     = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
217
+        $query_params[0][$post_status_field_name] = self::post_status_trashed;
218 218
         return $query_params;
219 219
     }
220 220
 
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
                 $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
281 281
             }
282 282
         }
283
-        if (! $all) {
283
+        if ( ! $all) {
284 284
             foreach ($all_fields as $name => $obj) {
285 285
                 if ($obj instanceof EE_DB_Only_Field_Base) {
286 286
                     continue;
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
         $parent_term_taxonomy_id = null
313 313
     ) {
314 314
         // create term
315
-        require_once(EE_MODELS . 'EEM_Term.model.php');
315
+        require_once(EE_MODELS.'EEM_Term.model.php');
316 316
         // first, check for a term by the same name or slug
317 317
         $category_slug = sanitize_title($category_name);
318 318
         $term          = EEM_Term::instance()->get_one(
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
                 ],
327 327
             ]
328 328
         );
329
-        if (! $term) {
329
+        if ( ! $term) {
330 330
             $term = EE_Term::new_instance(
331 331
                 [
332 332
                     'name' => $category_name,
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
             $term->save();
337 337
         }
338 338
         // make sure there's a term-taxonomy entry too
339
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
339
+        require_once(EE_MODELS.'EEM_Term_Taxonomy.model.php');
340 340
         $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
341 341
             [
342 342
                 [
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
             ]
347 347
         );
348 348
         /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if (! $term_taxonomy) {
349
+        if ( ! $term_taxonomy) {
350 350
             $term_taxonomy = EE_Term_Taxonomy::new_instance(
351 351
                 [
352 352
                     'term_id'     => $term->ID(),
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
         global $wp_post_statuses;
420 420
         $statuses = [];
421 421
         foreach ($wp_post_statuses as $post_status => $args_object) {
422
-            $statuses[ $post_status ] = $args_object->label;
422
+            $statuses[$post_status] = $args_object->label;
423 423
         }
424 424
         return $statuses;
425 425
     }
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
         // first the global filter
437 437
         $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
438 438
         // now the class specific filter
439
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
439
+        $statuses = apply_filters('FHEE_EEM_'.get_class($this).'__get_status_array', $statuses);
440 440
         return $statuses;
441 441
     }
442 442
 
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
     {
451 451
         $new_stati = [];
452 452
         foreach ($this->_custom_stati as $status => $props) {
453
-            $new_stati[ $status ] = $props['label'];
453
+            $new_stati[$status] = $props['label'];
454 454
         }
455 455
         return $new_stati;
456 456
     }
@@ -474,15 +474,15 @@  discard block
 block discarded – undo
474 474
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
475 475
             foreach ($fields_for_that_table as $field_obj) {
476 476
                 if (
477
-                    ! isset($post[ $field_obj->get_table_column() ])
478
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
477
+                    ! isset($post[$field_obj->get_table_column()])
478
+                    && ! isset($post[$field_obj->get_qualified_column()])
479 479
                 ) {
480 480
                     $has_all_necessary_fields_for_table = false;
481 481
                 }
482 482
             }
483 483
         }
484 484
         // if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if (! $has_all_necessary_fields_for_table) {
485
+        if ( ! $has_all_necessary_fields_for_table) {
486 486
             return $this->get_one_by_ID($post['ID']);
487 487
         } else {
488 488
             return $this->instantiate_class_from_array_or_object($post);
@@ -506,10 +506,10 @@  discard block
 block discarded – undo
506 506
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
507 507
             foreach ($fields_for_that_table as $field_obj) {
508 508
                 if (
509
-                    ! isset($post[ $field_obj->get_table_column() ])
510
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
509
+                    ! isset($post[$field_obj->get_table_column()])
510
+                    && ! isset($post[$field_obj->get_qualified_column()])
511 511
                 ) {
512
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
512
+                    $tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
513 513
                 }
514 514
             }
515 515
         }
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
                         ARRAY_A,
536 536
                     ]
537 537
                 );
538
-                if (! empty($missing_data)) {
538
+                if ( ! empty($missing_data)) {
539 539
                     $post = array_merge($post, $missing_data);
540 540
                 }
541 541
             } else {
Please login to merge, or discard this patch.
core/db_models/EEM_Extra_Join.model.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -19,73 +19,73 @@
 block discarded – undo
19 19
  */
20 20
 class EEM_Extra_Join extends EEM_Base
21 21
 {
22
-    // private instance of the Extra Join object
23
-    protected static $_instance = null;
22
+	// private instance of the Extra Join object
23
+	protected static $_instance = null;
24 24
 
25 25
 
26
-    /**
27
-     * @param string|null $timezone
28
-     * @throws EE_Error
29
-     */
30
-    public function __construct(?string $timezone = '')
31
-    {
32
-        $models_this_can_join = array_keys(EE_Registry::instance()->non_abstract_db_models);
33
-        $this->_tables        = [
34
-            'Extra_Join' => new EE_Primary_Table('esp_extra_join', 'EXJ_ID'),
35
-        ];
36
-        $this->_fields        = [
37
-            'Extra_Join' => [
38
-                'EXJ_ID'                => new EE_Primary_Key_Int_Field(
39
-                    'EXJ_ID',
40
-                    esc_html__('Extra Join ID', 'event_espresso')
41
-                ),
42
-                'EXJ_first_model_ID'    => new EE_Foreign_Key_String_Field(
43
-                    'EXJ_first_model_ID',
44
-                    esc_html__('First Model ID', 'event_espresso'),
45
-                    true,
46
-                    0,
47
-                    $models_this_can_join
48
-                ),
49
-                'EXJ_first_model_name'  => new EE_Any_Foreign_Model_Name_Field(
50
-                    'EXJ_first_model_name',
51
-                    esc_html__(
52
-                        'First Model Name',
53
-                        'event_espresso'
54
-                    ),
55
-                    true,
56
-                    '',
57
-                    $models_this_can_join
58
-                ),
59
-                'EXJ_second_model_ID'   => new EE_Foreign_Key_String_Field(
60
-                    'EXJ_second_model_ID',
61
-                    esc_html__(
62
-                        'Second Model ID',
63
-                        'event_espresso'
64
-                    ),
65
-                    true,
66
-                    0,
67
-                    $models_this_can_join
68
-                ),
69
-                'EXJ_second_model_name' => new EE_Any_Foreign_Model_Name_Field(
70
-                    'EXJ_second_model_name',
71
-                    esc_html__(
72
-                        'Second Model Name',
73
-                        'event_espresso'
74
-                    ),
75
-                    true,
76
-                    '',
77
-                    $models_this_can_join
78
-                ),
26
+	/**
27
+	 * @param string|null $timezone
28
+	 * @throws EE_Error
29
+	 */
30
+	public function __construct(?string $timezone = '')
31
+	{
32
+		$models_this_can_join = array_keys(EE_Registry::instance()->non_abstract_db_models);
33
+		$this->_tables        = [
34
+			'Extra_Join' => new EE_Primary_Table('esp_extra_join', 'EXJ_ID'),
35
+		];
36
+		$this->_fields        = [
37
+			'Extra_Join' => [
38
+				'EXJ_ID'                => new EE_Primary_Key_Int_Field(
39
+					'EXJ_ID',
40
+					esc_html__('Extra Join ID', 'event_espresso')
41
+				),
42
+				'EXJ_first_model_ID'    => new EE_Foreign_Key_String_Field(
43
+					'EXJ_first_model_ID',
44
+					esc_html__('First Model ID', 'event_espresso'),
45
+					true,
46
+					0,
47
+					$models_this_can_join
48
+				),
49
+				'EXJ_first_model_name'  => new EE_Any_Foreign_Model_Name_Field(
50
+					'EXJ_first_model_name',
51
+					esc_html__(
52
+						'First Model Name',
53
+						'event_espresso'
54
+					),
55
+					true,
56
+					'',
57
+					$models_this_can_join
58
+				),
59
+				'EXJ_second_model_ID'   => new EE_Foreign_Key_String_Field(
60
+					'EXJ_second_model_ID',
61
+					esc_html__(
62
+						'Second Model ID',
63
+						'event_espresso'
64
+					),
65
+					true,
66
+					0,
67
+					$models_this_can_join
68
+				),
69
+				'EXJ_second_model_name' => new EE_Any_Foreign_Model_Name_Field(
70
+					'EXJ_second_model_name',
71
+					esc_html__(
72
+						'Second Model Name',
73
+						'event_espresso'
74
+					),
75
+					true,
76
+					'',
77
+					$models_this_can_join
78
+				),
79 79
 
80
-            ],
81
-        ];
82
-        // this model is weird in that it has two foreign key columns which can point to any model/table.
83
-        // eg a foreign key to event will be in "EXJ_first_model_ID", provided the other
84
-        // model linked to is alphabetically greater than event (eg venue).
85
-        // but if the model linked to is alphabetically lower (eg attendee),
86
-        // the foreign key to the event will be in "EXJ_second_model_ID"
87
-        // so normal usage of foreign keys is weird. So don't define any
88
-        // relations to other models because they won't work properly with this model
89
-        parent::__construct($timezone);
90
-    }
80
+			],
81
+		];
82
+		// this model is weird in that it has two foreign key columns which can point to any model/table.
83
+		// eg a foreign key to event will be in "EXJ_first_model_ID", provided the other
84
+		// model linked to is alphabetically greater than event (eg venue).
85
+		// but if the model linked to is alphabetically lower (eg attendee),
86
+		// the foreign key to the event will be in "EXJ_second_model_ID"
87
+		// so normal usage of foreign keys is weird. So don't define any
88
+		// relations to other models because they won't work properly with this model
89
+		parent::__construct($timezone);
90
+	}
91 91
 }
Please login to merge, or discard this patch.