Completed
Branch FET-9856-direct-instantiation (36dffe)
by
unknown
95:52 queued 84:39
created
core/services/loaders/Loader.php 1 patch
Indentation   +134 added lines, -134 removed lines patch added patch discarded remove patch
@@ -24,140 +24,140 @@
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * @var LoaderDecoratorInterface $new_loader
29
-     */
30
-    private $new_loader;
31
-
32
-
33
-    /**
34
-     * @var LoaderDecoratorInterface $shared_loader
35
-     */
36
-    private $shared_loader;
37
-
38
-
39
-
40
-    /**
41
-     * Loader constructor.
42
-     *
43
-     * @param LoaderDecoratorInterface|null $new_loader
44
-     * @param LoaderDecoratorInterface|null $shared_loader
45
-     * @throws InvalidInterfaceException
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     */
49
-    public function __construct(LoaderDecoratorInterface $new_loader = null, LoaderDecoratorInterface $shared_loader = null)
50
-    {
51
-        $this->new_loader = $this->setupNewLoader($new_loader);
52
-        $this->shared_loader = $this->setupSharedLoader($shared_loader);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * @param LoaderDecoratorInterface|null $new_loader
59
-     * @return CoreLoader|LoaderDecoratorInterface
60
-     * @throws InvalidArgumentException
61
-     */
62
-    private function setupNewLoader(LoaderDecoratorInterface $new_loader = null)
63
-    {
64
-        // if not already generated, create a standard loader
65
-        if (! $new_loader instanceof LoaderDecoratorInterface) {
66
-            $new_loader = new CoreLoader(EE_Registry::instance());
67
-        }
68
-        return $new_loader;
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * @param LoaderDecoratorInterface|null $shared_loader
75
-     * @return CoreLoader|LoaderDecoratorInterface
76
-     * @throws InvalidDataTypeException
77
-     * @throws InvalidInterfaceException
78
-     * @throws InvalidArgumentException
79
-     */
80
-    private function setupSharedLoader(LoaderDecoratorInterface $shared_loader = null)
81
-    {
82
-        // if not already generated, create a caching loader
83
-        if (! $shared_loader instanceof LoaderDecoratorInterface) {
84
-            $shared_loader = new CachingLoader(
85
-                new CoreLoader(EE_Registry::instance()),
86
-                new LooseCollection('')
87
-            );
88
-        }
89
-        return $shared_loader;
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @return LoaderDecoratorInterface
96
-     */
97
-    public function getNewLoader()
98
-    {
99
-        return $this->new_loader;
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * @return LoaderDecoratorInterface
106
-     */
107
-    public function getSharedLoader()
108
-    {
109
-        return $this->shared_loader;
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * @param string $fqcn
116
-     * @param array  $arguments
117
-     * @param bool   $shared
118
-     * @return mixed
119
-     */
120
-    public function load($fqcn, $arguments = array(), $shared = true)
121
-    {
122
-        return $shared
123
-            ? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
124
-            : $this->getNewLoader()->load($fqcn, $arguments, $shared);
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * @param string $fqcn
131
-     * @param array  $arguments
132
-     * @return mixed
133
-     */
134
-    public function getNew($fqcn, $arguments = array())
135
-    {
136
-        return $this->getNewLoader()->load($fqcn, $arguments, false);
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @param string $fqcn
143
-     * @param array  $arguments
144
-     * @return mixed
145
-     */
146
-    public function getShared($fqcn, $arguments = array())
147
-    {
148
-        return $this->getSharedLoader()->load($fqcn, $arguments, true);
149
-    }
150
-
151
-
152
-
153
-    /**
154
-     * calls reset() on loaders if that method exists
155
-     */
156
-    public function reset()
157
-    {
158
-        $this->new_loader->reset();
159
-        $this->shared_loader->reset();
160
-    }
27
+	/**
28
+	 * @var LoaderDecoratorInterface $new_loader
29
+	 */
30
+	private $new_loader;
31
+
32
+
33
+	/**
34
+	 * @var LoaderDecoratorInterface $shared_loader
35
+	 */
36
+	private $shared_loader;
37
+
38
+
39
+
40
+	/**
41
+	 * Loader constructor.
42
+	 *
43
+	 * @param LoaderDecoratorInterface|null $new_loader
44
+	 * @param LoaderDecoratorInterface|null $shared_loader
45
+	 * @throws InvalidInterfaceException
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 */
49
+	public function __construct(LoaderDecoratorInterface $new_loader = null, LoaderDecoratorInterface $shared_loader = null)
50
+	{
51
+		$this->new_loader = $this->setupNewLoader($new_loader);
52
+		$this->shared_loader = $this->setupSharedLoader($shared_loader);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * @param LoaderDecoratorInterface|null $new_loader
59
+	 * @return CoreLoader|LoaderDecoratorInterface
60
+	 * @throws InvalidArgumentException
61
+	 */
62
+	private function setupNewLoader(LoaderDecoratorInterface $new_loader = null)
63
+	{
64
+		// if not already generated, create a standard loader
65
+		if (! $new_loader instanceof LoaderDecoratorInterface) {
66
+			$new_loader = new CoreLoader(EE_Registry::instance());
67
+		}
68
+		return $new_loader;
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * @param LoaderDecoratorInterface|null $shared_loader
75
+	 * @return CoreLoader|LoaderDecoratorInterface
76
+	 * @throws InvalidDataTypeException
77
+	 * @throws InvalidInterfaceException
78
+	 * @throws InvalidArgumentException
79
+	 */
80
+	private function setupSharedLoader(LoaderDecoratorInterface $shared_loader = null)
81
+	{
82
+		// if not already generated, create a caching loader
83
+		if (! $shared_loader instanceof LoaderDecoratorInterface) {
84
+			$shared_loader = new CachingLoader(
85
+				new CoreLoader(EE_Registry::instance()),
86
+				new LooseCollection('')
87
+			);
88
+		}
89
+		return $shared_loader;
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @return LoaderDecoratorInterface
96
+	 */
97
+	public function getNewLoader()
98
+	{
99
+		return $this->new_loader;
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * @return LoaderDecoratorInterface
106
+	 */
107
+	public function getSharedLoader()
108
+	{
109
+		return $this->shared_loader;
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * @param string $fqcn
116
+	 * @param array  $arguments
117
+	 * @param bool   $shared
118
+	 * @return mixed
119
+	 */
120
+	public function load($fqcn, $arguments = array(), $shared = true)
121
+	{
122
+		return $shared
123
+			? $this->getSharedLoader()->load($fqcn, $arguments, $shared)
124
+			: $this->getNewLoader()->load($fqcn, $arguments, $shared);
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * @param string $fqcn
131
+	 * @param array  $arguments
132
+	 * @return mixed
133
+	 */
134
+	public function getNew($fqcn, $arguments = array())
135
+	{
136
+		return $this->getNewLoader()->load($fqcn, $arguments, false);
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @param string $fqcn
143
+	 * @param array  $arguments
144
+	 * @return mixed
145
+	 */
146
+	public function getShared($fqcn, $arguments = array())
147
+	{
148
+		return $this->getSharedLoader()->load($fqcn, $arguments, true);
149
+	}
150
+
151
+
152
+
153
+	/**
154
+	 * calls reset() on loaders if that method exists
155
+	 */
156
+	public function reset()
157
+	{
158
+		$this->new_loader->reset();
159
+		$this->shared_loader->reset();
160
+	}
161 161
 
162 162
 }
163 163
 // End of file Loader.php
Please login to merge, or discard this patch.
core/services/loaders/CachingLoader.php 2 patches
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -22,117 +22,117 @@
 block discarded – undo
22 22
 class CachingLoader extends LoaderDecorator
23 23
 {
24 24
 
25
-    /**
26
-     * @var CollectionInterface $cache
27
-     */
28
-    protected $cache;
29
-
30
-    /**
31
-     * @var string $identifier
32
-     */
33
-    protected $identifier;
34
-
35
-
36
-
37
-    /**
38
-     * CachingLoader constructor.
39
-     *
40
-     * @param LoaderDecoratorInterface $loader
41
-     * @param CollectionInterface      $cache
42
-     * @param string                   $identifier
43
-     * @throws InvalidDataTypeException
44
-     */
45
-    public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
46
-    {
47
-        parent::__construct($loader);
48
-        $this->cache = $cache;
49
-        $this->setIdentifier($identifier);
50
-        if ($this->identifier !== '') {
51
-            // to only clear this cache, and assuming an identifier has been set, simply do the following:
52
-            // do_action('AHEE__EventEspresso\core\services\loaders\CachingLoader__resetCache__IDENTIFIER');
53
-            // where "IDENTIFIER" = the string that was set during construction
54
-            add_action(
55
-                "AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
56
-                array($this, 'reset')
57
-            );
58
-        }
59
-        // to clear ALL caches, simply do the following:
60
-        // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
61
-        add_action(
62
-            'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
63
-            array($this, 'reset')
64
-        );
65
-    }
66
-
67
-
68
-
69
-    /**
70
-     * @return string
71
-     */
72
-    public function identifier()
73
-    {
74
-        return $this->identifier;
75
-    }
76
-
77
-
78
-
79
-    /**
80
-     * @param string $identifier
81
-     * @throws InvalidDataTypeException
82
-     */
83
-    private function setIdentifier($identifier)
84
-    {
85
-        if ( ! is_string($identifier)) {
86
-            throw new InvalidDataTypeException('$identifier', $identifier, 'string');
87
-        }
88
-        $this->identifier = $identifier;
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * @param string $fqcn
95
-     * @param array  $arguments
96
-     * @param bool   $shared
97
-     * @return mixed
98
-     * @throws InvalidEntityException
99
-     * @throws ServiceNotFoundException
100
-     */
101
-    public function load($fqcn, $arguments = array(), $shared = true)
102
-    {
103
-        $fqcn = ltrim($fqcn, '\\');
104
-        // caching can be turned off via the following code:
105
-        // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
106
-        if(
107
-            apply_filters(
108
-                'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
109
-                false,
110
-                $this
111
-            )
112
-        ){
113
-            return $this->loader->load($fqcn, $arguments, false);
114
-        }
115
-        $identifier = md5($fqcn . serialize($arguments));
116
-        if($this->cache->has($identifier)){
117
-            return $this->cache->get($identifier);
118
-        }
119
-        // even though $shared might be true, we don't want the core loader to  cache anything
120
-        // so we're  turning caching off, because  we will handle it here
121
-        $object = $this->loader->load($fqcn, $arguments, false);
122
-        $this->cache->add($object, $identifier);
123
-        return $object;
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * empties cache and calls reset() on loader if method exists
130
-     */
131
-    public function reset()
132
-    {
133
-        $this->cache->detachAll();
134
-        $this->loader->reset();
135
-    }
25
+	/**
26
+	 * @var CollectionInterface $cache
27
+	 */
28
+	protected $cache;
29
+
30
+	/**
31
+	 * @var string $identifier
32
+	 */
33
+	protected $identifier;
34
+
35
+
36
+
37
+	/**
38
+	 * CachingLoader constructor.
39
+	 *
40
+	 * @param LoaderDecoratorInterface $loader
41
+	 * @param CollectionInterface      $cache
42
+	 * @param string                   $identifier
43
+	 * @throws InvalidDataTypeException
44
+	 */
45
+	public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
46
+	{
47
+		parent::__construct($loader);
48
+		$this->cache = $cache;
49
+		$this->setIdentifier($identifier);
50
+		if ($this->identifier !== '') {
51
+			// to only clear this cache, and assuming an identifier has been set, simply do the following:
52
+			// do_action('AHEE__EventEspresso\core\services\loaders\CachingLoader__resetCache__IDENTIFIER');
53
+			// where "IDENTIFIER" = the string that was set during construction
54
+			add_action(
55
+				"AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
56
+				array($this, 'reset')
57
+			);
58
+		}
59
+		// to clear ALL caches, simply do the following:
60
+		// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
61
+		add_action(
62
+			'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
63
+			array($this, 'reset')
64
+		);
65
+	}
66
+
67
+
68
+
69
+	/**
70
+	 * @return string
71
+	 */
72
+	public function identifier()
73
+	{
74
+		return $this->identifier;
75
+	}
76
+
77
+
78
+
79
+	/**
80
+	 * @param string $identifier
81
+	 * @throws InvalidDataTypeException
82
+	 */
83
+	private function setIdentifier($identifier)
84
+	{
85
+		if ( ! is_string($identifier)) {
86
+			throw new InvalidDataTypeException('$identifier', $identifier, 'string');
87
+		}
88
+		$this->identifier = $identifier;
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * @param string $fqcn
95
+	 * @param array  $arguments
96
+	 * @param bool   $shared
97
+	 * @return mixed
98
+	 * @throws InvalidEntityException
99
+	 * @throws ServiceNotFoundException
100
+	 */
101
+	public function load($fqcn, $arguments = array(), $shared = true)
102
+	{
103
+		$fqcn = ltrim($fqcn, '\\');
104
+		// caching can be turned off via the following code:
105
+		// add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
106
+		if(
107
+			apply_filters(
108
+				'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
109
+				false,
110
+				$this
111
+			)
112
+		){
113
+			return $this->loader->load($fqcn, $arguments, false);
114
+		}
115
+		$identifier = md5($fqcn . serialize($arguments));
116
+		if($this->cache->has($identifier)){
117
+			return $this->cache->get($identifier);
118
+		}
119
+		// even though $shared might be true, we don't want the core loader to  cache anything
120
+		// so we're  turning caching off, because  we will handle it here
121
+		$object = $this->loader->load($fqcn, $arguments, false);
122
+		$this->cache->add($object, $identifier);
123
+		return $object;
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * empties cache and calls reset() on loader if method exists
130
+	 */
131
+	public function reset()
132
+	{
133
+		$this->cache->detachAll();
134
+		$this->loader->reset();
135
+	}
136 136
 
137 137
 
138 138
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -103,17 +103,17 @@
 block discarded – undo
103 103
         $fqcn = ltrim($fqcn, '\\');
104 104
         // caching can be turned off via the following code:
105 105
         // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
106
-        if(
106
+        if (
107 107
             apply_filters(
108 108
                 'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
109 109
                 false,
110 110
                 $this
111 111
             )
112
-        ){
112
+        ) {
113 113
             return $this->loader->load($fqcn, $arguments, false);
114 114
         }
115
-        $identifier = md5($fqcn . serialize($arguments));
116
-        if($this->cache->has($identifier)){
115
+        $identifier = md5($fqcn.serialize($arguments));
116
+        if ($this->cache->has($identifier)) {
117 117
             return $this->cache->get($identifier);
118 118
         }
119 119
         // even though $shared might be true, we don't want the core loader to  cache anything
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -16 removed lines patch added patch discarded remove patch
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961 961
      * foreign key to the WP_User table)
962 962
      *
963
-     * @return string|boolean string on success, boolean false when there is no
963
+     * @return string|false string on success, boolean false when there is no
964 964
      * foreign key to the WP_User table
965 965
      */
966 966
     public function wp_user_field_name()
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      *
1067 1067
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1068 1068
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1069
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070 1070
      *                                  fields on the model, and the models we joined to in the query. However, you can
1071 1071
      *                                  override this and set the select to "*", or a specific column name, like
1072 1072
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1404,6 +1404,7 @@  discard block
 block discarded – undo
1404 1404
      * This sets the _timezone property after model object has been instantiated.
1405 1405
      *
1406 1406
      * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+     * @param null|string $timezone
1407 1408
      */
1408 1409
     public function set_timezone($timezone)
1409 1410
     {
@@ -1458,7 +1459,7 @@  discard block
 block discarded – undo
1458 1459
      * @param string $field_name The name of the field the formats are being retrieved for.
1459 1460
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460 1461
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
+     * @return string[] formats in an array with the date format first, and the time format last.
1462 1463
      */
1463 1464
     public function get_formats_for($field_name, $pretty = false)
1464 1465
     {
@@ -1493,7 +1494,7 @@  discard block
 block discarded – undo
1493 1494
      *                                 be returned.
1494 1495
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495 1496
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497 1498
      *                                 exception is triggered.
1498 1499
      */
1499 1500
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1533,7 +1534,7 @@  discard block
 block discarded – undo
1533 1534
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534 1535
      *                                format is
1535 1536
      *                                'U', this is ignored.
1536
-     * @return DateTime
1537
+     * @return string
1537 1538
      * @throws EE_Error
1538 1539
      */
1539 1540
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1831,7 +1832,7 @@  discard block
 block discarded – undo
1831 1832
      * Wrapper for EEM_Base::delete_permanently()
1832 1833
      *
1833 1834
      * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
+     * @return integer whether the row got deleted or not
1835 1836
      * @throws EE_Error
1836 1837
      */
1837 1838
     public function delete_permanently_by_ID($id)
@@ -1851,7 +1852,7 @@  discard block
 block discarded – undo
1851 1852
      * Wrapper for EEM_Base::delete()
1852 1853
      *
1853 1854
      * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
+     * @return integer whether the row got deleted or not
1855 1856
      * @throws EE_Error
1856 1857
      */
1857 1858
     public function delete_by_ID($id)
@@ -2301,7 +2302,7 @@  discard block
 block discarded – undo
2301 2302
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2302 2303
      * EEM_Base::$_db_verification_level
2303 2304
      *
2304
-     * @param $wpdb_method
2305
+     * @param string $wpdb_method
2305 2306
      * @param $arguments_to_provide
2306 2307
      * @return string
2307 2308
      */
@@ -2425,6 +2426,7 @@  discard block
 block discarded – undo
2425 2426
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2426 2427
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2427 2428
      *                             because these will be inserted in any new rows created as well.
2429
+     * @param EE_Base_Class $id_or_obj
2428 2430
      */
2429 2431
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2430 2432
     {
@@ -2435,7 +2437,7 @@  discard block
 block discarded – undo
2435 2437
 
2436 2438
 
2437 2439
     /**
2438
-     * @param mixed           $id_or_obj
2440
+     * @param EE_Base_Class           $id_or_obj
2439 2441
      * @param string          $relationName
2440 2442
      * @param array           $where_query_params
2441 2443
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2476,7 +2478,7 @@  discard block
 block discarded – undo
2476 2478
      * However, if the model objects can't be deleted because of blocking related model objects, then
2477 2479
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2478 2480
      *
2479
-     * @param EE_Base_Class|int|string $id_or_obj
2481
+     * @param EE_Base_Class $id_or_obj
2480 2482
      * @param string                   $model_name
2481 2483
      * @param array                    $query_params
2482 2484
      * @return int how many deleted
@@ -2497,7 +2499,7 @@  discard block
 block discarded – undo
2497 2499
      * the model objects can't be hard deleted because of blocking related model objects,
2498 2500
      * just does a soft-delete on them instead.
2499 2501
      *
2500
-     * @param EE_Base_Class|int|string $id_or_obj
2502
+     * @param EE_Base_Class $id_or_obj
2501 2503
      * @param string                   $model_name
2502 2504
      * @param array                    $query_params
2503 2505
      * @return int how many deleted
@@ -2554,6 +2556,7 @@  discard block
 block discarded – undo
2554 2556
      * @param string $model_name   like 'Event', or 'Registration'
2555 2557
      * @param array  $query_params like EEM_Base::get_all's
2556 2558
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2559
+     * @param EE_Base_Class $id_or_obj
2557 2560
      * @return float
2558 2561
      * @throws EE_Error
2559 2562
      */
@@ -3028,7 +3031,7 @@  discard block
 block discarded – undo
3028 3031
      * Finds all the fields that correspond to the given table
3029 3032
      *
3030 3033
      * @param string $table_alias , array key in EEM_Base::_tables
3031
-     * @return EE_Model_Field_Base[]
3034
+     * @return EE_Model_Field_Base
3032 3035
      */
3033 3036
     public function _get_fields_for_table($table_alias)
3034 3037
     {
@@ -3513,7 +3516,7 @@  discard block
 block discarded – undo
3513 3516
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3514 3517
      * We should use default where conditions on related models when they requested to use default where conditions
3515 3518
      * on all models, or specifically just on other related models
3516
-     * @param      $default_where_conditions_value
3519
+     * @param      string $default_where_conditions_value
3517 3520
      * @param bool $for_this_model false means this is for OTHER related models
3518 3521
      * @return bool
3519 3522
      */
@@ -3551,7 +3554,7 @@  discard block
 block discarded – undo
3551 3554
      * where conditions.
3552 3555
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3553 3556
      * on this model or others
3554
-     * @param      $default_where_conditions_value
3557
+     * @param      string $default_where_conditions_value
3555 3558
      * @param bool $for_this_model false means this is for OTHER related models
3556 3559
      * @return bool
3557 3560
      */
@@ -4604,7 +4607,7 @@  discard block
 block discarded – undo
4604 4607
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4605 4608
      * Eg, on EE_Answer that would be ANS_ID field object
4606 4609
      *
4607
-     * @param $field_obj
4610
+     * @param EE_Model_Field_Base $field_obj
4608 4611
      * @return boolean
4609 4612
      */
4610 4613
     public function is_primary_key_field($field_obj)
@@ -5335,7 +5338,7 @@  discard block
 block discarded – undo
5335 5338
     /**
5336 5339
      * Read comments for assume_values_already_prepared_by_model_object()
5337 5340
      *
5338
-     * @return int
5341
+     * @return boolean
5339 5342
      */
5340 5343
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5341 5344
     {
Please login to merge, or discard this patch.
Indentation   +5857 added lines, -5857 removed lines patch added patch discarded remove patch
@@ -28,5865 +28,5865 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
-     * @since 4.6.x
1490
-     * @param string $field_name       The field the current time is needed for.
1491
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
-     *                                 formatted string matching the set format for the field in the set timezone will
1493
-     *                                 be returned.
1494
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
-     *                                 exception is triggered.
1498
-     */
1499
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
-    {
1501
-        $formats = $this->get_formats_for($field_name);
1502
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
-        if ($timestamp) {
1504
-            return $DateTime->format('U');
1505
-        }
1506
-        //not returning timestamp, so return formatted string in timezone.
1507
-        switch ($what) {
1508
-            case 'time' :
1509
-                return $DateTime->format($formats[1]);
1510
-                break;
1511
-            case 'date' :
1512
-                return $DateTime->format($formats[0]);
1513
-                break;
1514
-            default :
1515
-                return $DateTime->format(implode(' ', $formats));
1516
-                break;
1517
-        }
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
-     * for the model are.  Returns a DateTime object.
1525
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
-     * ignored.
1528
-     *
1529
-     * @param string $field_name      The field being setup.
1530
-     * @param string $timestring      The date time string being used.
1531
-     * @param string $incoming_format The format for the time string.
1532
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
-     *                                format is
1535
-     *                                'U', this is ignored.
1536
-     * @return DateTime
1537
-     * @throws EE_Error
1538
-     */
1539
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
-    {
1541
-        //just using this to ensure the timezone is set correctly internally
1542
-        $this->get_formats_for($field_name);
1543
-        //load EEH_DTT_Helper
1544
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
-     *
1554
-     * @return EE_Table_Base[]
1555
-     */
1556
-    public function get_tables()
1557
-    {
1558
-        return $this->_tables;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
-     * model object with EVT_ID = 1
1570
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
-     * are not specified)
1575
-     *
1576
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1581
-     *                                         ID=34, we'd use this method as follows:
1582
-     *                                         EEM_Transaction::instance()->update(
1583
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
-     *                                         array(array('TXN_ID'=>34)));
1585
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
-     *                                         in client code into what's expected to be stored on each field. Eg,
1587
-     *                                         consider updating Question's QST_admin_label field is of type
1588
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
-     *                                         TRUE, it is assumed that you've already called
1593
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
-     *                                         malicious javascript. However, if
1595
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
-     *                                         and every other field, before insertion. We provide this parameter
1598
-     *                                         because model objects perform their prepare_for_set function on all
1599
-     *                                         their values, and so don't need to be called again (and in many cases,
1600
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
-     *                                         prepare_for_set method...)
1602
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
-     *                                         in this model's entity map according to $fields_n_values that match
1604
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1605
-     *                                         by setting this to FALSE, but be aware that model objects being used
1606
-     *                                         could get out-of-sync with the database
1607
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
-     *                                         bad)
1610
-     * @throws EE_Error
1611
-     */
1612
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
-    {
1614
-        if (! is_array($query_params)) {
1615
-            EE_Error::doing_it_wrong('EEM_Base::update',
1616
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
-                    gettype($query_params)), '4.6.0');
1618
-            $query_params = array();
1619
-        }
1620
-        /**
1621
-         * Action called before a model update call has been made.
1622
-         *
1623
-         * @param EEM_Base $model
1624
-         * @param array    $fields_n_values the updated fields and their new values
1625
-         * @param array    $query_params    @see EEM_Base::get_all()
1626
-         */
1627
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
-        /**
1629
-         * Filters the fields about to be updated given the query parameters. You can provide the
1630
-         * $query_params to $this->get_all() to find exactly which records will be updated
1631
-         *
1632
-         * @param array    $fields_n_values fields and their new values
1633
-         * @param EEM_Base $model           the model being queried
1634
-         * @param array    $query_params    see EEM_Base::get_all()
1635
-         */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
-            $query_params);
1638
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
-        //to do that, for each table, verify that it's PK isn't null.
1640
-        $tables = $this->get_tables();
1641
-        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1642
-        //NOTE: we should make this code more efficient by NOT querying twice
1643
-        //before the real update, but that needs to first go through ALPHA testing
1644
-        //as it's dangerous. says Mike August 8 2014
1645
-        //we want to make sure the default_where strategy is ignored
1646
-        $this->_ignore_where_strategy = true;
1647
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
-        foreach ($wpdb_select_results as $wpdb_result) {
1649
-            // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1651
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
-            if ($this->has_primary_key_field()) {
1653
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
-            } else {
1655
-                //if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1656
-                $main_table_pk_value = null;
1657
-            }
1658
-            //if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1659
-            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
-            if (count($tables) > 1) {
1661
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
-                //in that table, and so we'll want to insert one
1663
-                foreach ($tables as $table_obj) {
1664
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
-                    //if there is no private key for this table on the results, it means there's no entry
1666
-                    //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
-                           && $wpdb_result[$this_table_pk_column])
1669
-                    ) {
1670
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
-                            $main_table_pk_value);
1672
-                        //if we died here, report the error
1673
-                        if (! $success) {
1674
-                            return false;
1675
-                        }
1676
-                    }
1677
-                }
1678
-            }
1679
-            //				//and now check that if we have cached any models by that ID on the model, that
1680
-            //				//they also get updated properly
1681
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
-            //				if( $model_object ){
1683
-            //					foreach( $fields_n_values as $field => $value ){
1684
-            //						$model_object->set($field, $value);
1685
-            //let's make sure default_where strategy is followed now
1686
-            $this->_ignore_where_strategy = false;
1687
-        }
1688
-        //if we want to keep model objects in sync, AND
1689
-        //if this wasn't called from a model object (to update itself)
1690
-        //then we want to make sure we keep all the existing
1691
-        //model objects in sync with the db
1692
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
-            if ($this->has_primary_key_field()) {
1694
-                $model_objs_affected_ids = $this->get_col($query_params);
1695
-            } else {
1696
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
-                $model_objs_affected_ids = array();
1699
-                foreach ($models_affected_key_columns as $row) {
1700
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1701
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
-                }
1703
-            }
1704
-            if (! $model_objs_affected_ids) {
1705
-                //wait wait wait- if nothing was affected let's stop here
1706
-                return 0;
1707
-            }
1708
-            foreach ($model_objs_affected_ids as $id) {
1709
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
-                if ($model_obj_in_entity_map) {
1711
-                    foreach ($fields_n_values as $field => $new_value) {
1712
-                        $model_obj_in_entity_map->set($field, $new_value);
1713
-                    }
1714
-                }
1715
-            }
1716
-            //if there is a primary key on this model, we can now do a slight optimization
1717
-            if ($this->has_primary_key_field()) {
1718
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
-                $query_params = array(
1720
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
-                    'limit'                    => count($model_objs_affected_ids),
1722
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
-                );
1724
-            }
1725
-        }
1726
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
-        $SQL = "UPDATE "
1728
-               . $model_query_info->get_full_join_sql()
1729
-               . " SET "
1730
-               . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
-        /**
1734
-         * Action called after a model update call has been made.
1735
-         *
1736
-         * @param EEM_Base $model
1737
-         * @param array    $fields_n_values the updated fields and their new values
1738
-         * @param array    $query_params    @see EEM_Base::get_all()
1739
-         * @param int      $rows_affected
1740
-         */
1741
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
-     * are teh values of the field specified (or by default the primary key field)
1750
-     * that matched the query params. Note that you should pass the name of the
1751
-     * model FIELD, not the database table's column name.
1752
-     *
1753
-     * @param array  $query_params @see EEM_Base::get_all()
1754
-     * @param string $field_to_select
1755
-     * @return array just like $wpdb->get_col()
1756
-     * @throws EE_Error
1757
-     */
1758
-    public function get_col($query_params = array(), $field_to_select = null)
1759
-    {
1760
-        if ($field_to_select) {
1761
-            $field = $this->field_settings_for($field_to_select);
1762
-        } elseif ($this->has_primary_key_field()) {
1763
-            $field = $this->get_primary_key_field();
1764
-        } else {
1765
-            //no primary key, just grab the first column
1766
-            $field = reset($this->field_settings());
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
-        return $this->_do_wpdb_query('get_col', array($SQL));
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Returns a single column value for a single row from the database
1778
-     *
1779
-     * @param array  $query_params    @see EEM_Base::get_all()
1780
-     * @param string $field_to_select @see EEM_Base::get_col()
1781
-     * @return string
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function get_var($query_params = array(), $field_to_select = null)
1785
-    {
1786
-        $query_params['limit'] = 1;
1787
-        $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1789
-            return reset($col);
1790
-        } else {
1791
-            return null;
1792
-        }
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
-     * injection, but currently no further filtering is done
1801
-     *
1802
-     * @global      $wpdb
1803
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
-     *                               be updated to in the DB
1805
-     * @return string of SQL
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function _construct_update_sql($fields_n_values)
1809
-    {
1810
-        /** @type WPDB $wpdb */
1811
-        global $wpdb;
1812
-        $cols_n_values = array();
1813
-        foreach ($fields_n_values as $field_name => $value) {
1814
-            $field_obj = $this->field_settings_for($field_name);
1815
-            //if the value is NULL, we want to assign the value to that.
1816
-            //wpdb->prepare doesn't really handle that properly
1817
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
-            $value_sql = $prepared_value === null ? 'NULL'
1819
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
-        }
1822
-        return implode(",", $cols_n_values);
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Performs a HARD delete, meaning the database row should always be removed,
1830
-     * not just have a flag field on it switched
1831
-     * Wrapper for EEM_Base::delete_permanently()
1832
-     *
1833
-     * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
-     * @throws EE_Error
1836
-     */
1837
-    public function delete_permanently_by_ID($id)
1838
-    {
1839
-        return $this->delete_permanently(
1840
-            array(
1841
-                array($this->get_primary_key_field()->get_name() => $id),
1842
-                'limit' => 1,
1843
-            )
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Wrapper for EEM_Base::delete()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
-     * @throws EE_Error
1856
-     */
1857
-    public function delete_by_ID($id)
1858
-    {
1859
-        return $this->delete(
1860
-            array(
1861
-                array($this->get_primary_key_field()->get_name() => $id),
1862
-                'limit' => 1,
1863
-            )
1864
-        );
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1871
-     * meaning if the model has a field that indicates its been "trashed" or
1872
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1873
-     *
1874
-     * @see EEM_Base::delete_permanently
1875
-     * @param array   $query_params
1876
-     * @param boolean $allow_blocking
1877
-     * @return int how many rows got deleted
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function delete($query_params, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete_permanently($query_params, $allow_blocking);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1889
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
-     * as archived, not actually deleted
1891
-     *
1892
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
-     *                                deletes regardless of other objects which may depend on it. Its generally
1896
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
-     *                                DB
1898
-     * @return int how many rows got deleted
1899
-     * @throws EE_Error
1900
-     */
1901
-    public function delete_permanently($query_params, $allow_blocking = true)
1902
-    {
1903
-        /**
1904
-         * Action called just before performing a real deletion query. You can use the
1905
-         * model and its $query_params to find exactly which items will be deleted
1906
-         *
1907
-         * @param EEM_Base $model
1908
-         * @param array    $query_params   @see EEM_Base::get_all()
1909
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1910
-         *                                 to block (prevent) this deletion
1911
-         */
1912
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
-        //some MySQL databases may be running safe mode, which may restrict
1914
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
-        //to delete them
1917
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1919
-        if ($deletion_where) {
1920
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1921
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1922
-            $table_aliases = array_keys($this->_tables);
1923
-            $SQL = "DELETE "
1924
-                   . implode(", ", $table_aliases)
1925
-                   . " FROM "
1926
-                   . $model_query_info->get_full_join_sql()
1927
-                   . " WHERE "
1928
-                   . $deletion_where;
1929
-            //		/echo "delete sql:$SQL";
1930
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
-        } else {
1932
-            $rows_deleted = 0;
1933
-        }
1934
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1935
-        if ($this->has_primary_key_field()) {
1936
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1937
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1938
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1939
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1940
-                }
1941
-            }
1942
-        }
1943
-        /**
1944
-         * Action called just after performing a real deletion query. Although at this point the
1945
-         * items should have been deleted
1946
-         *
1947
-         * @param EEM_Base $model
1948
-         * @param array    $query_params @see EEM_Base::get_all()
1949
-         * @param int      $rows_deleted
1950
-         */
1951
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1952
-        return $rows_deleted;//how many supposedly got deleted
1953
-    }
1954
-
1955
-
1956
-
1957
-    /**
1958
-     * Checks all the relations that throw error messages when there are blocking related objects
1959
-     * for related model objects. If there are any related model objects on those relations,
1960
-     * adds an EE_Error, and return true
1961
-     *
1962
-     * @param EE_Base_Class|int $this_model_obj_or_id
1963
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1964
-     *                                                 should be ignored when determining whether there are related
1965
-     *                                                 model objects which block this model object's deletion. Useful
1966
-     *                                                 if you know A is related to B and are considering deleting A,
1967
-     *                                                 but want to see if A has any other objects blocking its deletion
1968
-     *                                                 before removing the relation between A and B
1969
-     * @return boolean
1970
-     * @throws EE_Error
1971
-     */
1972
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1973
-    {
1974
-        //first, if $ignore_this_model_obj was supplied, get its model
1975
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1976
-            $ignored_model = $ignore_this_model_obj->get_model();
1977
-        } else {
1978
-            $ignored_model = null;
1979
-        }
1980
-        //now check all the relations of $this_model_obj_or_id and see if there
1981
-        //are any related model objects blocking it?
1982
-        $is_blocked = false;
1983
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1984
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1985
-                //if $ignore_this_model_obj was supplied, then for the query
1986
-                //on that model needs to be told to ignore $ignore_this_model_obj
1987
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1988
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1989
-                        array(
1990
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1991
-                                '!=',
1992
-                                $ignore_this_model_obj->ID(),
1993
-                            ),
1994
-                        ),
1995
-                    ));
1996
-                } else {
1997
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1998
-                }
1999
-                if ($related_model_objects) {
2000
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2001
-                    $is_blocked = true;
2002
-                }
2003
-            }
2004
-        }
2005
-        return $is_blocked;
2006
-    }
2007
-
2008
-
2009
-
2010
-    /**
2011
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2012
-     * well.
2013
-     *
2014
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2015
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2016
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2017
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2018
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2019
-     *                                      easily corrupt your DB
2020
-     * @throws EE_Error
2021
-     * @return string    everything that comes after the WHERE statement.
2022
-     */
2023
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2024
-    {
2025
-        if ($this->has_primary_key_field()) {
2026
-            $primary_table = $this->_get_main_table();
2027
-            $other_tables = $this->_get_other_tables();
2028
-            $deletes = $query = array();
2029
-            foreach ($objects_for_deletion as $delete_object) {
2030
-                //before we mark this object for deletion,
2031
-                //make sure there's no related objects blocking its deletion (if we're checking)
2032
-                if (
2033
-                    $allow_blocking
2034
-                    && $this->delete_is_blocked_by_related_models(
2035
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2036
-                    )
2037
-                ) {
2038
-                    continue;
2039
-                }
2040
-                //primary table deletes
2041
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2042
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2043
-                }
2044
-                //other tables
2045
-                if (! empty($other_tables)) {
2046
-                    foreach ($other_tables as $ot) {
2047
-                        //first check if we've got the foreign key column here.
2048
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2049
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2050
-                        }
2051
-                        // wait! it's entirely possible that we'll have a the primary key
2052
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2053
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2054
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2055
-                        }
2056
-                        // finally, it is possible that the fk for this table is found
2057
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2058
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2059
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2060
-                        }
2061
-                    }
2062
-                }
2063
-            }
2064
-            //we should have deletes now, so let's just go through and setup the where statement
2065
-            foreach ($deletes as $column => $values) {
2066
-                //make sure we have unique $values;
2067
-                $values = array_unique($values);
2068
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2069
-            }
2070
-            return ! empty($query) ? implode(' AND ', $query) : '';
2071
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2072
-            $ways_to_identify_a_row = array();
2073
-            $fields = $this->get_combined_primary_key_fields();
2074
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2075
-            foreach ($objects_for_deletion as $delete_object) {
2076
-                $values_for_each_cpk_for_a_row = array();
2077
-                foreach ($fields as $cpk_field) {
2078
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2079
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2080
-                                                           . "="
2081
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2082
-                    }
2083
-                }
2084
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2085
-            }
2086
-            return implode(" OR ", $ways_to_identify_a_row);
2087
-        } else {
2088
-            //so there's no primary key and no combined key...
2089
-            //sorry, can't help you
2090
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2091
-                "event_espresso"), get_class($this)));
2092
-        }
2093
-    }
2094
-
2095
-
2096
-
2097
-    /**
2098
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2099
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2100
-     * column
2101
-     *
2102
-     * @param array  $query_params   like EEM_Base::get_all's
2103
-     * @param string $field_to_count field on model to count by (not column name)
2104
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2105
-     *                               that by the setting $distinct to TRUE;
2106
-     * @return int
2107
-     * @throws EE_Error
2108
-     */
2109
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2110
-    {
2111
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2112
-        if ($field_to_count) {
2113
-            $field_obj = $this->field_settings_for($field_to_count);
2114
-            $column_to_count = $field_obj->get_qualified_column();
2115
-        } elseif ($this->has_primary_key_field()) {
2116
-            $pk_field_obj = $this->get_primary_key_field();
2117
-            $column_to_count = $pk_field_obj->get_qualified_column();
2118
-        } else {
2119
-            //there's no primary key
2120
-            //if we're counting distinct items, and there's no primary key,
2121
-            //we need to list out the columns for distinction;
2122
-            //otherwise we can just use star
2123
-            if ($distinct) {
2124
-                $columns_to_use = array();
2125
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2126
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2127
-                }
2128
-                $column_to_count = implode(',', $columns_to_use);
2129
-            } else {
2130
-                $column_to_count = '*';
2131
-            }
2132
-        }
2133
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2134
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2135
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2136
-    }
2137
-
2138
-
2139
-
2140
-    /**
2141
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2142
-     *
2143
-     * @param array  $query_params like EEM_Base::get_all
2144
-     * @param string $field_to_sum name of field (array key in $_fields array)
2145
-     * @return float
2146
-     * @throws EE_Error
2147
-     */
2148
-    public function sum($query_params, $field_to_sum = null)
2149
-    {
2150
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
-        if ($field_to_sum) {
2152
-            $field_obj = $this->field_settings_for($field_to_sum);
2153
-        } else {
2154
-            $field_obj = $this->get_primary_key_field();
2155
-        }
2156
-        $column_to_count = $field_obj->get_qualified_column();
2157
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2158
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2159
-        $data_type = $field_obj->get_wpdb_data_type();
2160
-        if ($data_type === '%d' || $data_type === '%s') {
2161
-            return (float)$return_value;
2162
-        } else {//must be %f
2163
-            return (float)$return_value;
2164
-        }
2165
-    }
2166
-
2167
-
2168
-
2169
-    /**
2170
-     * Just calls the specified method on $wpdb with the given arguments
2171
-     * Consolidates a little extra error handling code
2172
-     *
2173
-     * @param string $wpdb_method
2174
-     * @param array  $arguments_to_provide
2175
-     * @throws EE_Error
2176
-     * @global wpdb  $wpdb
2177
-     * @return mixed
2178
-     */
2179
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2180
-    {
2181
-        //if we're in maintenance mode level 2, DON'T run any queries
2182
-        //because level 2 indicates the database needs updating and
2183
-        //is probably out of sync with the code
2184
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2185
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2186
-                "event_espresso")));
2187
-        }
2188
-        /** @type WPDB $wpdb */
2189
-        global $wpdb;
2190
-        if (! method_exists($wpdb, $wpdb_method)) {
2191
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2192
-                'event_espresso'), $wpdb_method));
2193
-        }
2194
-        if (WP_DEBUG) {
2195
-            $old_show_errors_value = $wpdb->show_errors;
2196
-            $wpdb->show_errors(false);
2197
-        }
2198
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2199
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2200
-        if (WP_DEBUG) {
2201
-            $wpdb->show_errors($old_show_errors_value);
2202
-            if (! empty($wpdb->last_error)) {
2203
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2204
-            } elseif ($result === false) {
2205
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2206
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2207
-            }
2208
-        } elseif ($result === false) {
2209
-            EE_Error::add_error(
2210
-                sprintf(
2211
-                    __('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2212
-                        'event_espresso'),
2213
-                    $wpdb_method,
2214
-                    var_export($arguments_to_provide, true),
2215
-                    $wpdb->last_error
2216
-                ),
2217
-                __FILE__,
2218
-                __FUNCTION__,
2219
-                __LINE__
2220
-            );
2221
-        }
2222
-        return $result;
2223
-    }
2224
-
2225
-
2226
-
2227
-    /**
2228
-     * Attempts to run the indicated WPDB method with the provided arguments,
2229
-     * and if there's an error tries to verify the DB is correct. Uses
2230
-     * the static property EEM_Base::$_db_verification_level to determine whether
2231
-     * we should try to fix the EE core db, the addons, or just give up
2232
-     *
2233
-     * @param string $wpdb_method
2234
-     * @param array  $arguments_to_provide
2235
-     * @return mixed
2236
-     */
2237
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2238
-    {
2239
-        /** @type WPDB $wpdb */
2240
-        global $wpdb;
2241
-        $wpdb->last_error = null;
2242
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2243
-        // was there an error running the query? but we don't care on new activations
2244
-        // (we're going to setup the DB anyway on new activations)
2245
-        if (($result === false || ! empty($wpdb->last_error))
2246
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2247
-        ) {
2248
-            switch (EEM_Base::$_db_verification_level) {
2249
-                case EEM_Base::db_verified_none :
2250
-                    // let's double-check core's DB
2251
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2252
-                    break;
2253
-                case EEM_Base::db_verified_core :
2254
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2255
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2256
-                    break;
2257
-                case EEM_Base::db_verified_addons :
2258
-                    // ummmm... you in trouble
2259
-                    return $result;
2260
-                    break;
2261
-            }
2262
-            if (! empty($error_message)) {
2263
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2264
-                trigger_error($error_message);
2265
-            }
2266
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2267
-        }
2268
-        return $result;
2269
-    }
2270
-
2271
-
2272
-
2273
-    /**
2274
-     * Verifies the EE core database is up-to-date and records that we've done it on
2275
-     * EEM_Base::$_db_verification_level
2276
-     *
2277
-     * @param string $wpdb_method
2278
-     * @param array  $arguments_to_provide
2279
-     * @return string
2280
-     */
2281
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2282
-    {
2283
-        /** @type WPDB $wpdb */
2284
-        global $wpdb;
2285
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2286
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2287
-        $error_message = sprintf(
2288
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2289
-                'event_espresso'),
2290
-            $wpdb->last_error,
2291
-            $wpdb_method,
2292
-            wp_json_encode($arguments_to_provide)
2293
-        );
2294
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2295
-        return $error_message;
2296
-    }
2297
-
2298
-
2299
-
2300
-    /**
2301
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2302
-     * EEM_Base::$_db_verification_level
2303
-     *
2304
-     * @param $wpdb_method
2305
-     * @param $arguments_to_provide
2306
-     * @return string
2307
-     */
2308
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2309
-    {
2310
-        /** @type WPDB $wpdb */
2311
-        global $wpdb;
2312
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2313
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2314
-        $error_message = sprintf(
2315
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2316
-                'event_espresso'),
2317
-            $wpdb->last_error,
2318
-            $wpdb_method,
2319
-            wp_json_encode($arguments_to_provide)
2320
-        );
2321
-        EE_System::instance()->initialize_addons();
2322
-        return $error_message;
2323
-    }
2324
-
2325
-
2326
-
2327
-    /**
2328
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2329
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2330
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2331
-     * ..."
2332
-     *
2333
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2334
-     * @return string
2335
-     */
2336
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2337
-    {
2338
-        return " FROM " . $model_query_info->get_full_join_sql() .
2339
-               $model_query_info->get_where_sql() .
2340
-               $model_query_info->get_group_by_sql() .
2341
-               $model_query_info->get_having_sql() .
2342
-               $model_query_info->get_order_by_sql() .
2343
-               $model_query_info->get_limit_sql();
2344
-    }
2345
-
2346
-
2347
-
2348
-    /**
2349
-     * Set to easily debug the next X queries ran from this model.
2350
-     *
2351
-     * @param int $count
2352
-     */
2353
-    public function show_next_x_db_queries($count = 1)
2354
-    {
2355
-        $this->_show_next_x_db_queries = $count;
2356
-    }
2357
-
2358
-
2359
-
2360
-    /**
2361
-     * @param $sql_query
2362
-     */
2363
-    public function show_db_query_if_previously_requested($sql_query)
2364
-    {
2365
-        if ($this->_show_next_x_db_queries > 0) {
2366
-            echo $sql_query;
2367
-            $this->_show_next_x_db_queries--;
2368
-        }
2369
-    }
2370
-
2371
-
2372
-
2373
-    /**
2374
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2375
-     * There are the 3 cases:
2376
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2377
-     * $otherModelObject has no ID, it is first saved.
2378
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2379
-     * has no ID, it is first saved.
2380
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2381
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2382
-     * join table
2383
-     *
2384
-     * @param        EE_Base_Class                     /int $thisModelObject
2385
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2386
-     * @param string $relationName                     , key in EEM_Base::_relations
2387
-     *                                                 an attendee to a group, you also want to specify which role they
2388
-     *                                                 will have in that group. So you would use this parameter to
2389
-     *                                                 specify array('role-column-name'=>'role-id')
2390
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2391
-     *                                                 to for relation to methods that allow you to further specify
2392
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2393
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2394
-     *                                                 because these will be inserted in any new rows created as well.
2395
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2396
-     * @throws EE_Error
2397
-     */
2398
-    public function add_relationship_to(
2399
-        $id_or_obj,
2400
-        $other_model_id_or_obj,
2401
-        $relationName,
2402
-        $extra_join_model_fields_n_values = array()
2403
-    ) {
2404
-        $relation_obj = $this->related_settings_for($relationName);
2405
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2406
-    }
2407
-
2408
-
2409
-
2410
-    /**
2411
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2412
-     * There are the 3 cases:
2413
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2414
-     * error
2415
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2416
-     * an error
2417
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2418
-     *
2419
-     * @param        EE_Base_Class /int $id_or_obj
2420
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2421
-     * @param string $relationName key in EEM_Base::_relations
2422
-     * @return boolean of success
2423
-     * @throws EE_Error
2424
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2425
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2426
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2427
-     *                             because these will be inserted in any new rows created as well.
2428
-     */
2429
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2430
-    {
2431
-        $relation_obj = $this->related_settings_for($relationName);
2432
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2433
-    }
2434
-
2435
-
2436
-
2437
-    /**
2438
-     * @param mixed           $id_or_obj
2439
-     * @param string          $relationName
2440
-     * @param array           $where_query_params
2441
-     * @param EE_Base_Class[] objects to which relations were removed
2442
-     * @return \EE_Base_Class[]
2443
-     * @throws EE_Error
2444
-     */
2445
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2446
-    {
2447
-        $relation_obj = $this->related_settings_for($relationName);
2448
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2449
-    }
2450
-
2451
-
2452
-
2453
-    /**
2454
-     * Gets all the related items of the specified $model_name, using $query_params.
2455
-     * Note: by default, we remove the "default query params"
2456
-     * because we want to get even deleted items etc.
2457
-     *
2458
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2459
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2460
-     * @param array  $query_params like EEM_Base::get_all
2461
-     * @return EE_Base_Class[]
2462
-     * @throws EE_Error
2463
-     */
2464
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2465
-    {
2466
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2467
-        $relation_settings = $this->related_settings_for($model_name);
2468
-        return $relation_settings->get_all_related($model_obj, $query_params);
2469
-    }
2470
-
2471
-
2472
-
2473
-    /**
2474
-     * Deletes all the model objects across the relation indicated by $model_name
2475
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2476
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2477
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2478
-     *
2479
-     * @param EE_Base_Class|int|string $id_or_obj
2480
-     * @param string                   $model_name
2481
-     * @param array                    $query_params
2482
-     * @return int how many deleted
2483
-     * @throws EE_Error
2484
-     */
2485
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2486
-    {
2487
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2488
-        $relation_settings = $this->related_settings_for($model_name);
2489
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Hard deletes all the model objects across the relation indicated by $model_name
2496
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2497
-     * the model objects can't be hard deleted because of blocking related model objects,
2498
-     * just does a soft-delete on them instead.
2499
-     *
2500
-     * @param EE_Base_Class|int|string $id_or_obj
2501
-     * @param string                   $model_name
2502
-     * @param array                    $query_params
2503
-     * @return int how many deleted
2504
-     * @throws EE_Error
2505
-     */
2506
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2507
-    {
2508
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2509
-        $relation_settings = $this->related_settings_for($model_name);
2510
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2517
-     * unless otherwise specified in the $query_params
2518
-     *
2519
-     * @param        int             /EE_Base_Class $id_or_obj
2520
-     * @param string $model_name     like 'Event', or 'Registration'
2521
-     * @param array  $query_params   like EEM_Base::get_all's
2522
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2523
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2524
-     *                               that by the setting $distinct to TRUE;
2525
-     * @return int
2526
-     * @throws EE_Error
2527
-     */
2528
-    public function count_related(
2529
-        $id_or_obj,
2530
-        $model_name,
2531
-        $query_params = array(),
2532
-        $field_to_count = null,
2533
-        $distinct = false
2534
-    ) {
2535
-        $related_model = $this->get_related_model_obj($model_name);
2536
-        //we're just going to use the query params on the related model's normal get_all query,
2537
-        //except add a condition to say to match the current mod
2538
-        if (! isset($query_params['default_where_conditions'])) {
2539
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2540
-        }
2541
-        $this_model_name = $this->get_this_model_name();
2542
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2543
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2544
-        return $related_model->count($query_params, $field_to_count, $distinct);
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2551
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2552
-     *
2553
-     * @param        int           /EE_Base_Class $id_or_obj
2554
-     * @param string $model_name   like 'Event', or 'Registration'
2555
-     * @param array  $query_params like EEM_Base::get_all's
2556
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
-     * @return float
2558
-     * @throws EE_Error
2559
-     */
2560
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2561
-    {
2562
-        $related_model = $this->get_related_model_obj($model_name);
2563
-        if (! is_array($query_params)) {
2564
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2565
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2566
-                    gettype($query_params)), '4.6.0');
2567
-            $query_params = array();
2568
-        }
2569
-        //we're just going to use the query params on the related model's normal get_all query,
2570
-        //except add a condition to say to match the current mod
2571
-        if (! isset($query_params['default_where_conditions'])) {
2572
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2573
-        }
2574
-        $this_model_name = $this->get_this_model_name();
2575
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2576
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2577
-        return $related_model->sum($query_params, $field_to_sum);
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2584
-     * $modelObject
2585
-     *
2586
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2587
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2588
-     * @param array               $query_params     like EEM_Base::get_all's
2589
-     * @return EE_Base_Class
2590
-     * @throws EE_Error
2591
-     */
2592
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2593
-    {
2594
-        $query_params['limit'] = 1;
2595
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2596
-        if ($results) {
2597
-            return array_shift($results);
2598
-        } else {
2599
-            return null;
2600
-        }
2601
-    }
2602
-
2603
-
2604
-
2605
-    /**
2606
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2607
-     *
2608
-     * @return string
2609
-     */
2610
-    public function get_this_model_name()
2611
-    {
2612
-        return str_replace("EEM_", "", get_class($this));
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2619
-     *
2620
-     * @return EE_Any_Foreign_Model_Name_Field
2621
-     * @throws EE_Error
2622
-     */
2623
-    public function get_field_containing_related_model_name()
2624
-    {
2625
-        foreach ($this->field_settings(true) as $field) {
2626
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2627
-                $field_with_model_name = $field;
2628
-            }
2629
-        }
2630
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2631
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2632
-                $this->get_this_model_name()));
2633
-        }
2634
-        return $field_with_model_name;
2635
-    }
2636
-
2637
-
2638
-
2639
-    /**
2640
-     * Inserts a new entry into the database, for each table.
2641
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2642
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2643
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2644
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2645
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2646
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2647
-     *
2648
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2649
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2650
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2651
-     *                              of EEM_Base)
2652
-     * @return int new primary key on main table that got inserted
2653
-     * @throws EE_Error
2654
-     */
2655
-    public function insert($field_n_values)
2656
-    {
2657
-        /**
2658
-         * Filters the fields and their values before inserting an item using the models
2659
-         *
2660
-         * @param array    $fields_n_values keys are the fields and values are their new values
2661
-         * @param EEM_Base $model           the model used
2662
-         */
2663
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2664
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2665
-            $main_table = $this->_get_main_table();
2666
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2667
-            if ($new_id !== false) {
2668
-                foreach ($this->_get_other_tables() as $other_table) {
2669
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2670
-                }
2671
-            }
2672
-            /**
2673
-             * Done just after attempting to insert a new model object
2674
-             *
2675
-             * @param EEM_Base   $model           used
2676
-             * @param array      $fields_n_values fields and their values
2677
-             * @param int|string the              ID of the newly-inserted model object
2678
-             */
2679
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2680
-            return $new_id;
2681
-        } else {
2682
-            return false;
2683
-        }
2684
-    }
2685
-
2686
-
2687
-
2688
-    /**
2689
-     * Checks that the result would satisfy the unique indexes on this model
2690
-     *
2691
-     * @param array  $field_n_values
2692
-     * @param string $action
2693
-     * @return boolean
2694
-     * @throws EE_Error
2695
-     */
2696
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2697
-    {
2698
-        foreach ($this->unique_indexes() as $index_name => $index) {
2699
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2700
-            if ($this->exists(array($uniqueness_where_params))) {
2701
-                EE_Error::add_error(
2702
-                    sprintf(
2703
-                        __(
2704
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2705
-                            "event_espresso"
2706
-                        ),
2707
-                        $action,
2708
-                        $this->_get_class_name(),
2709
-                        $index_name,
2710
-                        implode(",", $index->field_names()),
2711
-                        http_build_query($uniqueness_where_params)
2712
-                    ),
2713
-                    __FILE__,
2714
-                    __FUNCTION__,
2715
-                    __LINE__
2716
-                );
2717
-                return false;
2718
-            }
2719
-        }
2720
-        return true;
2721
-    }
2722
-
2723
-
2724
-
2725
-    /**
2726
-     * Checks the database for an item that conflicts (ie, if this item were
2727
-     * saved to the DB would break some uniqueness requirement, like a primary key
2728
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2729
-     * can be either an EE_Base_Class or an array of fields n values
2730
-     *
2731
-     * @param EE_Base_Class|array $obj_or_fields_array
2732
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2733
-     *                                                 when looking for conflicts
2734
-     *                                                 (ie, if false, we ignore the model object's primary key
2735
-     *                                                 when finding "conflicts". If true, it's also considered).
2736
-     *                                                 Only works for INT primary key,
2737
-     *                                                 STRING primary keys cannot be ignored
2738
-     * @throws EE_Error
2739
-     * @return EE_Base_Class|array
2740
-     */
2741
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2742
-    {
2743
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2744
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2745
-        } elseif (is_array($obj_or_fields_array)) {
2746
-            $fields_n_values = $obj_or_fields_array;
2747
-        } else {
2748
-            throw new EE_Error(
2749
-                sprintf(
2750
-                    __(
2751
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2752
-                        "event_espresso"
2753
-                    ),
2754
-                    get_class($this),
2755
-                    $obj_or_fields_array
2756
-                )
2757
-            );
2758
-        }
2759
-        $query_params = array();
2760
-        if ($this->has_primary_key_field()
2761
-            && ($include_primary_key
2762
-                || $this->get_primary_key_field()
2763
-                   instanceof
2764
-                   EE_Primary_Key_String_Field)
2765
-            && isset($fields_n_values[$this->primary_key_name()])
2766
-        ) {
2767
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2768
-        }
2769
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2770
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2771
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2772
-        }
2773
-        //if there is nothing to base this search on, then we shouldn't find anything
2774
-        if (empty($query_params)) {
2775
-            return array();
2776
-        } else {
2777
-            return $this->get_one($query_params);
2778
-        }
2779
-    }
2780
-
2781
-
2782
-
2783
-    /**
2784
-     * Like count, but is optimized and returns a boolean instead of an int
2785
-     *
2786
-     * @param array $query_params
2787
-     * @return boolean
2788
-     * @throws EE_Error
2789
-     */
2790
-    public function exists($query_params)
2791
-    {
2792
-        $query_params['limit'] = 1;
2793
-        return $this->count($query_params) > 0;
2794
-    }
2795
-
2796
-
2797
-
2798
-    /**
2799
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2800
-     *
2801
-     * @param int|string $id
2802
-     * @return boolean
2803
-     * @throws EE_Error
2804
-     */
2805
-    public function exists_by_ID($id)
2806
-    {
2807
-        return $this->exists(
2808
-            array(
2809
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2810
-                array(
2811
-                    $this->primary_key_name() => $id,
2812
-                ),
2813
-            )
2814
-        );
2815
-    }
2816
-
2817
-
2818
-
2819
-    /**
2820
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2821
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2822
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2823
-     * on the main table)
2824
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2825
-     * cases where we want to call it directly rather than via insert().
2826
-     *
2827
-     * @access   protected
2828
-     * @param EE_Table_Base $table
2829
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2830
-     *                                       float
2831
-     * @param int           $new_id          for now we assume only int keys
2832
-     * @throws EE_Error
2833
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2834
-     * @return int ID of new row inserted, or FALSE on failure
2835
-     */
2836
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2837
-    {
2838
-        global $wpdb;
2839
-        $insertion_col_n_values = array();
2840
-        $format_for_insertion = array();
2841
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2842
-        foreach ($fields_on_table as $field_name => $field_obj) {
2843
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2844
-            if ($field_obj->is_auto_increment()) {
2845
-                continue;
2846
-            }
2847
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2848
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2849
-            if ($prepared_value !== null) {
2850
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2851
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2852
-            }
2853
-        }
2854
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2855
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2856
-            //so add the fk to the main table as a column
2857
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2858
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2859
-        }
2860
-        //insert the new entry
2861
-        $result = $this->_do_wpdb_query('insert',
2862
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2863
-        if ($result === false) {
2864
-            return false;
2865
-        }
2866
-        //ok, now what do we return for the ID of the newly-inserted thing?
2867
-        if ($this->has_primary_key_field()) {
2868
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2869
-                return $wpdb->insert_id;
2870
-            } else {
2871
-                //it's not an auto-increment primary key, so
2872
-                //it must have been supplied
2873
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2874
-            }
2875
-        } else {
2876
-            //we can't return a  primary key because there is none. instead return
2877
-            //a unique string indicating this model
2878
-            return $this->get_index_primary_key_string($fields_n_values);
2879
-        }
2880
-    }
2881
-
2882
-
2883
-
2884
-    /**
2885
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2886
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2887
-     * and there is no default, we pass it along. WPDB will take care of it)
2888
-     *
2889
-     * @param EE_Model_Field_Base $field_obj
2890
-     * @param array               $fields_n_values
2891
-     * @return mixed string|int|float depending on what the table column will be expecting
2892
-     * @throws EE_Error
2893
-     */
2894
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2895
-    {
2896
-        //if this field doesn't allow nullable, don't allow it
2897
-        if (
2898
-            ! $field_obj->is_nullable()
2899
-            && (
2900
-                ! isset($fields_n_values[$field_obj->get_name()])
2901
-                || $fields_n_values[$field_obj->get_name()] === null
2902
-            )
2903
-        ) {
2904
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2905
-        }
2906
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2907
-            ? $fields_n_values[$field_obj->get_name()]
2908
-            : null;
2909
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2910
-    }
2911
-
2912
-
2913
-
2914
-    /**
2915
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2916
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2917
-     * the field's prepare_for_set() method.
2918
-     *
2919
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2920
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2921
-     *                                   top of file)
2922
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2923
-     *                                   $value is a custom selection
2924
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2925
-     */
2926
-    private function _prepare_value_for_use_in_db($value, $field)
2927
-    {
2928
-        if ($field && $field instanceof EE_Model_Field_Base) {
2929
-            switch ($this->_values_already_prepared_by_model_object) {
2930
-                /** @noinspection PhpMissingBreakStatementInspection */
2931
-                case self::not_prepared_by_model_object:
2932
-                    $value = $field->prepare_for_set($value);
2933
-                //purposefully left out "return"
2934
-                case self::prepared_by_model_object:
2935
-                    $value = $field->prepare_for_use_in_db($value);
2936
-                case self::prepared_for_use_in_db:
2937
-                    //leave the value alone
2938
-            }
2939
-            return $value;
2940
-        } else {
2941
-            return $value;
2942
-        }
2943
-    }
2944
-
2945
-
2946
-
2947
-    /**
2948
-     * Returns the main table on this model
2949
-     *
2950
-     * @return EE_Primary_Table
2951
-     * @throws EE_Error
2952
-     */
2953
-    protected function _get_main_table()
2954
-    {
2955
-        foreach ($this->_tables as $table) {
2956
-            if ($table instanceof EE_Primary_Table) {
2957
-                return $table;
2958
-            }
2959
-        }
2960
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2961
-            'event_espresso'), get_class($this)));
2962
-    }
2963
-
2964
-
2965
-
2966
-    /**
2967
-     * table
2968
-     * returns EE_Primary_Table table name
2969
-     *
2970
-     * @return string
2971
-     * @throws EE_Error
2972
-     */
2973
-    public function table()
2974
-    {
2975
-        return $this->_get_main_table()->get_table_name();
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * table
2982
-     * returns first EE_Secondary_Table table name
2983
-     *
2984
-     * @return string
2985
-     */
2986
-    public function second_table()
2987
-    {
2988
-        // grab second table from tables array
2989
-        $second_table = end($this->_tables);
2990
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2991
-    }
2992
-
2993
-
2994
-
2995
-    /**
2996
-     * get_table_obj_by_alias
2997
-     * returns table name given it's alias
2998
-     *
2999
-     * @param string $table_alias
3000
-     * @return EE_Primary_Table | EE_Secondary_Table
3001
-     */
3002
-    public function get_table_obj_by_alias($table_alias = '')
3003
-    {
3004
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3005
-    }
3006
-
3007
-
3008
-
3009
-    /**
3010
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3011
-     *
3012
-     * @return EE_Secondary_Table[]
3013
-     */
3014
-    protected function _get_other_tables()
3015
-    {
3016
-        $other_tables = array();
3017
-        foreach ($this->_tables as $table_alias => $table) {
3018
-            if ($table instanceof EE_Secondary_Table) {
3019
-                $other_tables[$table_alias] = $table;
3020
-            }
3021
-        }
3022
-        return $other_tables;
3023
-    }
3024
-
3025
-
3026
-
3027
-    /**
3028
-     * Finds all the fields that correspond to the given table
3029
-     *
3030
-     * @param string $table_alias , array key in EEM_Base::_tables
3031
-     * @return EE_Model_Field_Base[]
3032
-     */
3033
-    public function _get_fields_for_table($table_alias)
3034
-    {
3035
-        return $this->_fields[$table_alias];
3036
-    }
3037
-
3038
-
3039
-
3040
-    /**
3041
-     * Recurses through all the where parameters, and finds all the related models we'll need
3042
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3043
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3044
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3045
-     * related Registration, Transaction, and Payment models.
3046
-     *
3047
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3048
-     * @return EE_Model_Query_Info_Carrier
3049
-     * @throws EE_Error
3050
-     */
3051
-    public function _extract_related_models_from_query($query_params)
3052
-    {
3053
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3054
-        if (array_key_exists(0, $query_params)) {
3055
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3056
-        }
3057
-        if (array_key_exists('group_by', $query_params)) {
3058
-            if (is_array($query_params['group_by'])) {
3059
-                $this->_extract_related_models_from_sub_params_array_values(
3060
-                    $query_params['group_by'],
3061
-                    $query_info_carrier,
3062
-                    'group_by'
3063
-                );
3064
-            } elseif (! empty ($query_params['group_by'])) {
3065
-                $this->_extract_related_model_info_from_query_param(
3066
-                    $query_params['group_by'],
3067
-                    $query_info_carrier,
3068
-                    'group_by'
3069
-                );
3070
-            }
3071
-        }
3072
-        if (array_key_exists('having', $query_params)) {
3073
-            $this->_extract_related_models_from_sub_params_array_keys(
3074
-                $query_params[0],
3075
-                $query_info_carrier,
3076
-                'having'
3077
-            );
3078
-        }
3079
-        if (array_key_exists('order_by', $query_params)) {
3080
-            if (is_array($query_params['order_by'])) {
3081
-                $this->_extract_related_models_from_sub_params_array_keys(
3082
-                    $query_params['order_by'],
3083
-                    $query_info_carrier,
3084
-                    'order_by'
3085
-                );
3086
-            } elseif (! empty($query_params['order_by'])) {
3087
-                $this->_extract_related_model_info_from_query_param(
3088
-                    $query_params['order_by'],
3089
-                    $query_info_carrier,
3090
-                    'order_by'
3091
-                );
3092
-            }
3093
-        }
3094
-        if (array_key_exists('force_join', $query_params)) {
3095
-            $this->_extract_related_models_from_sub_params_array_values(
3096
-                $query_params['force_join'],
3097
-                $query_info_carrier,
3098
-                'force_join'
3099
-            );
3100
-        }
3101
-        return $query_info_carrier;
3102
-    }
3103
-
3104
-
3105
-
3106
-    /**
3107
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3108
-     *
3109
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3110
-     *                                                      $query_params['having']
3111
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3112
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3113
-     * @throws EE_Error
3114
-     * @return \EE_Model_Query_Info_Carrier
3115
-     */
3116
-    private function _extract_related_models_from_sub_params_array_keys(
3117
-        $sub_query_params,
3118
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3119
-        $query_param_type
3120
-    ) {
3121
-        if (! empty($sub_query_params)) {
3122
-            $sub_query_params = (array)$sub_query_params;
3123
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3124
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3125
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3126
-                    $query_param_type);
3127
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3128
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3129
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3130
-                //of array('Registration.TXN_ID'=>23)
3131
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3132
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3133
-                    if (! is_array($possibly_array_of_params)) {
3134
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3135
-                            "event_espresso"),
3136
-                            $param, $possibly_array_of_params));
3137
-                    } else {
3138
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3139
-                            $model_query_info_carrier, $query_param_type);
3140
-                    }
3141
-                } elseif ($query_param_type === 0 //ie WHERE
3142
-                          && is_array($possibly_array_of_params)
3143
-                          && isset($possibly_array_of_params[2])
3144
-                          && $possibly_array_of_params[2] == true
3145
-                ) {
3146
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3147
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3148
-                    //from which we should extract query parameters!
3149
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3150
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3151
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3152
-                    }
3153
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3154
-                        $model_query_info_carrier, $query_param_type);
3155
-                }
3156
-            }
3157
-        }
3158
-        return $model_query_info_carrier;
3159
-    }
3160
-
3161
-
3162
-
3163
-    /**
3164
-     * For extracting related models from forced_joins, where the array values contain the info about what
3165
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3166
-     *
3167
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3168
-     *                                                      $query_params['having']
3169
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3170
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3171
-     * @throws EE_Error
3172
-     * @return \EE_Model_Query_Info_Carrier
3173
-     */
3174
-    private function _extract_related_models_from_sub_params_array_values(
3175
-        $sub_query_params,
3176
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3177
-        $query_param_type
3178
-    ) {
3179
-        if (! empty($sub_query_params)) {
3180
-            if (! is_array($sub_query_params)) {
3181
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3182
-                    $sub_query_params));
3183
-            }
3184
-            foreach ($sub_query_params as $param) {
3185
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3186
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3187
-                    $query_param_type);
3188
-            }
3189
-        }
3190
-        return $model_query_info_carrier;
3191
-    }
3192
-
3193
-
3194
-
3195
-    /**
3196
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3197
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3198
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3199
-     * but use them in a different order. Eg, we need to know what models we are querying
3200
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3201
-     * other models before we can finalize the where clause SQL.
3202
-     *
3203
-     * @param array $query_params
3204
-     * @throws EE_Error
3205
-     * @return EE_Model_Query_Info_Carrier
3206
-     */
3207
-    public function _create_model_query_info_carrier($query_params)
3208
-    {
3209
-        if (! is_array($query_params)) {
3210
-            EE_Error::doing_it_wrong(
3211
-                'EEM_Base::_create_model_query_info_carrier',
3212
-                sprintf(
3213
-                    __(
3214
-                        '$query_params should be an array, you passed a variable of type %s',
3215
-                        'event_espresso'
3216
-                    ),
3217
-                    gettype($query_params)
3218
-                ),
3219
-                '4.6.0'
3220
-            );
3221
-            $query_params = array();
3222
-        }
3223
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3224
-        //first check if we should alter the query to account for caps or not
3225
-        //because the caps might require us to do extra joins
3226
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3227
-            $query_params[0] = $where_query_params = array_replace_recursive(
3228
-                $where_query_params,
3229
-                $this->caps_where_conditions(
3230
-                    $query_params['caps']
3231
-                )
3232
-            );
3233
-        }
3234
-        $query_object = $this->_extract_related_models_from_query($query_params);
3235
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3236
-        foreach ($where_query_params as $key => $value) {
3237
-            if (is_int($key)) {
3238
-                throw new EE_Error(
3239
-                    sprintf(
3240
-                        __(
3241
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3242
-                            "event_espresso"
3243
-                        ),
3244
-                        $key,
3245
-                        var_export($value, true),
3246
-                        var_export($query_params, true),
3247
-                        get_class($this)
3248
-                    )
3249
-                );
3250
-            }
3251
-        }
3252
-        if (
3253
-            array_key_exists('default_where_conditions', $query_params)
3254
-            && ! empty($query_params['default_where_conditions'])
3255
-        ) {
3256
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3257
-        } else {
3258
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3259
-        }
3260
-        $where_query_params = array_merge(
3261
-            $this->_get_default_where_conditions_for_models_in_query(
3262
-                $query_object,
3263
-                $use_default_where_conditions,
3264
-                $where_query_params
3265
-            ),
3266
-            $where_query_params
3267
-        );
3268
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3269
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3270
-        // So we need to setup a subquery and use that for the main join.
3271
-        // Note for now this only works on the primary table for the model.
3272
-        // So for instance, you could set the limit array like this:
3273
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3274
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3275
-            $query_object->set_main_model_join_sql(
3276
-                $this->_construct_limit_join_select(
3277
-                    $query_params['on_join_limit'][0],
3278
-                    $query_params['on_join_limit'][1]
3279
-                )
3280
-            );
3281
-        }
3282
-        //set limit
3283
-        if (array_key_exists('limit', $query_params)) {
3284
-            if (is_array($query_params['limit'])) {
3285
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3286
-                    $e = sprintf(
3287
-                        __(
3288
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3289
-                            "event_espresso"
3290
-                        ),
3291
-                        http_build_query($query_params['limit'])
3292
-                    );
3293
-                    throw new EE_Error($e . "|" . $e);
3294
-                }
3295
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3296
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3297
-            } elseif (! empty ($query_params['limit'])) {
3298
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3299
-            }
3300
-        }
3301
-        //set order by
3302
-        if (array_key_exists('order_by', $query_params)) {
3303
-            if (is_array($query_params['order_by'])) {
3304
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3305
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3306
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3307
-                if (array_key_exists('order', $query_params)) {
3308
-                    throw new EE_Error(
3309
-                        sprintf(
3310
-                            __(
3311
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3312
-                                "event_espresso"
3313
-                            ),
3314
-                            get_class($this),
3315
-                            implode(", ", array_keys($query_params['order_by'])),
3316
-                            implode(", ", $query_params['order_by']),
3317
-                            $query_params['order']
3318
-                        )
3319
-                    );
3320
-                }
3321
-                $this->_extract_related_models_from_sub_params_array_keys(
3322
-                    $query_params['order_by'],
3323
-                    $query_object,
3324
-                    'order_by'
3325
-                );
3326
-                //assume it's an array of fields to order by
3327
-                $order_array = array();
3328
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3329
-                    $order = $this->_extract_order($order);
3330
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3331
-                }
3332
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3333
-            } elseif (! empty ($query_params['order_by'])) {
3334
-                $this->_extract_related_model_info_from_query_param(
3335
-                    $query_params['order_by'],
3336
-                    $query_object,
3337
-                    'order',
3338
-                    $query_params['order_by']
3339
-                );
3340
-                $order = isset($query_params['order'])
3341
-                    ? $this->_extract_order($query_params['order'])
3342
-                    : 'DESC';
3343
-                $query_object->set_order_by_sql(
3344
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3345
-                );
3346
-            }
3347
-        }
3348
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3349
-        if (! array_key_exists('order_by', $query_params)
3350
-            && array_key_exists('order', $query_params)
3351
-            && ! empty($query_params['order'])
3352
-        ) {
3353
-            $pk_field = $this->get_primary_key_field();
3354
-            $order = $this->_extract_order($query_params['order']);
3355
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3356
-        }
3357
-        //set group by
3358
-        if (array_key_exists('group_by', $query_params)) {
3359
-            if (is_array($query_params['group_by'])) {
3360
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3361
-                $group_by_array = array();
3362
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3363
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3364
-                }
3365
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3366
-            } elseif (! empty ($query_params['group_by'])) {
3367
-                $query_object->set_group_by_sql(
3368
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3369
-                );
3370
-            }
3371
-        }
3372
-        //set having
3373
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3374
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3375
-        }
3376
-        //now, just verify they didn't pass anything wack
3377
-        foreach ($query_params as $query_key => $query_value) {
3378
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3379
-                throw new EE_Error(
3380
-                    sprintf(
3381
-                        __(
3382
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3383
-                            'event_espresso'
3384
-                        ),
3385
-                        $query_key,
3386
-                        get_class($this),
3387
-                        //						print_r( $this->_allowed_query_params, TRUE )
3388
-                        implode(',', $this->_allowed_query_params)
3389
-                    )
3390
-                );
3391
-            }
3392
-        }
3393
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3394
-        if (empty($main_model_join_sql)) {
3395
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3396
-        }
3397
-        return $query_object;
3398
-    }
3399
-
3400
-
3401
-
3402
-    /**
3403
-     * Gets the where conditions that should be imposed on the query based on the
3404
-     * context (eg reading frontend, backend, edit or delete).
3405
-     *
3406
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3407
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3408
-     * @throws EE_Error
3409
-     */
3410
-    public function caps_where_conditions($context = self::caps_read)
3411
-    {
3412
-        EEM_Base::verify_is_valid_cap_context($context);
3413
-        $cap_where_conditions = array();
3414
-        $cap_restrictions = $this->caps_missing($context);
3415
-        /**
3416
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3417
-         */
3418
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3419
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3420
-                $restriction_if_no_cap->get_default_where_conditions());
3421
-        }
3422
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3423
-            $cap_restrictions);
3424
-    }
3425
-
3426
-
3427
-
3428
-    /**
3429
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3430
-     * otherwise throws an exception
3431
-     *
3432
-     * @param string $should_be_order_string
3433
-     * @return string either ASC, asc, DESC or desc
3434
-     * @throws EE_Error
3435
-     */
3436
-    private function _extract_order($should_be_order_string)
3437
-    {
3438
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3439
-            return $should_be_order_string;
3440
-        } else {
3441
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3442
-                "event_espresso"), get_class($this), $should_be_order_string));
3443
-        }
3444
-    }
3445
-
3446
-
3447
-
3448
-    /**
3449
-     * Looks at all the models which are included in this query, and asks each
3450
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3451
-     * so they can be merged
3452
-     *
3453
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3454
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3455
-     *                                                                  'none' means NO default where conditions will
3456
-     *                                                                  be used AT ALL during this query.
3457
-     *                                                                  'other_models_only' means default where
3458
-     *                                                                  conditions from other models will be used, but
3459
-     *                                                                  not for this primary model. 'all', the default,
3460
-     *                                                                  means default where conditions will apply as
3461
-     *                                                                  normal
3462
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3463
-     * @throws EE_Error
3464
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3465
-     */
3466
-    private function _get_default_where_conditions_for_models_in_query(
3467
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3468
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3469
-        $where_query_params = array()
3470
-    ) {
3471
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3472
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3473
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3474
-                "event_espresso"), $use_default_where_conditions,
3475
-                implode(", ", $allowed_used_default_where_conditions_values)));
3476
-        }
3477
-        $universal_query_params = array();
3478
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3479
-            $universal_query_params = $this->_get_default_where_conditions();
3480
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3481
-            $universal_query_params = $this->_get_minimum_where_conditions();
3482
-        }
3483
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3484
-            $related_model = $this->get_related_model_obj($model_name);
3485
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3486
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3487
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3488
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3489
-            } else {
3490
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3491
-                continue;
3492
-            }
3493
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3494
-                $related_model_universal_where_params,
3495
-                $where_query_params,
3496
-                $related_model,
3497
-                $model_relation_path
3498
-            );
3499
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3500
-                $universal_query_params,
3501
-                $overrides
3502
-            );
3503
-        }
3504
-        return $universal_query_params;
3505
-    }
3506
-
3507
-
3508
-
3509
-    /**
3510
-     * Determines whether or not we should use default where conditions for the model in question
3511
-     * (this model, or other related models).
3512
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3513
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3514
-     * We should use default where conditions on related models when they requested to use default where conditions
3515
-     * on all models, or specifically just on other related models
3516
-     * @param      $default_where_conditions_value
3517
-     * @param bool $for_this_model false means this is for OTHER related models
3518
-     * @return bool
3519
-     */
3520
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3521
-    {
3522
-        return (
3523
-                   $for_this_model
3524
-                   && in_array(
3525
-                       $default_where_conditions_value,
3526
-                       array(
3527
-                           EEM_Base::default_where_conditions_all,
3528
-                           EEM_Base::default_where_conditions_this_only,
3529
-                           EEM_Base::default_where_conditions_minimum_others,
3530
-                       ),
3531
-                       true
3532
-                   )
3533
-               )
3534
-               || (
3535
-                   ! $for_this_model
3536
-                   && in_array(
3537
-                       $default_where_conditions_value,
3538
-                       array(
3539
-                           EEM_Base::default_where_conditions_all,
3540
-                           EEM_Base::default_where_conditions_others_only,
3541
-                       ),
3542
-                       true
3543
-                   )
3544
-               );
3545
-    }
3546
-
3547
-    /**
3548
-     * Determines whether or not we should use default minimum conditions for the model in question
3549
-     * (this model, or other related models).
3550
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3551
-     * where conditions.
3552
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3553
-     * on this model or others
3554
-     * @param      $default_where_conditions_value
3555
-     * @param bool $for_this_model false means this is for OTHER related models
3556
-     * @return bool
3557
-     */
3558
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3559
-    {
3560
-        return (
3561
-                   $for_this_model
3562
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3563
-               )
3564
-               || (
3565
-                   ! $for_this_model
3566
-                   && in_array(
3567
-                       $default_where_conditions_value,
3568
-                       array(
3569
-                           EEM_Base::default_where_conditions_minimum_others,
3570
-                           EEM_Base::default_where_conditions_minimum_all,
3571
-                       ),
3572
-                       true
3573
-                   )
3574
-               );
3575
-    }
3576
-
3577
-
3578
-    /**
3579
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3580
-     * then we also add a special where condition which allows for that model's primary key
3581
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3582
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3583
-     *
3584
-     * @param array    $default_where_conditions
3585
-     * @param array    $provided_where_conditions
3586
-     * @param EEM_Base $model
3587
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3588
-     * @return array like EEM_Base::get_all's $query_params[0]
3589
-     * @throws EE_Error
3590
-     */
3591
-    private function _override_defaults_or_make_null_friendly(
3592
-        $default_where_conditions,
3593
-        $provided_where_conditions,
3594
-        $model,
3595
-        $model_relation_path
3596
-    ) {
3597
-        $null_friendly_where_conditions = array();
3598
-        $none_overridden = true;
3599
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3600
-        foreach ($default_where_conditions as $key => $val) {
3601
-            if (isset($provided_where_conditions[$key])) {
3602
-                $none_overridden = false;
3603
-            } else {
3604
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3605
-            }
3606
-        }
3607
-        if ($none_overridden && $default_where_conditions) {
3608
-            if ($model->has_primary_key_field()) {
3609
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3610
-                                                                                . "."
3611
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3612
-            }/*else{
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
+	 * @since 4.6.x
1490
+	 * @param string $field_name       The field the current time is needed for.
1491
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
+	 *                                 formatted string matching the set format for the field in the set timezone will
1493
+	 *                                 be returned.
1494
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+	 *                                 exception is triggered.
1498
+	 */
1499
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
+	{
1501
+		$formats = $this->get_formats_for($field_name);
1502
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
+		if ($timestamp) {
1504
+			return $DateTime->format('U');
1505
+		}
1506
+		//not returning timestamp, so return formatted string in timezone.
1507
+		switch ($what) {
1508
+			case 'time' :
1509
+				return $DateTime->format($formats[1]);
1510
+				break;
1511
+			case 'date' :
1512
+				return $DateTime->format($formats[0]);
1513
+				break;
1514
+			default :
1515
+				return $DateTime->format(implode(' ', $formats));
1516
+				break;
1517
+		}
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
+	 * for the model are.  Returns a DateTime object.
1525
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
+	 * ignored.
1528
+	 *
1529
+	 * @param string $field_name      The field being setup.
1530
+	 * @param string $timestring      The date time string being used.
1531
+	 * @param string $incoming_format The format for the time string.
1532
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
+	 *                                format is
1535
+	 *                                'U', this is ignored.
1536
+	 * @return DateTime
1537
+	 * @throws EE_Error
1538
+	 */
1539
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
+	{
1541
+		//just using this to ensure the timezone is set correctly internally
1542
+		$this->get_formats_for($field_name);
1543
+		//load EEH_DTT_Helper
1544
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
+	 *
1554
+	 * @return EE_Table_Base[]
1555
+	 */
1556
+	public function get_tables()
1557
+	{
1558
+		return $this->_tables;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
+	 * model object with EVT_ID = 1
1570
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
+	 * are not specified)
1575
+	 *
1576
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1581
+	 *                                         ID=34, we'd use this method as follows:
1582
+	 *                                         EEM_Transaction::instance()->update(
1583
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
+	 *                                         array(array('TXN_ID'=>34)));
1585
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1587
+	 *                                         consider updating Question's QST_admin_label field is of type
1588
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
+	 *                                         TRUE, it is assumed that you've already called
1593
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
+	 *                                         malicious javascript. However, if
1595
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
+	 *                                         and every other field, before insertion. We provide this parameter
1598
+	 *                                         because model objects perform their prepare_for_set function on all
1599
+	 *                                         their values, and so don't need to be called again (and in many cases,
1600
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
+	 *                                         prepare_for_set method...)
1602
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
+	 *                                         in this model's entity map according to $fields_n_values that match
1604
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1605
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1606
+	 *                                         could get out-of-sync with the database
1607
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
+	 *                                         bad)
1610
+	 * @throws EE_Error
1611
+	 */
1612
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
+	{
1614
+		if (! is_array($query_params)) {
1615
+			EE_Error::doing_it_wrong('EEM_Base::update',
1616
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
+					gettype($query_params)), '4.6.0');
1618
+			$query_params = array();
1619
+		}
1620
+		/**
1621
+		 * Action called before a model update call has been made.
1622
+		 *
1623
+		 * @param EEM_Base $model
1624
+		 * @param array    $fields_n_values the updated fields and their new values
1625
+		 * @param array    $query_params    @see EEM_Base::get_all()
1626
+		 */
1627
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
+		/**
1629
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1630
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1631
+		 *
1632
+		 * @param array    $fields_n_values fields and their new values
1633
+		 * @param EEM_Base $model           the model being queried
1634
+		 * @param array    $query_params    see EEM_Base::get_all()
1635
+		 */
1636
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
+			$query_params);
1638
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
+		//to do that, for each table, verify that it's PK isn't null.
1640
+		$tables = $this->get_tables();
1641
+		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1642
+		//NOTE: we should make this code more efficient by NOT querying twice
1643
+		//before the real update, but that needs to first go through ALPHA testing
1644
+		//as it's dangerous. says Mike August 8 2014
1645
+		//we want to make sure the default_where strategy is ignored
1646
+		$this->_ignore_where_strategy = true;
1647
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
+		foreach ($wpdb_select_results as $wpdb_result) {
1649
+			// type cast stdClass as array
1650
+			$wpdb_result = (array)$wpdb_result;
1651
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
+			if ($this->has_primary_key_field()) {
1653
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
+			} else {
1655
+				//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1656
+				$main_table_pk_value = null;
1657
+			}
1658
+			//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1659
+			//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
+			if (count($tables) > 1) {
1661
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
+				//in that table, and so we'll want to insert one
1663
+				foreach ($tables as $table_obj) {
1664
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
+					//if there is no private key for this table on the results, it means there's no entry
1666
+					//in this table, right? so insert a row in the current table, using any fields available
1667
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
+						   && $wpdb_result[$this_table_pk_column])
1669
+					) {
1670
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
+							$main_table_pk_value);
1672
+						//if we died here, report the error
1673
+						if (! $success) {
1674
+							return false;
1675
+						}
1676
+					}
1677
+				}
1678
+			}
1679
+			//				//and now check that if we have cached any models by that ID on the model, that
1680
+			//				//they also get updated properly
1681
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
+			//				if( $model_object ){
1683
+			//					foreach( $fields_n_values as $field => $value ){
1684
+			//						$model_object->set($field, $value);
1685
+			//let's make sure default_where strategy is followed now
1686
+			$this->_ignore_where_strategy = false;
1687
+		}
1688
+		//if we want to keep model objects in sync, AND
1689
+		//if this wasn't called from a model object (to update itself)
1690
+		//then we want to make sure we keep all the existing
1691
+		//model objects in sync with the db
1692
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
+			if ($this->has_primary_key_field()) {
1694
+				$model_objs_affected_ids = $this->get_col($query_params);
1695
+			} else {
1696
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
+				$model_objs_affected_ids = array();
1699
+				foreach ($models_affected_key_columns as $row) {
1700
+					$combined_index_key = $this->get_index_primary_key_string($row);
1701
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
+				}
1703
+			}
1704
+			if (! $model_objs_affected_ids) {
1705
+				//wait wait wait- if nothing was affected let's stop here
1706
+				return 0;
1707
+			}
1708
+			foreach ($model_objs_affected_ids as $id) {
1709
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
+				if ($model_obj_in_entity_map) {
1711
+					foreach ($fields_n_values as $field => $new_value) {
1712
+						$model_obj_in_entity_map->set($field, $new_value);
1713
+					}
1714
+				}
1715
+			}
1716
+			//if there is a primary key on this model, we can now do a slight optimization
1717
+			if ($this->has_primary_key_field()) {
1718
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
+				$query_params = array(
1720
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
+					'limit'                    => count($model_objs_affected_ids),
1722
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
+				);
1724
+			}
1725
+		}
1726
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
+		$SQL = "UPDATE "
1728
+			   . $model_query_info->get_full_join_sql()
1729
+			   . " SET "
1730
+			   . $this->_construct_update_sql($fields_n_values)
1731
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
+		/**
1734
+		 * Action called after a model update call has been made.
1735
+		 *
1736
+		 * @param EEM_Base $model
1737
+		 * @param array    $fields_n_values the updated fields and their new values
1738
+		 * @param array    $query_params    @see EEM_Base::get_all()
1739
+		 * @param int      $rows_affected
1740
+		 */
1741
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
+		return $rows_affected;//how many supposedly got updated
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
+	 * are teh values of the field specified (or by default the primary key field)
1750
+	 * that matched the query params. Note that you should pass the name of the
1751
+	 * model FIELD, not the database table's column name.
1752
+	 *
1753
+	 * @param array  $query_params @see EEM_Base::get_all()
1754
+	 * @param string $field_to_select
1755
+	 * @return array just like $wpdb->get_col()
1756
+	 * @throws EE_Error
1757
+	 */
1758
+	public function get_col($query_params = array(), $field_to_select = null)
1759
+	{
1760
+		if ($field_to_select) {
1761
+			$field = $this->field_settings_for($field_to_select);
1762
+		} elseif ($this->has_primary_key_field()) {
1763
+			$field = $this->get_primary_key_field();
1764
+		} else {
1765
+			//no primary key, just grab the first column
1766
+			$field = reset($this->field_settings());
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$select_expressions = $field->get_qualified_column();
1770
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
+		return $this->_do_wpdb_query('get_col', array($SQL));
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Returns a single column value for a single row from the database
1778
+	 *
1779
+	 * @param array  $query_params    @see EEM_Base::get_all()
1780
+	 * @param string $field_to_select @see EEM_Base::get_col()
1781
+	 * @return string
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function get_var($query_params = array(), $field_to_select = null)
1785
+	{
1786
+		$query_params['limit'] = 1;
1787
+		$col = $this->get_col($query_params, $field_to_select);
1788
+		if (! empty($col)) {
1789
+			return reset($col);
1790
+		} else {
1791
+			return null;
1792
+		}
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
+	 * injection, but currently no further filtering is done
1801
+	 *
1802
+	 * @global      $wpdb
1803
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
+	 *                               be updated to in the DB
1805
+	 * @return string of SQL
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function _construct_update_sql($fields_n_values)
1809
+	{
1810
+		/** @type WPDB $wpdb */
1811
+		global $wpdb;
1812
+		$cols_n_values = array();
1813
+		foreach ($fields_n_values as $field_name => $value) {
1814
+			$field_obj = $this->field_settings_for($field_name);
1815
+			//if the value is NULL, we want to assign the value to that.
1816
+			//wpdb->prepare doesn't really handle that properly
1817
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
+			$value_sql = $prepared_value === null ? 'NULL'
1819
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
+		}
1822
+		return implode(",", $cols_n_values);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Performs a HARD delete, meaning the database row should always be removed,
1830
+	 * not just have a flag field on it switched
1831
+	 * Wrapper for EEM_Base::delete_permanently()
1832
+	 *
1833
+	 * @param mixed $id
1834
+	 * @return boolean whether the row got deleted or not
1835
+	 * @throws EE_Error
1836
+	 */
1837
+	public function delete_permanently_by_ID($id)
1838
+	{
1839
+		return $this->delete_permanently(
1840
+			array(
1841
+				array($this->get_primary_key_field()->get_name() => $id),
1842
+				'limit' => 1,
1843
+			)
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Wrapper for EEM_Base::delete()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @return boolean whether the row got deleted or not
1855
+	 * @throws EE_Error
1856
+	 */
1857
+	public function delete_by_ID($id)
1858
+	{
1859
+		return $this->delete(
1860
+			array(
1861
+				array($this->get_primary_key_field()->get_name() => $id),
1862
+				'limit' => 1,
1863
+			)
1864
+		);
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1871
+	 * meaning if the model has a field that indicates its been "trashed" or
1872
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1873
+	 *
1874
+	 * @see EEM_Base::delete_permanently
1875
+	 * @param array   $query_params
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int how many rows got deleted
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function delete($query_params, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete_permanently($query_params, $allow_blocking);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1889
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
+	 * as archived, not actually deleted
1891
+	 *
1892
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1896
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
+	 *                                DB
1898
+	 * @return int how many rows got deleted
1899
+	 * @throws EE_Error
1900
+	 */
1901
+	public function delete_permanently($query_params, $allow_blocking = true)
1902
+	{
1903
+		/**
1904
+		 * Action called just before performing a real deletion query. You can use the
1905
+		 * model and its $query_params to find exactly which items will be deleted
1906
+		 *
1907
+		 * @param EEM_Base $model
1908
+		 * @param array    $query_params   @see EEM_Base::get_all()
1909
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1910
+		 *                                 to block (prevent) this deletion
1911
+		 */
1912
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
+		//some MySQL databases may be running safe mode, which may restrict
1914
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
+		//to delete them
1917
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1919
+		if ($deletion_where) {
1920
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1921
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1922
+			$table_aliases = array_keys($this->_tables);
1923
+			$SQL = "DELETE "
1924
+				   . implode(", ", $table_aliases)
1925
+				   . " FROM "
1926
+				   . $model_query_info->get_full_join_sql()
1927
+				   . " WHERE "
1928
+				   . $deletion_where;
1929
+			//		/echo "delete sql:$SQL";
1930
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
+		} else {
1932
+			$rows_deleted = 0;
1933
+		}
1934
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1935
+		if ($this->has_primary_key_field()) {
1936
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1937
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1938
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1939
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1940
+				}
1941
+			}
1942
+		}
1943
+		/**
1944
+		 * Action called just after performing a real deletion query. Although at this point the
1945
+		 * items should have been deleted
1946
+		 *
1947
+		 * @param EEM_Base $model
1948
+		 * @param array    $query_params @see EEM_Base::get_all()
1949
+		 * @param int      $rows_deleted
1950
+		 */
1951
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1952
+		return $rows_deleted;//how many supposedly got deleted
1953
+	}
1954
+
1955
+
1956
+
1957
+	/**
1958
+	 * Checks all the relations that throw error messages when there are blocking related objects
1959
+	 * for related model objects. If there are any related model objects on those relations,
1960
+	 * adds an EE_Error, and return true
1961
+	 *
1962
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1963
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1964
+	 *                                                 should be ignored when determining whether there are related
1965
+	 *                                                 model objects which block this model object's deletion. Useful
1966
+	 *                                                 if you know A is related to B and are considering deleting A,
1967
+	 *                                                 but want to see if A has any other objects blocking its deletion
1968
+	 *                                                 before removing the relation between A and B
1969
+	 * @return boolean
1970
+	 * @throws EE_Error
1971
+	 */
1972
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1973
+	{
1974
+		//first, if $ignore_this_model_obj was supplied, get its model
1975
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1976
+			$ignored_model = $ignore_this_model_obj->get_model();
1977
+		} else {
1978
+			$ignored_model = null;
1979
+		}
1980
+		//now check all the relations of $this_model_obj_or_id and see if there
1981
+		//are any related model objects blocking it?
1982
+		$is_blocked = false;
1983
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1984
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1985
+				//if $ignore_this_model_obj was supplied, then for the query
1986
+				//on that model needs to be told to ignore $ignore_this_model_obj
1987
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1988
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1989
+						array(
1990
+							$ignored_model->get_primary_key_field()->get_name() => array(
1991
+								'!=',
1992
+								$ignore_this_model_obj->ID(),
1993
+							),
1994
+						),
1995
+					));
1996
+				} else {
1997
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1998
+				}
1999
+				if ($related_model_objects) {
2000
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2001
+					$is_blocked = true;
2002
+				}
2003
+			}
2004
+		}
2005
+		return $is_blocked;
2006
+	}
2007
+
2008
+
2009
+
2010
+	/**
2011
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2012
+	 * well.
2013
+	 *
2014
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2015
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2016
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2017
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2018
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2019
+	 *                                      easily corrupt your DB
2020
+	 * @throws EE_Error
2021
+	 * @return string    everything that comes after the WHERE statement.
2022
+	 */
2023
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2024
+	{
2025
+		if ($this->has_primary_key_field()) {
2026
+			$primary_table = $this->_get_main_table();
2027
+			$other_tables = $this->_get_other_tables();
2028
+			$deletes = $query = array();
2029
+			foreach ($objects_for_deletion as $delete_object) {
2030
+				//before we mark this object for deletion,
2031
+				//make sure there's no related objects blocking its deletion (if we're checking)
2032
+				if (
2033
+					$allow_blocking
2034
+					&& $this->delete_is_blocked_by_related_models(
2035
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2036
+					)
2037
+				) {
2038
+					continue;
2039
+				}
2040
+				//primary table deletes
2041
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2042
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2043
+				}
2044
+				//other tables
2045
+				if (! empty($other_tables)) {
2046
+					foreach ($other_tables as $ot) {
2047
+						//first check if we've got the foreign key column here.
2048
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2049
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2050
+						}
2051
+						// wait! it's entirely possible that we'll have a the primary key
2052
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2053
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2054
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2055
+						}
2056
+						// finally, it is possible that the fk for this table is found
2057
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2058
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2059
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2060
+						}
2061
+					}
2062
+				}
2063
+			}
2064
+			//we should have deletes now, so let's just go through and setup the where statement
2065
+			foreach ($deletes as $column => $values) {
2066
+				//make sure we have unique $values;
2067
+				$values = array_unique($values);
2068
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2069
+			}
2070
+			return ! empty($query) ? implode(' AND ', $query) : '';
2071
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2072
+			$ways_to_identify_a_row = array();
2073
+			$fields = $this->get_combined_primary_key_fields();
2074
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2075
+			foreach ($objects_for_deletion as $delete_object) {
2076
+				$values_for_each_cpk_for_a_row = array();
2077
+				foreach ($fields as $cpk_field) {
2078
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2079
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2080
+														   . "="
2081
+														   . $delete_object[$cpk_field->get_qualified_column()];
2082
+					}
2083
+				}
2084
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2085
+			}
2086
+			return implode(" OR ", $ways_to_identify_a_row);
2087
+		} else {
2088
+			//so there's no primary key and no combined key...
2089
+			//sorry, can't help you
2090
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2091
+				"event_espresso"), get_class($this)));
2092
+		}
2093
+	}
2094
+
2095
+
2096
+
2097
+	/**
2098
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2099
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2100
+	 * column
2101
+	 *
2102
+	 * @param array  $query_params   like EEM_Base::get_all's
2103
+	 * @param string $field_to_count field on model to count by (not column name)
2104
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2105
+	 *                               that by the setting $distinct to TRUE;
2106
+	 * @return int
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2110
+	{
2111
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2112
+		if ($field_to_count) {
2113
+			$field_obj = $this->field_settings_for($field_to_count);
2114
+			$column_to_count = $field_obj->get_qualified_column();
2115
+		} elseif ($this->has_primary_key_field()) {
2116
+			$pk_field_obj = $this->get_primary_key_field();
2117
+			$column_to_count = $pk_field_obj->get_qualified_column();
2118
+		} else {
2119
+			//there's no primary key
2120
+			//if we're counting distinct items, and there's no primary key,
2121
+			//we need to list out the columns for distinction;
2122
+			//otherwise we can just use star
2123
+			if ($distinct) {
2124
+				$columns_to_use = array();
2125
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2126
+					$columns_to_use[] = $field_obj->get_qualified_column();
2127
+				}
2128
+				$column_to_count = implode(',', $columns_to_use);
2129
+			} else {
2130
+				$column_to_count = '*';
2131
+			}
2132
+		}
2133
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2134
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2135
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2136
+	}
2137
+
2138
+
2139
+
2140
+	/**
2141
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2142
+	 *
2143
+	 * @param array  $query_params like EEM_Base::get_all
2144
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2145
+	 * @return float
2146
+	 * @throws EE_Error
2147
+	 */
2148
+	public function sum($query_params, $field_to_sum = null)
2149
+	{
2150
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
+		if ($field_to_sum) {
2152
+			$field_obj = $this->field_settings_for($field_to_sum);
2153
+		} else {
2154
+			$field_obj = $this->get_primary_key_field();
2155
+		}
2156
+		$column_to_count = $field_obj->get_qualified_column();
2157
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2158
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2159
+		$data_type = $field_obj->get_wpdb_data_type();
2160
+		if ($data_type === '%d' || $data_type === '%s') {
2161
+			return (float)$return_value;
2162
+		} else {//must be %f
2163
+			return (float)$return_value;
2164
+		}
2165
+	}
2166
+
2167
+
2168
+
2169
+	/**
2170
+	 * Just calls the specified method on $wpdb with the given arguments
2171
+	 * Consolidates a little extra error handling code
2172
+	 *
2173
+	 * @param string $wpdb_method
2174
+	 * @param array  $arguments_to_provide
2175
+	 * @throws EE_Error
2176
+	 * @global wpdb  $wpdb
2177
+	 * @return mixed
2178
+	 */
2179
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2180
+	{
2181
+		//if we're in maintenance mode level 2, DON'T run any queries
2182
+		//because level 2 indicates the database needs updating and
2183
+		//is probably out of sync with the code
2184
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2185
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2186
+				"event_espresso")));
2187
+		}
2188
+		/** @type WPDB $wpdb */
2189
+		global $wpdb;
2190
+		if (! method_exists($wpdb, $wpdb_method)) {
2191
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2192
+				'event_espresso'), $wpdb_method));
2193
+		}
2194
+		if (WP_DEBUG) {
2195
+			$old_show_errors_value = $wpdb->show_errors;
2196
+			$wpdb->show_errors(false);
2197
+		}
2198
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2199
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2200
+		if (WP_DEBUG) {
2201
+			$wpdb->show_errors($old_show_errors_value);
2202
+			if (! empty($wpdb->last_error)) {
2203
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2204
+			} elseif ($result === false) {
2205
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2206
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2207
+			}
2208
+		} elseif ($result === false) {
2209
+			EE_Error::add_error(
2210
+				sprintf(
2211
+					__('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2212
+						'event_espresso'),
2213
+					$wpdb_method,
2214
+					var_export($arguments_to_provide, true),
2215
+					$wpdb->last_error
2216
+				),
2217
+				__FILE__,
2218
+				__FUNCTION__,
2219
+				__LINE__
2220
+			);
2221
+		}
2222
+		return $result;
2223
+	}
2224
+
2225
+
2226
+
2227
+	/**
2228
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2229
+	 * and if there's an error tries to verify the DB is correct. Uses
2230
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2231
+	 * we should try to fix the EE core db, the addons, or just give up
2232
+	 *
2233
+	 * @param string $wpdb_method
2234
+	 * @param array  $arguments_to_provide
2235
+	 * @return mixed
2236
+	 */
2237
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2238
+	{
2239
+		/** @type WPDB $wpdb */
2240
+		global $wpdb;
2241
+		$wpdb->last_error = null;
2242
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2243
+		// was there an error running the query? but we don't care on new activations
2244
+		// (we're going to setup the DB anyway on new activations)
2245
+		if (($result === false || ! empty($wpdb->last_error))
2246
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2247
+		) {
2248
+			switch (EEM_Base::$_db_verification_level) {
2249
+				case EEM_Base::db_verified_none :
2250
+					// let's double-check core's DB
2251
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2252
+					break;
2253
+				case EEM_Base::db_verified_core :
2254
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2255
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2256
+					break;
2257
+				case EEM_Base::db_verified_addons :
2258
+					// ummmm... you in trouble
2259
+					return $result;
2260
+					break;
2261
+			}
2262
+			if (! empty($error_message)) {
2263
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2264
+				trigger_error($error_message);
2265
+			}
2266
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2267
+		}
2268
+		return $result;
2269
+	}
2270
+
2271
+
2272
+
2273
+	/**
2274
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2275
+	 * EEM_Base::$_db_verification_level
2276
+	 *
2277
+	 * @param string $wpdb_method
2278
+	 * @param array  $arguments_to_provide
2279
+	 * @return string
2280
+	 */
2281
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2282
+	{
2283
+		/** @type WPDB $wpdb */
2284
+		global $wpdb;
2285
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2286
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2287
+		$error_message = sprintf(
2288
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2289
+				'event_espresso'),
2290
+			$wpdb->last_error,
2291
+			$wpdb_method,
2292
+			wp_json_encode($arguments_to_provide)
2293
+		);
2294
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2295
+		return $error_message;
2296
+	}
2297
+
2298
+
2299
+
2300
+	/**
2301
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2302
+	 * EEM_Base::$_db_verification_level
2303
+	 *
2304
+	 * @param $wpdb_method
2305
+	 * @param $arguments_to_provide
2306
+	 * @return string
2307
+	 */
2308
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2309
+	{
2310
+		/** @type WPDB $wpdb */
2311
+		global $wpdb;
2312
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2313
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2314
+		$error_message = sprintf(
2315
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2316
+				'event_espresso'),
2317
+			$wpdb->last_error,
2318
+			$wpdb_method,
2319
+			wp_json_encode($arguments_to_provide)
2320
+		);
2321
+		EE_System::instance()->initialize_addons();
2322
+		return $error_message;
2323
+	}
2324
+
2325
+
2326
+
2327
+	/**
2328
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2329
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2330
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2331
+	 * ..."
2332
+	 *
2333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2334
+	 * @return string
2335
+	 */
2336
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2337
+	{
2338
+		return " FROM " . $model_query_info->get_full_join_sql() .
2339
+			   $model_query_info->get_where_sql() .
2340
+			   $model_query_info->get_group_by_sql() .
2341
+			   $model_query_info->get_having_sql() .
2342
+			   $model_query_info->get_order_by_sql() .
2343
+			   $model_query_info->get_limit_sql();
2344
+	}
2345
+
2346
+
2347
+
2348
+	/**
2349
+	 * Set to easily debug the next X queries ran from this model.
2350
+	 *
2351
+	 * @param int $count
2352
+	 */
2353
+	public function show_next_x_db_queries($count = 1)
2354
+	{
2355
+		$this->_show_next_x_db_queries = $count;
2356
+	}
2357
+
2358
+
2359
+
2360
+	/**
2361
+	 * @param $sql_query
2362
+	 */
2363
+	public function show_db_query_if_previously_requested($sql_query)
2364
+	{
2365
+		if ($this->_show_next_x_db_queries > 0) {
2366
+			echo $sql_query;
2367
+			$this->_show_next_x_db_queries--;
2368
+		}
2369
+	}
2370
+
2371
+
2372
+
2373
+	/**
2374
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2375
+	 * There are the 3 cases:
2376
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2377
+	 * $otherModelObject has no ID, it is first saved.
2378
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2379
+	 * has no ID, it is first saved.
2380
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2381
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2382
+	 * join table
2383
+	 *
2384
+	 * @param        EE_Base_Class                     /int $thisModelObject
2385
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2386
+	 * @param string $relationName                     , key in EEM_Base::_relations
2387
+	 *                                                 an attendee to a group, you also want to specify which role they
2388
+	 *                                                 will have in that group. So you would use this parameter to
2389
+	 *                                                 specify array('role-column-name'=>'role-id')
2390
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2391
+	 *                                                 to for relation to methods that allow you to further specify
2392
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2393
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2394
+	 *                                                 because these will be inserted in any new rows created as well.
2395
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2396
+	 * @throws EE_Error
2397
+	 */
2398
+	public function add_relationship_to(
2399
+		$id_or_obj,
2400
+		$other_model_id_or_obj,
2401
+		$relationName,
2402
+		$extra_join_model_fields_n_values = array()
2403
+	) {
2404
+		$relation_obj = $this->related_settings_for($relationName);
2405
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2406
+	}
2407
+
2408
+
2409
+
2410
+	/**
2411
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2412
+	 * There are the 3 cases:
2413
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2414
+	 * error
2415
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2416
+	 * an error
2417
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2418
+	 *
2419
+	 * @param        EE_Base_Class /int $id_or_obj
2420
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2421
+	 * @param string $relationName key in EEM_Base::_relations
2422
+	 * @return boolean of success
2423
+	 * @throws EE_Error
2424
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2425
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2426
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2427
+	 *                             because these will be inserted in any new rows created as well.
2428
+	 */
2429
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2430
+	{
2431
+		$relation_obj = $this->related_settings_for($relationName);
2432
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * @param mixed           $id_or_obj
2439
+	 * @param string          $relationName
2440
+	 * @param array           $where_query_params
2441
+	 * @param EE_Base_Class[] objects to which relations were removed
2442
+	 * @return \EE_Base_Class[]
2443
+	 * @throws EE_Error
2444
+	 */
2445
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2446
+	{
2447
+		$relation_obj = $this->related_settings_for($relationName);
2448
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2449
+	}
2450
+
2451
+
2452
+
2453
+	/**
2454
+	 * Gets all the related items of the specified $model_name, using $query_params.
2455
+	 * Note: by default, we remove the "default query params"
2456
+	 * because we want to get even deleted items etc.
2457
+	 *
2458
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2459
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2460
+	 * @param array  $query_params like EEM_Base::get_all
2461
+	 * @return EE_Base_Class[]
2462
+	 * @throws EE_Error
2463
+	 */
2464
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2465
+	{
2466
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2467
+		$relation_settings = $this->related_settings_for($model_name);
2468
+		return $relation_settings->get_all_related($model_obj, $query_params);
2469
+	}
2470
+
2471
+
2472
+
2473
+	/**
2474
+	 * Deletes all the model objects across the relation indicated by $model_name
2475
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2476
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2477
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2478
+	 *
2479
+	 * @param EE_Base_Class|int|string $id_or_obj
2480
+	 * @param string                   $model_name
2481
+	 * @param array                    $query_params
2482
+	 * @return int how many deleted
2483
+	 * @throws EE_Error
2484
+	 */
2485
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2486
+	{
2487
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2488
+		$relation_settings = $this->related_settings_for($model_name);
2489
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2496
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2497
+	 * the model objects can't be hard deleted because of blocking related model objects,
2498
+	 * just does a soft-delete on them instead.
2499
+	 *
2500
+	 * @param EE_Base_Class|int|string $id_or_obj
2501
+	 * @param string                   $model_name
2502
+	 * @param array                    $query_params
2503
+	 * @return int how many deleted
2504
+	 * @throws EE_Error
2505
+	 */
2506
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2507
+	{
2508
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2509
+		$relation_settings = $this->related_settings_for($model_name);
2510
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2517
+	 * unless otherwise specified in the $query_params
2518
+	 *
2519
+	 * @param        int             /EE_Base_Class $id_or_obj
2520
+	 * @param string $model_name     like 'Event', or 'Registration'
2521
+	 * @param array  $query_params   like EEM_Base::get_all's
2522
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2523
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2524
+	 *                               that by the setting $distinct to TRUE;
2525
+	 * @return int
2526
+	 * @throws EE_Error
2527
+	 */
2528
+	public function count_related(
2529
+		$id_or_obj,
2530
+		$model_name,
2531
+		$query_params = array(),
2532
+		$field_to_count = null,
2533
+		$distinct = false
2534
+	) {
2535
+		$related_model = $this->get_related_model_obj($model_name);
2536
+		//we're just going to use the query params on the related model's normal get_all query,
2537
+		//except add a condition to say to match the current mod
2538
+		if (! isset($query_params['default_where_conditions'])) {
2539
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2540
+		}
2541
+		$this_model_name = $this->get_this_model_name();
2542
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2543
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2544
+		return $related_model->count($query_params, $field_to_count, $distinct);
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2551
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2552
+	 *
2553
+	 * @param        int           /EE_Base_Class $id_or_obj
2554
+	 * @param string $model_name   like 'Event', or 'Registration'
2555
+	 * @param array  $query_params like EEM_Base::get_all's
2556
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
+	 * @return float
2558
+	 * @throws EE_Error
2559
+	 */
2560
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2561
+	{
2562
+		$related_model = $this->get_related_model_obj($model_name);
2563
+		if (! is_array($query_params)) {
2564
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2565
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2566
+					gettype($query_params)), '4.6.0');
2567
+			$query_params = array();
2568
+		}
2569
+		//we're just going to use the query params on the related model's normal get_all query,
2570
+		//except add a condition to say to match the current mod
2571
+		if (! isset($query_params['default_where_conditions'])) {
2572
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2573
+		}
2574
+		$this_model_name = $this->get_this_model_name();
2575
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2576
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2577
+		return $related_model->sum($query_params, $field_to_sum);
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2584
+	 * $modelObject
2585
+	 *
2586
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2587
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2588
+	 * @param array               $query_params     like EEM_Base::get_all's
2589
+	 * @return EE_Base_Class
2590
+	 * @throws EE_Error
2591
+	 */
2592
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2593
+	{
2594
+		$query_params['limit'] = 1;
2595
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2596
+		if ($results) {
2597
+			return array_shift($results);
2598
+		} else {
2599
+			return null;
2600
+		}
2601
+	}
2602
+
2603
+
2604
+
2605
+	/**
2606
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2607
+	 *
2608
+	 * @return string
2609
+	 */
2610
+	public function get_this_model_name()
2611
+	{
2612
+		return str_replace("EEM_", "", get_class($this));
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2619
+	 *
2620
+	 * @return EE_Any_Foreign_Model_Name_Field
2621
+	 * @throws EE_Error
2622
+	 */
2623
+	public function get_field_containing_related_model_name()
2624
+	{
2625
+		foreach ($this->field_settings(true) as $field) {
2626
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2627
+				$field_with_model_name = $field;
2628
+			}
2629
+		}
2630
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2631
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2632
+				$this->get_this_model_name()));
2633
+		}
2634
+		return $field_with_model_name;
2635
+	}
2636
+
2637
+
2638
+
2639
+	/**
2640
+	 * Inserts a new entry into the database, for each table.
2641
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2642
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2643
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2644
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2645
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2646
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2647
+	 *
2648
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2649
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2650
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2651
+	 *                              of EEM_Base)
2652
+	 * @return int new primary key on main table that got inserted
2653
+	 * @throws EE_Error
2654
+	 */
2655
+	public function insert($field_n_values)
2656
+	{
2657
+		/**
2658
+		 * Filters the fields and their values before inserting an item using the models
2659
+		 *
2660
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2661
+		 * @param EEM_Base $model           the model used
2662
+		 */
2663
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2664
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2665
+			$main_table = $this->_get_main_table();
2666
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2667
+			if ($new_id !== false) {
2668
+				foreach ($this->_get_other_tables() as $other_table) {
2669
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2670
+				}
2671
+			}
2672
+			/**
2673
+			 * Done just after attempting to insert a new model object
2674
+			 *
2675
+			 * @param EEM_Base   $model           used
2676
+			 * @param array      $fields_n_values fields and their values
2677
+			 * @param int|string the              ID of the newly-inserted model object
2678
+			 */
2679
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2680
+			return $new_id;
2681
+		} else {
2682
+			return false;
2683
+		}
2684
+	}
2685
+
2686
+
2687
+
2688
+	/**
2689
+	 * Checks that the result would satisfy the unique indexes on this model
2690
+	 *
2691
+	 * @param array  $field_n_values
2692
+	 * @param string $action
2693
+	 * @return boolean
2694
+	 * @throws EE_Error
2695
+	 */
2696
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2697
+	{
2698
+		foreach ($this->unique_indexes() as $index_name => $index) {
2699
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2700
+			if ($this->exists(array($uniqueness_where_params))) {
2701
+				EE_Error::add_error(
2702
+					sprintf(
2703
+						__(
2704
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2705
+							"event_espresso"
2706
+						),
2707
+						$action,
2708
+						$this->_get_class_name(),
2709
+						$index_name,
2710
+						implode(",", $index->field_names()),
2711
+						http_build_query($uniqueness_where_params)
2712
+					),
2713
+					__FILE__,
2714
+					__FUNCTION__,
2715
+					__LINE__
2716
+				);
2717
+				return false;
2718
+			}
2719
+		}
2720
+		return true;
2721
+	}
2722
+
2723
+
2724
+
2725
+	/**
2726
+	 * Checks the database for an item that conflicts (ie, if this item were
2727
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2728
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2729
+	 * can be either an EE_Base_Class or an array of fields n values
2730
+	 *
2731
+	 * @param EE_Base_Class|array $obj_or_fields_array
2732
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2733
+	 *                                                 when looking for conflicts
2734
+	 *                                                 (ie, if false, we ignore the model object's primary key
2735
+	 *                                                 when finding "conflicts". If true, it's also considered).
2736
+	 *                                                 Only works for INT primary key,
2737
+	 *                                                 STRING primary keys cannot be ignored
2738
+	 * @throws EE_Error
2739
+	 * @return EE_Base_Class|array
2740
+	 */
2741
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2742
+	{
2743
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2744
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2745
+		} elseif (is_array($obj_or_fields_array)) {
2746
+			$fields_n_values = $obj_or_fields_array;
2747
+		} else {
2748
+			throw new EE_Error(
2749
+				sprintf(
2750
+					__(
2751
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2752
+						"event_espresso"
2753
+					),
2754
+					get_class($this),
2755
+					$obj_or_fields_array
2756
+				)
2757
+			);
2758
+		}
2759
+		$query_params = array();
2760
+		if ($this->has_primary_key_field()
2761
+			&& ($include_primary_key
2762
+				|| $this->get_primary_key_field()
2763
+				   instanceof
2764
+				   EE_Primary_Key_String_Field)
2765
+			&& isset($fields_n_values[$this->primary_key_name()])
2766
+		) {
2767
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2768
+		}
2769
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2770
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2771
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2772
+		}
2773
+		//if there is nothing to base this search on, then we shouldn't find anything
2774
+		if (empty($query_params)) {
2775
+			return array();
2776
+		} else {
2777
+			return $this->get_one($query_params);
2778
+		}
2779
+	}
2780
+
2781
+
2782
+
2783
+	/**
2784
+	 * Like count, but is optimized and returns a boolean instead of an int
2785
+	 *
2786
+	 * @param array $query_params
2787
+	 * @return boolean
2788
+	 * @throws EE_Error
2789
+	 */
2790
+	public function exists($query_params)
2791
+	{
2792
+		$query_params['limit'] = 1;
2793
+		return $this->count($query_params) > 0;
2794
+	}
2795
+
2796
+
2797
+
2798
+	/**
2799
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2800
+	 *
2801
+	 * @param int|string $id
2802
+	 * @return boolean
2803
+	 * @throws EE_Error
2804
+	 */
2805
+	public function exists_by_ID($id)
2806
+	{
2807
+		return $this->exists(
2808
+			array(
2809
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2810
+				array(
2811
+					$this->primary_key_name() => $id,
2812
+				),
2813
+			)
2814
+		);
2815
+	}
2816
+
2817
+
2818
+
2819
+	/**
2820
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2821
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2822
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2823
+	 * on the main table)
2824
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2825
+	 * cases where we want to call it directly rather than via insert().
2826
+	 *
2827
+	 * @access   protected
2828
+	 * @param EE_Table_Base $table
2829
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2830
+	 *                                       float
2831
+	 * @param int           $new_id          for now we assume only int keys
2832
+	 * @throws EE_Error
2833
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2834
+	 * @return int ID of new row inserted, or FALSE on failure
2835
+	 */
2836
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2837
+	{
2838
+		global $wpdb;
2839
+		$insertion_col_n_values = array();
2840
+		$format_for_insertion = array();
2841
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2842
+		foreach ($fields_on_table as $field_name => $field_obj) {
2843
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2844
+			if ($field_obj->is_auto_increment()) {
2845
+				continue;
2846
+			}
2847
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2848
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2849
+			if ($prepared_value !== null) {
2850
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2851
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2852
+			}
2853
+		}
2854
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2855
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2856
+			//so add the fk to the main table as a column
2857
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2858
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2859
+		}
2860
+		//insert the new entry
2861
+		$result = $this->_do_wpdb_query('insert',
2862
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2863
+		if ($result === false) {
2864
+			return false;
2865
+		}
2866
+		//ok, now what do we return for the ID of the newly-inserted thing?
2867
+		if ($this->has_primary_key_field()) {
2868
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2869
+				return $wpdb->insert_id;
2870
+			} else {
2871
+				//it's not an auto-increment primary key, so
2872
+				//it must have been supplied
2873
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2874
+			}
2875
+		} else {
2876
+			//we can't return a  primary key because there is none. instead return
2877
+			//a unique string indicating this model
2878
+			return $this->get_index_primary_key_string($fields_n_values);
2879
+		}
2880
+	}
2881
+
2882
+
2883
+
2884
+	/**
2885
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2886
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2887
+	 * and there is no default, we pass it along. WPDB will take care of it)
2888
+	 *
2889
+	 * @param EE_Model_Field_Base $field_obj
2890
+	 * @param array               $fields_n_values
2891
+	 * @return mixed string|int|float depending on what the table column will be expecting
2892
+	 * @throws EE_Error
2893
+	 */
2894
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2895
+	{
2896
+		//if this field doesn't allow nullable, don't allow it
2897
+		if (
2898
+			! $field_obj->is_nullable()
2899
+			&& (
2900
+				! isset($fields_n_values[$field_obj->get_name()])
2901
+				|| $fields_n_values[$field_obj->get_name()] === null
2902
+			)
2903
+		) {
2904
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2905
+		}
2906
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2907
+			? $fields_n_values[$field_obj->get_name()]
2908
+			: null;
2909
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2910
+	}
2911
+
2912
+
2913
+
2914
+	/**
2915
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2916
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2917
+	 * the field's prepare_for_set() method.
2918
+	 *
2919
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2920
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2921
+	 *                                   top of file)
2922
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2923
+	 *                                   $value is a custom selection
2924
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2925
+	 */
2926
+	private function _prepare_value_for_use_in_db($value, $field)
2927
+	{
2928
+		if ($field && $field instanceof EE_Model_Field_Base) {
2929
+			switch ($this->_values_already_prepared_by_model_object) {
2930
+				/** @noinspection PhpMissingBreakStatementInspection */
2931
+				case self::not_prepared_by_model_object:
2932
+					$value = $field->prepare_for_set($value);
2933
+				//purposefully left out "return"
2934
+				case self::prepared_by_model_object:
2935
+					$value = $field->prepare_for_use_in_db($value);
2936
+				case self::prepared_for_use_in_db:
2937
+					//leave the value alone
2938
+			}
2939
+			return $value;
2940
+		} else {
2941
+			return $value;
2942
+		}
2943
+	}
2944
+
2945
+
2946
+
2947
+	/**
2948
+	 * Returns the main table on this model
2949
+	 *
2950
+	 * @return EE_Primary_Table
2951
+	 * @throws EE_Error
2952
+	 */
2953
+	protected function _get_main_table()
2954
+	{
2955
+		foreach ($this->_tables as $table) {
2956
+			if ($table instanceof EE_Primary_Table) {
2957
+				return $table;
2958
+			}
2959
+		}
2960
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2961
+			'event_espresso'), get_class($this)));
2962
+	}
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 * table
2968
+	 * returns EE_Primary_Table table name
2969
+	 *
2970
+	 * @return string
2971
+	 * @throws EE_Error
2972
+	 */
2973
+	public function table()
2974
+	{
2975
+		return $this->_get_main_table()->get_table_name();
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * table
2982
+	 * returns first EE_Secondary_Table table name
2983
+	 *
2984
+	 * @return string
2985
+	 */
2986
+	public function second_table()
2987
+	{
2988
+		// grab second table from tables array
2989
+		$second_table = end($this->_tables);
2990
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2991
+	}
2992
+
2993
+
2994
+
2995
+	/**
2996
+	 * get_table_obj_by_alias
2997
+	 * returns table name given it's alias
2998
+	 *
2999
+	 * @param string $table_alias
3000
+	 * @return EE_Primary_Table | EE_Secondary_Table
3001
+	 */
3002
+	public function get_table_obj_by_alias($table_alias = '')
3003
+	{
3004
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3005
+	}
3006
+
3007
+
3008
+
3009
+	/**
3010
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3011
+	 *
3012
+	 * @return EE_Secondary_Table[]
3013
+	 */
3014
+	protected function _get_other_tables()
3015
+	{
3016
+		$other_tables = array();
3017
+		foreach ($this->_tables as $table_alias => $table) {
3018
+			if ($table instanceof EE_Secondary_Table) {
3019
+				$other_tables[$table_alias] = $table;
3020
+			}
3021
+		}
3022
+		return $other_tables;
3023
+	}
3024
+
3025
+
3026
+
3027
+	/**
3028
+	 * Finds all the fields that correspond to the given table
3029
+	 *
3030
+	 * @param string $table_alias , array key in EEM_Base::_tables
3031
+	 * @return EE_Model_Field_Base[]
3032
+	 */
3033
+	public function _get_fields_for_table($table_alias)
3034
+	{
3035
+		return $this->_fields[$table_alias];
3036
+	}
3037
+
3038
+
3039
+
3040
+	/**
3041
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3042
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3043
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3044
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3045
+	 * related Registration, Transaction, and Payment models.
3046
+	 *
3047
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3048
+	 * @return EE_Model_Query_Info_Carrier
3049
+	 * @throws EE_Error
3050
+	 */
3051
+	public function _extract_related_models_from_query($query_params)
3052
+	{
3053
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3054
+		if (array_key_exists(0, $query_params)) {
3055
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3056
+		}
3057
+		if (array_key_exists('group_by', $query_params)) {
3058
+			if (is_array($query_params['group_by'])) {
3059
+				$this->_extract_related_models_from_sub_params_array_values(
3060
+					$query_params['group_by'],
3061
+					$query_info_carrier,
3062
+					'group_by'
3063
+				);
3064
+			} elseif (! empty ($query_params['group_by'])) {
3065
+				$this->_extract_related_model_info_from_query_param(
3066
+					$query_params['group_by'],
3067
+					$query_info_carrier,
3068
+					'group_by'
3069
+				);
3070
+			}
3071
+		}
3072
+		if (array_key_exists('having', $query_params)) {
3073
+			$this->_extract_related_models_from_sub_params_array_keys(
3074
+				$query_params[0],
3075
+				$query_info_carrier,
3076
+				'having'
3077
+			);
3078
+		}
3079
+		if (array_key_exists('order_by', $query_params)) {
3080
+			if (is_array($query_params['order_by'])) {
3081
+				$this->_extract_related_models_from_sub_params_array_keys(
3082
+					$query_params['order_by'],
3083
+					$query_info_carrier,
3084
+					'order_by'
3085
+				);
3086
+			} elseif (! empty($query_params['order_by'])) {
3087
+				$this->_extract_related_model_info_from_query_param(
3088
+					$query_params['order_by'],
3089
+					$query_info_carrier,
3090
+					'order_by'
3091
+				);
3092
+			}
3093
+		}
3094
+		if (array_key_exists('force_join', $query_params)) {
3095
+			$this->_extract_related_models_from_sub_params_array_values(
3096
+				$query_params['force_join'],
3097
+				$query_info_carrier,
3098
+				'force_join'
3099
+			);
3100
+		}
3101
+		return $query_info_carrier;
3102
+	}
3103
+
3104
+
3105
+
3106
+	/**
3107
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3108
+	 *
3109
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3110
+	 *                                                      $query_params['having']
3111
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3112
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3113
+	 * @throws EE_Error
3114
+	 * @return \EE_Model_Query_Info_Carrier
3115
+	 */
3116
+	private function _extract_related_models_from_sub_params_array_keys(
3117
+		$sub_query_params,
3118
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3119
+		$query_param_type
3120
+	) {
3121
+		if (! empty($sub_query_params)) {
3122
+			$sub_query_params = (array)$sub_query_params;
3123
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3124
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3125
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3126
+					$query_param_type);
3127
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3128
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3129
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3130
+				//of array('Registration.TXN_ID'=>23)
3131
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3132
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3133
+					if (! is_array($possibly_array_of_params)) {
3134
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3135
+							"event_espresso"),
3136
+							$param, $possibly_array_of_params));
3137
+					} else {
3138
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3139
+							$model_query_info_carrier, $query_param_type);
3140
+					}
3141
+				} elseif ($query_param_type === 0 //ie WHERE
3142
+						  && is_array($possibly_array_of_params)
3143
+						  && isset($possibly_array_of_params[2])
3144
+						  && $possibly_array_of_params[2] == true
3145
+				) {
3146
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3147
+					//indicating that $possible_array_of_params[1] is actually a field name,
3148
+					//from which we should extract query parameters!
3149
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3150
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3151
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3152
+					}
3153
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3154
+						$model_query_info_carrier, $query_param_type);
3155
+				}
3156
+			}
3157
+		}
3158
+		return $model_query_info_carrier;
3159
+	}
3160
+
3161
+
3162
+
3163
+	/**
3164
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3165
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3166
+	 *
3167
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3168
+	 *                                                      $query_params['having']
3169
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3170
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3171
+	 * @throws EE_Error
3172
+	 * @return \EE_Model_Query_Info_Carrier
3173
+	 */
3174
+	private function _extract_related_models_from_sub_params_array_values(
3175
+		$sub_query_params,
3176
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3177
+		$query_param_type
3178
+	) {
3179
+		if (! empty($sub_query_params)) {
3180
+			if (! is_array($sub_query_params)) {
3181
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3182
+					$sub_query_params));
3183
+			}
3184
+			foreach ($sub_query_params as $param) {
3185
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3186
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3187
+					$query_param_type);
3188
+			}
3189
+		}
3190
+		return $model_query_info_carrier;
3191
+	}
3192
+
3193
+
3194
+
3195
+	/**
3196
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3197
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3198
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3199
+	 * but use them in a different order. Eg, we need to know what models we are querying
3200
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3201
+	 * other models before we can finalize the where clause SQL.
3202
+	 *
3203
+	 * @param array $query_params
3204
+	 * @throws EE_Error
3205
+	 * @return EE_Model_Query_Info_Carrier
3206
+	 */
3207
+	public function _create_model_query_info_carrier($query_params)
3208
+	{
3209
+		if (! is_array($query_params)) {
3210
+			EE_Error::doing_it_wrong(
3211
+				'EEM_Base::_create_model_query_info_carrier',
3212
+				sprintf(
3213
+					__(
3214
+						'$query_params should be an array, you passed a variable of type %s',
3215
+						'event_espresso'
3216
+					),
3217
+					gettype($query_params)
3218
+				),
3219
+				'4.6.0'
3220
+			);
3221
+			$query_params = array();
3222
+		}
3223
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3224
+		//first check if we should alter the query to account for caps or not
3225
+		//because the caps might require us to do extra joins
3226
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3227
+			$query_params[0] = $where_query_params = array_replace_recursive(
3228
+				$where_query_params,
3229
+				$this->caps_where_conditions(
3230
+					$query_params['caps']
3231
+				)
3232
+			);
3233
+		}
3234
+		$query_object = $this->_extract_related_models_from_query($query_params);
3235
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3236
+		foreach ($where_query_params as $key => $value) {
3237
+			if (is_int($key)) {
3238
+				throw new EE_Error(
3239
+					sprintf(
3240
+						__(
3241
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3242
+							"event_espresso"
3243
+						),
3244
+						$key,
3245
+						var_export($value, true),
3246
+						var_export($query_params, true),
3247
+						get_class($this)
3248
+					)
3249
+				);
3250
+			}
3251
+		}
3252
+		if (
3253
+			array_key_exists('default_where_conditions', $query_params)
3254
+			&& ! empty($query_params['default_where_conditions'])
3255
+		) {
3256
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3257
+		} else {
3258
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3259
+		}
3260
+		$where_query_params = array_merge(
3261
+			$this->_get_default_where_conditions_for_models_in_query(
3262
+				$query_object,
3263
+				$use_default_where_conditions,
3264
+				$where_query_params
3265
+			),
3266
+			$where_query_params
3267
+		);
3268
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3269
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3270
+		// So we need to setup a subquery and use that for the main join.
3271
+		// Note for now this only works on the primary table for the model.
3272
+		// So for instance, you could set the limit array like this:
3273
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3274
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3275
+			$query_object->set_main_model_join_sql(
3276
+				$this->_construct_limit_join_select(
3277
+					$query_params['on_join_limit'][0],
3278
+					$query_params['on_join_limit'][1]
3279
+				)
3280
+			);
3281
+		}
3282
+		//set limit
3283
+		if (array_key_exists('limit', $query_params)) {
3284
+			if (is_array($query_params['limit'])) {
3285
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3286
+					$e = sprintf(
3287
+						__(
3288
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3289
+							"event_espresso"
3290
+						),
3291
+						http_build_query($query_params['limit'])
3292
+					);
3293
+					throw new EE_Error($e . "|" . $e);
3294
+				}
3295
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3296
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3297
+			} elseif (! empty ($query_params['limit'])) {
3298
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3299
+			}
3300
+		}
3301
+		//set order by
3302
+		if (array_key_exists('order_by', $query_params)) {
3303
+			if (is_array($query_params['order_by'])) {
3304
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3305
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3306
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3307
+				if (array_key_exists('order', $query_params)) {
3308
+					throw new EE_Error(
3309
+						sprintf(
3310
+							__(
3311
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3312
+								"event_espresso"
3313
+							),
3314
+							get_class($this),
3315
+							implode(", ", array_keys($query_params['order_by'])),
3316
+							implode(", ", $query_params['order_by']),
3317
+							$query_params['order']
3318
+						)
3319
+					);
3320
+				}
3321
+				$this->_extract_related_models_from_sub_params_array_keys(
3322
+					$query_params['order_by'],
3323
+					$query_object,
3324
+					'order_by'
3325
+				);
3326
+				//assume it's an array of fields to order by
3327
+				$order_array = array();
3328
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3329
+					$order = $this->_extract_order($order);
3330
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3331
+				}
3332
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3333
+			} elseif (! empty ($query_params['order_by'])) {
3334
+				$this->_extract_related_model_info_from_query_param(
3335
+					$query_params['order_by'],
3336
+					$query_object,
3337
+					'order',
3338
+					$query_params['order_by']
3339
+				);
3340
+				$order = isset($query_params['order'])
3341
+					? $this->_extract_order($query_params['order'])
3342
+					: 'DESC';
3343
+				$query_object->set_order_by_sql(
3344
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3345
+				);
3346
+			}
3347
+		}
3348
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3349
+		if (! array_key_exists('order_by', $query_params)
3350
+			&& array_key_exists('order', $query_params)
3351
+			&& ! empty($query_params['order'])
3352
+		) {
3353
+			$pk_field = $this->get_primary_key_field();
3354
+			$order = $this->_extract_order($query_params['order']);
3355
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3356
+		}
3357
+		//set group by
3358
+		if (array_key_exists('group_by', $query_params)) {
3359
+			if (is_array($query_params['group_by'])) {
3360
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3361
+				$group_by_array = array();
3362
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3363
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3364
+				}
3365
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3366
+			} elseif (! empty ($query_params['group_by'])) {
3367
+				$query_object->set_group_by_sql(
3368
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3369
+				);
3370
+			}
3371
+		}
3372
+		//set having
3373
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3374
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3375
+		}
3376
+		//now, just verify they didn't pass anything wack
3377
+		foreach ($query_params as $query_key => $query_value) {
3378
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3379
+				throw new EE_Error(
3380
+					sprintf(
3381
+						__(
3382
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3383
+							'event_espresso'
3384
+						),
3385
+						$query_key,
3386
+						get_class($this),
3387
+						//						print_r( $this->_allowed_query_params, TRUE )
3388
+						implode(',', $this->_allowed_query_params)
3389
+					)
3390
+				);
3391
+			}
3392
+		}
3393
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3394
+		if (empty($main_model_join_sql)) {
3395
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3396
+		}
3397
+		return $query_object;
3398
+	}
3399
+
3400
+
3401
+
3402
+	/**
3403
+	 * Gets the where conditions that should be imposed on the query based on the
3404
+	 * context (eg reading frontend, backend, edit or delete).
3405
+	 *
3406
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3407
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3408
+	 * @throws EE_Error
3409
+	 */
3410
+	public function caps_where_conditions($context = self::caps_read)
3411
+	{
3412
+		EEM_Base::verify_is_valid_cap_context($context);
3413
+		$cap_where_conditions = array();
3414
+		$cap_restrictions = $this->caps_missing($context);
3415
+		/**
3416
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3417
+		 */
3418
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3419
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3420
+				$restriction_if_no_cap->get_default_where_conditions());
3421
+		}
3422
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3423
+			$cap_restrictions);
3424
+	}
3425
+
3426
+
3427
+
3428
+	/**
3429
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3430
+	 * otherwise throws an exception
3431
+	 *
3432
+	 * @param string $should_be_order_string
3433
+	 * @return string either ASC, asc, DESC or desc
3434
+	 * @throws EE_Error
3435
+	 */
3436
+	private function _extract_order($should_be_order_string)
3437
+	{
3438
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3439
+			return $should_be_order_string;
3440
+		} else {
3441
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3442
+				"event_espresso"), get_class($this), $should_be_order_string));
3443
+		}
3444
+	}
3445
+
3446
+
3447
+
3448
+	/**
3449
+	 * Looks at all the models which are included in this query, and asks each
3450
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3451
+	 * so they can be merged
3452
+	 *
3453
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3454
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3455
+	 *                                                                  'none' means NO default where conditions will
3456
+	 *                                                                  be used AT ALL during this query.
3457
+	 *                                                                  'other_models_only' means default where
3458
+	 *                                                                  conditions from other models will be used, but
3459
+	 *                                                                  not for this primary model. 'all', the default,
3460
+	 *                                                                  means default where conditions will apply as
3461
+	 *                                                                  normal
3462
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3463
+	 * @throws EE_Error
3464
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3465
+	 */
3466
+	private function _get_default_where_conditions_for_models_in_query(
3467
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3468
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3469
+		$where_query_params = array()
3470
+	) {
3471
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3472
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3473
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3474
+				"event_espresso"), $use_default_where_conditions,
3475
+				implode(", ", $allowed_used_default_where_conditions_values)));
3476
+		}
3477
+		$universal_query_params = array();
3478
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3479
+			$universal_query_params = $this->_get_default_where_conditions();
3480
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3481
+			$universal_query_params = $this->_get_minimum_where_conditions();
3482
+		}
3483
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3484
+			$related_model = $this->get_related_model_obj($model_name);
3485
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3486
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3487
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3488
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3489
+			} else {
3490
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3491
+				continue;
3492
+			}
3493
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3494
+				$related_model_universal_where_params,
3495
+				$where_query_params,
3496
+				$related_model,
3497
+				$model_relation_path
3498
+			);
3499
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3500
+				$universal_query_params,
3501
+				$overrides
3502
+			);
3503
+		}
3504
+		return $universal_query_params;
3505
+	}
3506
+
3507
+
3508
+
3509
+	/**
3510
+	 * Determines whether or not we should use default where conditions for the model in question
3511
+	 * (this model, or other related models).
3512
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3513
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3514
+	 * We should use default where conditions on related models when they requested to use default where conditions
3515
+	 * on all models, or specifically just on other related models
3516
+	 * @param      $default_where_conditions_value
3517
+	 * @param bool $for_this_model false means this is for OTHER related models
3518
+	 * @return bool
3519
+	 */
3520
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3521
+	{
3522
+		return (
3523
+				   $for_this_model
3524
+				   && in_array(
3525
+					   $default_where_conditions_value,
3526
+					   array(
3527
+						   EEM_Base::default_where_conditions_all,
3528
+						   EEM_Base::default_where_conditions_this_only,
3529
+						   EEM_Base::default_where_conditions_minimum_others,
3530
+					   ),
3531
+					   true
3532
+				   )
3533
+			   )
3534
+			   || (
3535
+				   ! $for_this_model
3536
+				   && in_array(
3537
+					   $default_where_conditions_value,
3538
+					   array(
3539
+						   EEM_Base::default_where_conditions_all,
3540
+						   EEM_Base::default_where_conditions_others_only,
3541
+					   ),
3542
+					   true
3543
+				   )
3544
+			   );
3545
+	}
3546
+
3547
+	/**
3548
+	 * Determines whether or not we should use default minimum conditions for the model in question
3549
+	 * (this model, or other related models).
3550
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3551
+	 * where conditions.
3552
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3553
+	 * on this model or others
3554
+	 * @param      $default_where_conditions_value
3555
+	 * @param bool $for_this_model false means this is for OTHER related models
3556
+	 * @return bool
3557
+	 */
3558
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3559
+	{
3560
+		return (
3561
+				   $for_this_model
3562
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3563
+			   )
3564
+			   || (
3565
+				   ! $for_this_model
3566
+				   && in_array(
3567
+					   $default_where_conditions_value,
3568
+					   array(
3569
+						   EEM_Base::default_where_conditions_minimum_others,
3570
+						   EEM_Base::default_where_conditions_minimum_all,
3571
+					   ),
3572
+					   true
3573
+				   )
3574
+			   );
3575
+	}
3576
+
3577
+
3578
+	/**
3579
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3580
+	 * then we also add a special where condition which allows for that model's primary key
3581
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3582
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3583
+	 *
3584
+	 * @param array    $default_where_conditions
3585
+	 * @param array    $provided_where_conditions
3586
+	 * @param EEM_Base $model
3587
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3588
+	 * @return array like EEM_Base::get_all's $query_params[0]
3589
+	 * @throws EE_Error
3590
+	 */
3591
+	private function _override_defaults_or_make_null_friendly(
3592
+		$default_where_conditions,
3593
+		$provided_where_conditions,
3594
+		$model,
3595
+		$model_relation_path
3596
+	) {
3597
+		$null_friendly_where_conditions = array();
3598
+		$none_overridden = true;
3599
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3600
+		foreach ($default_where_conditions as $key => $val) {
3601
+			if (isset($provided_where_conditions[$key])) {
3602
+				$none_overridden = false;
3603
+			} else {
3604
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3605
+			}
3606
+		}
3607
+		if ($none_overridden && $default_where_conditions) {
3608
+			if ($model->has_primary_key_field()) {
3609
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3610
+																				. "."
3611
+																				. $model->primary_key_name()] = array('IS NULL');
3612
+			}/*else{
3613 3613
 				//@todo NO PK, use other defaults
3614 3614
 			}*/
3615
-        }
3616
-        return $null_friendly_where_conditions;
3617
-    }
3618
-
3619
-
3620
-
3621
-    /**
3622
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3623
-     * default where conditions on all get_all, update, and delete queries done by this model.
3624
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3625
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3626
-     *
3627
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3628
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3629
-     */
3630
-    private function _get_default_where_conditions($model_relation_path = null)
3631
-    {
3632
-        if ($this->_ignore_where_strategy) {
3633
-            return array();
3634
-        }
3635
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3636
-    }
3637
-
3638
-
3639
-
3640
-    /**
3641
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3642
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3643
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3644
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3645
-     * Similar to _get_default_where_conditions
3646
-     *
3647
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3648
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3649
-     */
3650
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3651
-    {
3652
-        if ($this->_ignore_where_strategy) {
3653
-            return array();
3654
-        }
3655
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3656
-    }
3657
-
3658
-
3659
-
3660
-    /**
3661
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3662
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3663
-     *
3664
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3665
-     * @return string
3666
-     * @throws EE_Error
3667
-     */
3668
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3669
-    {
3670
-        $selects = $this->_get_columns_to_select_for_this_model();
3671
-        foreach (
3672
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3673
-            $name_of_other_model_included
3674
-        ) {
3675
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3676
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3677
-            foreach ($other_model_selects as $key => $value) {
3678
-                $selects[] = $value;
3679
-            }
3680
-        }
3681
-        return implode(", ", $selects);
3682
-    }
3683
-
3684
-
3685
-
3686
-    /**
3687
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3688
-     * So that's going to be the columns for all the fields on the model
3689
-     *
3690
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3691
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3692
-     */
3693
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3694
-    {
3695
-        $fields = $this->field_settings();
3696
-        $selects = array();
3697
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3698
-            $this->get_this_model_name());
3699
-        foreach ($fields as $field_obj) {
3700
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3701
-                         . $field_obj->get_table_alias()
3702
-                         . "."
3703
-                         . $field_obj->get_table_column()
3704
-                         . " AS '"
3705
-                         . $table_alias_with_model_relation_chain_prefix
3706
-                         . $field_obj->get_table_alias()
3707
-                         . "."
3708
-                         . $field_obj->get_table_column()
3709
-                         . "'";
3710
-        }
3711
-        //make sure we are also getting the PKs of each table
3712
-        $tables = $this->get_tables();
3713
-        if (count($tables) > 1) {
3714
-            foreach ($tables as $table_obj) {
3715
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3716
-                                       . $table_obj->get_fully_qualified_pk_column();
3717
-                if (! in_array($qualified_pk_column, $selects)) {
3718
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3719
-                }
3720
-            }
3721
-        }
3722
-        return $selects;
3723
-    }
3724
-
3725
-
3726
-
3727
-    /**
3728
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3729
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3730
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3731
-     * SQL for joining, and the data types
3732
-     *
3733
-     * @param null|string                 $original_query_param
3734
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3735
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3736
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3737
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3738
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3739
-     *                                                          or 'Registration's
3740
-     * @param string                      $original_query_param what it originally was (eg
3741
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3742
-     *                                                          matches $query_param
3743
-     * @throws EE_Error
3744
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3745
-     */
3746
-    private function _extract_related_model_info_from_query_param(
3747
-        $query_param,
3748
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3749
-        $query_param_type,
3750
-        $original_query_param = null
3751
-    ) {
3752
-        if ($original_query_param === null) {
3753
-            $original_query_param = $query_param;
3754
-        }
3755
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3756
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3757
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3758
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3759
-        //check to see if we have a field on this model
3760
-        $this_model_fields = $this->field_settings(true);
3761
-        if (array_key_exists($query_param, $this_model_fields)) {
3762
-            if ($allow_fields) {
3763
-                return;
3764
-            } else {
3765
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3766
-                    "event_espresso"),
3767
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3768
-            }
3769
-        } //check if this is a special logic query param
3770
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3771
-            if ($allow_logic_query_params) {
3772
-                return;
3773
-            } else {
3774
-                throw new EE_Error(
3775
-                    sprintf(
3776
-                        __('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3777
-                            'event_espresso'),
3778
-                        implode('", "', $this->_logic_query_param_keys),
3779
-                        $query_param,
3780
-                        get_class($this),
3781
-                        '<br />',
3782
-                        "\t"
3783
-                        . ' $passed_in_query_info = <pre>'
3784
-                        . print_r($passed_in_query_info, true)
3785
-                        . '</pre>'
3786
-                        . "\n\t"
3787
-                        . ' $query_param_type = '
3788
-                        . $query_param_type
3789
-                        . "\n\t"
3790
-                        . ' $original_query_param = '
3791
-                        . $original_query_param
3792
-                    )
3793
-                );
3794
-            }
3795
-        } //check if it's a custom selection
3796
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3797
-            return;
3798
-        }
3799
-        //check if has a model name at the beginning
3800
-        //and
3801
-        //check if it's a field on a related model
3802
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3803
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3804
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3805
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3806
-                if ($query_param === '') {
3807
-                    //nothing left to $query_param
3808
-                    //we should actually end in a field name, not a model like this!
3809
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3810
-                        "event_espresso"),
3811
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3812
-                } else {
3813
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3814
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3815
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3816
-                    return;
3817
-                }
3818
-            } elseif ($query_param === $valid_related_model_name) {
3819
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3820
-                return;
3821
-            }
3822
-        }
3823
-        //ok so $query_param didn't start with a model name
3824
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3825
-        //it's wack, that's what it is
3826
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3827
-            "event_espresso"),
3828
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3829
-    }
3830
-
3831
-
3832
-
3833
-    /**
3834
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3835
-     * and store it on $passed_in_query_info
3836
-     *
3837
-     * @param string                      $model_name
3838
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3839
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3840
-     *                                                          model and $model_name. Eg, if we are querying Event,
3841
-     *                                                          and are adding a join to 'Payment' with the original
3842
-     *                                                          query param key
3843
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3844
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3845
-     *                                                          Payment wants to add default query params so that it
3846
-     *                                                          will know what models to prepend onto its default query
3847
-     *                                                          params or in case it wants to rename tables (in case
3848
-     *                                                          there are multiple joins to the same table)
3849
-     * @return void
3850
-     * @throws EE_Error
3851
-     */
3852
-    private function _add_join_to_model(
3853
-        $model_name,
3854
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3855
-        $original_query_param
3856
-    ) {
3857
-        $relation_obj = $this->related_settings_for($model_name);
3858
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3859
-        //check if the relation is HABTM, because then we're essentially doing two joins
3860
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3861
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3862
-            $join_model_obj = $relation_obj->get_join_model();
3863
-            //replace the model specified with the join model for this relation chain, whi
3864
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3865
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3866
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3867
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3868
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3869
-            $passed_in_query_info->merge($new_query_info);
3870
-        }
3871
-        //now just join to the other table pointed to by the relation object, and add its data types
3872
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3873
-            array($model_relation_chain => $model_name),
3874
-            $relation_obj->get_join_statement($model_relation_chain));
3875
-        $passed_in_query_info->merge($new_query_info);
3876
-    }
3877
-
3878
-
3879
-
3880
-    /**
3881
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3882
-     *
3883
-     * @param array $where_params like EEM_Base::get_all
3884
-     * @return string of SQL
3885
-     * @throws EE_Error
3886
-     */
3887
-    private function _construct_where_clause($where_params)
3888
-    {
3889
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3890
-        if ($SQL) {
3891
-            return " WHERE " . $SQL;
3892
-        } else {
3893
-            return '';
3894
-        }
3895
-    }
3896
-
3897
-
3898
-
3899
-    /**
3900
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3901
-     * and should be passed HAVING parameters, not WHERE parameters
3902
-     *
3903
-     * @param array $having_params
3904
-     * @return string
3905
-     * @throws EE_Error
3906
-     */
3907
-    private function _construct_having_clause($having_params)
3908
-    {
3909
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3910
-        if ($SQL) {
3911
-            return " HAVING " . $SQL;
3912
-        } else {
3913
-            return '';
3914
-        }
3915
-    }
3916
-
3917
-
3918
-
3919
-    /**
3920
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3921
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3922
-     * EEM_Attendee.
3923
-     *
3924
-     * @param string $field_name
3925
-     * @param string $model_name
3926
-     * @return EE_Model_Field_Base
3927
-     * @throws EE_Error
3928
-     */
3929
-    protected function _get_field_on_model($field_name, $model_name)
3930
-    {
3931
-        $model_class = 'EEM_' . $model_name;
3932
-        $model_filepath = $model_class . ".model.php";
3933
-        if (is_readable($model_filepath)) {
3934
-            require_once($model_filepath);
3935
-            $model_instance = call_user_func($model_name . "::instance");
3936
-            /* @var $model_instance EEM_Base */
3937
-            return $model_instance->field_settings_for($field_name);
3938
-        } else {
3939
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3940
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3941
-        }
3942
-    }
3943
-
3944
-
3945
-
3946
-    /**
3947
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3948
-     * Event_Meta.meta_value = 'foo'))"
3949
-     *
3950
-     * @param array  $where_params see EEM_Base::get_all for documentation
3951
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3952
-     * @throws EE_Error
3953
-     * @return string of SQL
3954
-     */
3955
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3956
-    {
3957
-        $where_clauses = array();
3958
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3959
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3960
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3961
-                switch ($query_param) {
3962
-                    case 'not':
3963
-                    case 'NOT':
3964
-                        $where_clauses[] = "! ("
3965
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3966
-                                $glue)
3967
-                                           . ")";
3968
-                        break;
3969
-                    case 'and':
3970
-                    case 'AND':
3971
-                        $where_clauses[] = " ("
3972
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3973
-                                ' AND ')
3974
-                                           . ")";
3975
-                        break;
3976
-                    case 'or':
3977
-                    case 'OR':
3978
-                        $where_clauses[] = " ("
3979
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3980
-                                ' OR ')
3981
-                                           . ")";
3982
-                        break;
3983
-                }
3984
-            } else {
3985
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3986
-                //if it's not a normal field, maybe it's a custom selection?
3987
-                if (! $field_obj) {
3988
-                    if (isset($this->_custom_selections[$query_param][1])) {
3989
-                        $field_obj = $this->_custom_selections[$query_param][1];
3990
-                    } else {
3991
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3992
-                            "event_espresso"), $query_param));
3993
-                    }
3994
-                }
3995
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3996
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3997
-            }
3998
-        }
3999
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4000
-    }
4001
-
4002
-
4003
-
4004
-    /**
4005
-     * Takes the input parameter and extract the table name (alias) and column name
4006
-     *
4007
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4008
-     * @throws EE_Error
4009
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4010
-     */
4011
-    private function _deduce_column_name_from_query_param($query_param)
4012
-    {
4013
-        $field = $this->_deduce_field_from_query_param($query_param);
4014
-        if ($field) {
4015
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4016
-                $query_param);
4017
-            return $table_alias_prefix . $field->get_qualified_column();
4018
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4019
-            //maybe it's custom selection item?
4020
-            //if so, just use it as the "column name"
4021
-            return $query_param;
4022
-        } else {
4023
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4024
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4025
-        }
4026
-    }
4027
-
4028
-
4029
-
4030
-    /**
4031
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4032
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4033
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4034
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4035
-     *
4036
-     * @param string $condition_query_param_key
4037
-     * @return string
4038
-     */
4039
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4040
-    {
4041
-        $pos_of_star = strpos($condition_query_param_key, '*');
4042
-        if ($pos_of_star === false) {
4043
-            return $condition_query_param_key;
4044
-        } else {
4045
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4046
-            return $condition_query_param_sans_star;
4047
-        }
4048
-    }
4049
-
4050
-
4051
-
4052
-    /**
4053
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4054
-     *
4055
-     * @param                            mixed      array | string    $op_and_value
4056
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4057
-     * @throws EE_Error
4058
-     * @return string
4059
-     */
4060
-    private function _construct_op_and_value($op_and_value, $field_obj)
4061
-    {
4062
-        if (is_array($op_and_value)) {
4063
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4064
-            if (! $operator) {
4065
-                $php_array_like_string = array();
4066
-                foreach ($op_and_value as $key => $value) {
4067
-                    $php_array_like_string[] = "$key=>$value";
4068
-                }
4069
-                throw new EE_Error(
4070
-                    sprintf(
4071
-                        __(
4072
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4073
-                            "event_espresso"
4074
-                        ),
4075
-                        implode(",", $php_array_like_string)
4076
-                    )
4077
-                );
4078
-            }
4079
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4080
-        } else {
4081
-            $operator = '=';
4082
-            $value = $op_and_value;
4083
-        }
4084
-        //check to see if the value is actually another field
4085
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4086
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4087
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4088
-            //in this case, the value should be an array, or at least a comma-separated list
4089
-            //it will need to handle a little differently
4090
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4091
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4092
-            return $operator . SP . $cleaned_value;
4093
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4094
-            //the value should be an array with count of two.
4095
-            if (count($value) !== 2) {
4096
-                throw new EE_Error(
4097
-                    sprintf(
4098
-                        __(
4099
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4100
-                            'event_espresso'
4101
-                        ),
4102
-                        "BETWEEN"
4103
-                    )
4104
-                );
4105
-            }
4106
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4107
-            return $operator . SP . $cleaned_value;
4108
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4109
-            if ($value !== null) {
4110
-                throw new EE_Error(
4111
-                    sprintf(
4112
-                        __(
4113
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4114
-                            "event_espresso"
4115
-                        ),
4116
-                        $value,
4117
-                        $operator
4118
-                    )
4119
-                );
4120
-            }
4121
-            return $operator;
4122
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4123
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4124
-            //remove other junk. So just treat it as a string.
4125
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4126
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4128
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4129
-            throw new EE_Error(
4130
-                sprintf(
4131
-                    __(
4132
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4133
-                        'event_espresso'
4134
-                    ),
4135
-                    $operator,
4136
-                    $operator
4137
-                )
4138
-            );
4139
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4140
-            throw new EE_Error(
4141
-                sprintf(
4142
-                    __(
4143
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4144
-                        'event_espresso'
4145
-                    ),
4146
-                    $operator,
4147
-                    $operator
4148
-                )
4149
-            );
4150
-        } else {
4151
-            throw new EE_Error(
4152
-                sprintf(
4153
-                    __(
4154
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4155
-                        "event_espresso"
4156
-                    ),
4157
-                    http_build_query($op_and_value)
4158
-                )
4159
-            );
4160
-        }
4161
-    }
4162
-
4163
-
4164
-
4165
-    /**
4166
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4167
-     *
4168
-     * @param array                      $values
4169
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4170
-     *                                              '%s'
4171
-     * @return string
4172
-     * @throws EE_Error
4173
-     */
4174
-    public function _construct_between_value($values, $field_obj)
4175
-    {
4176
-        $cleaned_values = array();
4177
-        foreach ($values as $value) {
4178
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4179
-        }
4180
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Takes an array or a comma-separated list of $values and cleans them
4187
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4188
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4189
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4190
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4191
-     *
4192
-     * @param mixed                      $values    array or comma-separated string
4193
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4194
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4195
-     * @throws EE_Error
4196
-     */
4197
-    public function _construct_in_value($values, $field_obj)
4198
-    {
4199
-        //check if the value is a CSV list
4200
-        if (is_string($values)) {
4201
-            //in which case, turn it into an array
4202
-            $values = explode(",", $values);
4203
-        }
4204
-        $cleaned_values = array();
4205
-        foreach ($values as $value) {
4206
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4207
-        }
4208
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4209
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4210
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4211
-        if (empty($cleaned_values)) {
4212
-            $all_fields = $this->field_settings();
4213
-            $a_field = array_shift($all_fields);
4214
-            $main_table = $this->_get_main_table();
4215
-            $cleaned_values[] = "SELECT "
4216
-                                . $a_field->get_table_column()
4217
-                                . " FROM "
4218
-                                . $main_table->get_table_name()
4219
-                                . " WHERE FALSE";
4220
-        }
4221
-        return "(" . implode(",", $cleaned_values) . ")";
4222
-    }
4223
-
4224
-
4225
-
4226
-    /**
4227
-     * @param mixed                      $value
4228
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4229
-     * @throws EE_Error
4230
-     * @return false|null|string
4231
-     */
4232
-    private function _wpdb_prepare_using_field($value, $field_obj)
4233
-    {
4234
-        /** @type WPDB $wpdb */
4235
-        global $wpdb;
4236
-        if ($field_obj instanceof EE_Model_Field_Base) {
4237
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4238
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4239
-        } else {//$field_obj should really just be a data type
4240
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4241
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4242
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4243
-            }
4244
-            return $wpdb->prepare($field_obj, $value);
4245
-        }
4246
-    }
4247
-
4248
-
4249
-
4250
-    /**
4251
-     * Takes the input parameter and finds the model field that it indicates.
4252
-     *
4253
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4254
-     * @throws EE_Error
4255
-     * @return EE_Model_Field_Base
4256
-     */
4257
-    protected function _deduce_field_from_query_param($query_param_name)
4258
-    {
4259
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4260
-        //which will help us find the database table and column
4261
-        $query_param_parts = explode(".", $query_param_name);
4262
-        if (empty($query_param_parts)) {
4263
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4264
-                'event_espresso'), $query_param_name));
4265
-        }
4266
-        $number_of_parts = count($query_param_parts);
4267
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4268
-        if ($number_of_parts === 1) {
4269
-            $field_name = $last_query_param_part;
4270
-            $model_obj = $this;
4271
-        } else {// $number_of_parts >= 2
4272
-            //the last part is the column name, and there are only 2parts. therefore...
4273
-            $field_name = $last_query_param_part;
4274
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4275
-        }
4276
-        try {
4277
-            return $model_obj->field_settings_for($field_name);
4278
-        } catch (EE_Error $e) {
4279
-            return null;
4280
-        }
4281
-    }
4282
-
4283
-
4284
-
4285
-    /**
4286
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4287
-     * alias and column which corresponds to it
4288
-     *
4289
-     * @param string $field_name
4290
-     * @throws EE_Error
4291
-     * @return string
4292
-     */
4293
-    public function _get_qualified_column_for_field($field_name)
4294
-    {
4295
-        $all_fields = $this->field_settings();
4296
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4297
-        if ($field) {
4298
-            return $field->get_qualified_column();
4299
-        } else {
4300
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4301
-                'event_espresso'), $field_name, get_class($this)));
4302
-        }
4303
-    }
4304
-
4305
-
4306
-
4307
-    /**
4308
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4309
-     * Example usage:
4310
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4311
-     *      array(),
4312
-     *      ARRAY_A,
4313
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4314
-     *  );
4315
-     * is equivalent to
4316
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4317
-     * and
4318
-     *  EEM_Event::instance()->get_all_wpdb_results(
4319
-     *      array(
4320
-     *          array(
4321
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4322
-     *          ),
4323
-     *          ARRAY_A,
4324
-     *          implode(
4325
-     *              ', ',
4326
-     *              array_merge(
4327
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4328
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4329
-     *              )
4330
-     *          )
4331
-     *      )
4332
-     *  );
4333
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4334
-     *
4335
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4336
-     *                                            and the one whose fields you are selecting for example: when querying
4337
-     *                                            tickets model and selecting fields from the tickets model you would
4338
-     *                                            leave this parameter empty, because no models are needed to join
4339
-     *                                            between the queried model and the selected one. Likewise when
4340
-     *                                            querying the datetime model and selecting fields from the tickets
4341
-     *                                            model, it would also be left empty, because there is a direct
4342
-     *                                            relation from datetimes to tickets, so no model is needed to join
4343
-     *                                            them together. However, when querying from the event model and
4344
-     *                                            selecting fields from the ticket model, you should provide the string
4345
-     *                                            'Datetime', indicating that the event model must first join to the
4346
-     *                                            datetime model in order to find its relation to ticket model.
4347
-     *                                            Also, when querying from the venue model and selecting fields from
4348
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4349
-     *                                            indicating you need to join the venue model to the event model,
4350
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4351
-     *                                            This string is used to deduce the prefix that gets added onto the
4352
-     *                                            models' tables qualified columns
4353
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4354
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4355
-     *                                            qualified column names
4356
-     * @return array|string
4357
-     */
4358
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4359
-    {
4360
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4361
-        $qualified_columns = array();
4362
-        foreach ($this->field_settings() as $field_name => $field) {
4363
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4364
-        }
4365
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4366
-    }
4367
-
4368
-
4369
-
4370
-    /**
4371
-     * constructs the select use on special limit joins
4372
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4373
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4374
-     * (as that is typically where the limits would be set).
4375
-     *
4376
-     * @param  string       $table_alias The table the select is being built for
4377
-     * @param  mixed|string $limit       The limit for this select
4378
-     * @return string                The final select join element for the query.
4379
-     */
4380
-    public function _construct_limit_join_select($table_alias, $limit)
4381
-    {
4382
-        $SQL = '';
4383
-        foreach ($this->_tables as $table_obj) {
4384
-            if ($table_obj instanceof EE_Primary_Table) {
4385
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4386
-                    ? $table_obj->get_select_join_limit($limit)
4387
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4388
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4389
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4390
-                    ? $table_obj->get_select_join_limit_join($limit)
4391
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4392
-            }
4393
-        }
4394
-        return $SQL;
4395
-    }
4396
-
4397
-
4398
-
4399
-    /**
4400
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4401
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4402
-     *
4403
-     * @return string SQL
4404
-     * @throws EE_Error
4405
-     */
4406
-    public function _construct_internal_join()
4407
-    {
4408
-        $SQL = $this->_get_main_table()->get_table_sql();
4409
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4410
-        return $SQL;
4411
-    }
4412
-
4413
-
4414
-
4415
-    /**
4416
-     * Constructs the SQL for joining all the tables on this model.
4417
-     * Normally $alias should be the primary table's alias, but in cases where
4418
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4419
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4420
-     * alias, this will construct SQL like:
4421
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
-     * With $alias being a secondary table's alias, this will construct SQL like:
4423
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
-     *
4425
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4426
-     * @return string
4427
-     */
4428
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4429
-    {
4430
-        $SQL = '';
4431
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4432
-        foreach ($this->_tables as $table_obj) {
4433
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4434
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4435
-                    //so we're joining to this table, meaning the table is already in
4436
-                    //the FROM statement, BUT the primary table isn't. So we want
4437
-                    //to add the inverse join sql
4438
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4439
-                } else {
4440
-                    //just add a regular JOIN to this table from the primary table
4441
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4442
-                }
4443
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4444
-        }
4445
-        return $SQL;
4446
-    }
4447
-
4448
-
4449
-
4450
-    /**
4451
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4452
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4453
-     * their data type (eg, '%s', '%d', etc)
4454
-     *
4455
-     * @return array
4456
-     */
4457
-    public function _get_data_types()
4458
-    {
4459
-        $data_types = array();
4460
-        foreach ($this->field_settings() as $field_obj) {
4461
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4462
-            /** @var $field_obj EE_Model_Field_Base */
4463
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4464
-        }
4465
-        return $data_types;
4466
-    }
4467
-
4468
-
4469
-
4470
-    /**
4471
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4472
-     *
4473
-     * @param string $model_name
4474
-     * @throws EE_Error
4475
-     * @return EEM_Base
4476
-     */
4477
-    public function get_related_model_obj($model_name)
4478
-    {
4479
-        $model_classname = "EEM_" . $model_name;
4480
-        if (! class_exists($model_classname)) {
4481
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4482
-                'event_espresso'), $model_name, $model_classname));
4483
-        }
4484
-        return call_user_func($model_classname . "::instance");
4485
-    }
4486
-
4487
-
4488
-
4489
-    /**
4490
-     * Returns the array of EE_ModelRelations for this model.
4491
-     *
4492
-     * @return EE_Model_Relation_Base[]
4493
-     */
4494
-    public function relation_settings()
4495
-    {
4496
-        return $this->_model_relations;
4497
-    }
4498
-
4499
-
4500
-
4501
-    /**
4502
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4503
-     * because without THOSE models, this model probably doesn't have much purpose.
4504
-     * (Eg, without an event, datetimes have little purpose.)
4505
-     *
4506
-     * @return EE_Belongs_To_Relation[]
4507
-     */
4508
-    public function belongs_to_relations()
4509
-    {
4510
-        $belongs_to_relations = array();
4511
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4512
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4513
-                $belongs_to_relations[$model_name] = $relation_obj;
4514
-            }
4515
-        }
4516
-        return $belongs_to_relations;
4517
-    }
4518
-
4519
-
4520
-
4521
-    /**
4522
-     * Returns the specified EE_Model_Relation, or throws an exception
4523
-     *
4524
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4525
-     * @throws EE_Error
4526
-     * @return EE_Model_Relation_Base
4527
-     */
4528
-    public function related_settings_for($relation_name)
4529
-    {
4530
-        $relatedModels = $this->relation_settings();
4531
-        if (! array_key_exists($relation_name, $relatedModels)) {
4532
-            throw new EE_Error(
4533
-                sprintf(
4534
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4535
-                        'event_espresso'),
4536
-                    $relation_name,
4537
-                    $this->_get_class_name(),
4538
-                    implode(', ', array_keys($relatedModels))
4539
-                )
4540
-            );
4541
-        }
4542
-        return $relatedModels[$relation_name];
4543
-    }
4544
-
4545
-
4546
-
4547
-    /**
4548
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4549
-     * fields
4550
-     *
4551
-     * @param string $fieldName
4552
-     * @throws EE_Error
4553
-     * @return EE_Model_Field_Base
4554
-     */
4555
-    public function field_settings_for($fieldName)
4556
-    {
4557
-        $fieldSettings = $this->field_settings(true);
4558
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4559
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4560
-                get_class($this)));
4561
-        }
4562
-        return $fieldSettings[$fieldName];
4563
-    }
4564
-
4565
-
4566
-
4567
-    /**
4568
-     * Checks if this field exists on this model
4569
-     *
4570
-     * @param string $fieldName a key in the model's _field_settings array
4571
-     * @return boolean
4572
-     */
4573
-    public function has_field($fieldName)
4574
-    {
4575
-        $fieldSettings = $this->field_settings(true);
4576
-        if (isset($fieldSettings[$fieldName])) {
4577
-            return true;
4578
-        } else {
4579
-            return false;
4580
-        }
4581
-    }
4582
-
4583
-
4584
-
4585
-    /**
4586
-     * Returns whether or not this model has a relation to the specified model
4587
-     *
4588
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4589
-     * @return boolean
4590
-     */
4591
-    public function has_relation($relation_name)
4592
-    {
4593
-        $relations = $this->relation_settings();
4594
-        if (isset($relations[$relation_name])) {
4595
-            return true;
4596
-        } else {
4597
-            return false;
4598
-        }
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4605
-     * Eg, on EE_Answer that would be ANS_ID field object
4606
-     *
4607
-     * @param $field_obj
4608
-     * @return boolean
4609
-     */
4610
-    public function is_primary_key_field($field_obj)
4611
-    {
4612
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4613
-    }
4614
-
4615
-
4616
-
4617
-    /**
4618
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4619
-     * Eg, on EE_Answer that would be ANS_ID field object
4620
-     *
4621
-     * @return EE_Model_Field_Base
4622
-     * @throws EE_Error
4623
-     */
4624
-    public function get_primary_key_field()
4625
-    {
4626
-        if ($this->_primary_key_field === null) {
4627
-            foreach ($this->field_settings(true) as $field_obj) {
4628
-                if ($this->is_primary_key_field($field_obj)) {
4629
-                    $this->_primary_key_field = $field_obj;
4630
-                    break;
4631
-                }
4632
-            }
4633
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4634
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4635
-                    get_class($this)));
4636
-            }
4637
-        }
4638
-        return $this->_primary_key_field;
4639
-    }
4640
-
4641
-
4642
-
4643
-    /**
4644
-     * Returns whether or not not there is a primary key on this model.
4645
-     * Internally does some caching.
4646
-     *
4647
-     * @return boolean
4648
-     */
4649
-    public function has_primary_key_field()
4650
-    {
4651
-        if ($this->_has_primary_key_field === null) {
4652
-            try {
4653
-                $this->get_primary_key_field();
4654
-                $this->_has_primary_key_field = true;
4655
-            } catch (EE_Error $e) {
4656
-                $this->_has_primary_key_field = false;
4657
-            }
4658
-        }
4659
-        return $this->_has_primary_key_field;
4660
-    }
4661
-
4662
-
4663
-
4664
-    /**
4665
-     * Finds the first field of type $field_class_name.
4666
-     *
4667
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4668
-     *                                 EE_Foreign_Key_Field, etc
4669
-     * @return EE_Model_Field_Base or null if none is found
4670
-     */
4671
-    public function get_a_field_of_type($field_class_name)
4672
-    {
4673
-        foreach ($this->field_settings() as $field) {
4674
-            if ($field instanceof $field_class_name) {
4675
-                return $field;
4676
-            }
4677
-        }
4678
-        return null;
4679
-    }
4680
-
4681
-
4682
-
4683
-    /**
4684
-     * Gets a foreign key field pointing to model.
4685
-     *
4686
-     * @param string $model_name eg Event, Registration, not EEM_Event
4687
-     * @return EE_Foreign_Key_Field_Base
4688
-     * @throws EE_Error
4689
-     */
4690
-    public function get_foreign_key_to($model_name)
4691
-    {
4692
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
-            foreach ($this->field_settings() as $field) {
4694
-                if (
4695
-                    $field instanceof EE_Foreign_Key_Field_Base
4696
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4697
-                ) {
4698
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4699
-                    break;
4700
-                }
4701
-            }
4702
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4703
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4704
-                    'event_espresso'), $model_name, get_class($this)));
4705
-            }
4706
-        }
4707
-        return $this->_cache_foreign_key_to_fields[$model_name];
4708
-    }
4709
-
4710
-
4711
-
4712
-    /**
4713
-     * Gets the table name (including $wpdb->prefix) for the table alias
4714
-     *
4715
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4716
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4717
-     *                            Either one works
4718
-     * @return string
4719
-     */
4720
-    public function get_table_for_alias($table_alias)
4721
-    {
4722
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4723
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4724
-    }
4725
-
4726
-
4727
-
4728
-    /**
4729
-     * Returns a flat array of all field son this model, instead of organizing them
4730
-     * by table_alias as they are in the constructor.
4731
-     *
4732
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4733
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4734
-     */
4735
-    public function field_settings($include_db_only_fields = false)
4736
-    {
4737
-        if ($include_db_only_fields) {
4738
-            if ($this->_cached_fields === null) {
4739
-                $this->_cached_fields = array();
4740
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4741
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
-                        $this->_cached_fields[$field_name] = $field_obj;
4743
-                    }
4744
-                }
4745
-            }
4746
-            return $this->_cached_fields;
4747
-        } else {
4748
-            if ($this->_cached_fields_non_db_only === null) {
4749
-                $this->_cached_fields_non_db_only = array();
4750
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4751
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4752
-                        /** @var $field_obj EE_Model_Field_Base */
4753
-                        if (! $field_obj->is_db_only_field()) {
4754
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4755
-                        }
4756
-                    }
4757
-                }
4758
-            }
4759
-            return $this->_cached_fields_non_db_only;
4760
-        }
4761
-    }
4762
-
4763
-
4764
-
4765
-    /**
4766
-     *        cycle though array of attendees and create objects out of each item
4767
-     *
4768
-     * @access        private
4769
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4770
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4771
-     *                           numerically indexed)
4772
-     * @throws EE_Error
4773
-     */
4774
-    protected function _create_objects($rows = array())
4775
-    {
4776
-        $array_of_objects = array();
4777
-        if (empty($rows)) {
4778
-            return array();
4779
-        }
4780
-        $count_if_model_has_no_primary_key = 0;
4781
-        $has_primary_key = $this->has_primary_key_field();
4782
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4783
-        foreach ((array)$rows as $row) {
4784
-            if (empty($row)) {
4785
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4786
-                return array();
4787
-            }
4788
-            //check if we've already set this object in the results array,
4789
-            //in which case there's no need to process it further (again)
4790
-            if ($has_primary_key) {
4791
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4792
-                    $row,
4793
-                    $primary_key_field->get_qualified_column(),
4794
-                    $primary_key_field->get_table_column()
4795
-                );
4796
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4797
-                    continue;
4798
-                }
4799
-            }
4800
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4801
-            if (! $classInstance) {
4802
-                throw new EE_Error(
4803
-                    sprintf(
4804
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4805
-                        $this->get_this_model_name(),
4806
-                        http_build_query($row)
4807
-                    )
4808
-                );
4809
-            }
4810
-            //set the timezone on the instantiated objects
4811
-            $classInstance->set_timezone($this->_timezone);
4812
-            //make sure if there is any timezone setting present that we set the timezone for the object
4813
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4814
-            $array_of_objects[$key] = $classInstance;
4815
-            //also, for all the relations of type BelongsTo, see if we can cache
4816
-            //those related models
4817
-            //(we could do this for other relations too, but if there are conditions
4818
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4819
-            //so it requires a little more thought than just caching them immediately...)
4820
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4821
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4822
-                    //check if this model's INFO is present. If so, cache it on the model
4823
-                    $other_model = $relation_obj->get_other_model();
4824
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4825
-                    //if we managed to make a model object from the results, cache it on the main model object
4826
-                    if ($other_model_obj_maybe) {
4827
-                        //set timezone on these other model objects if they are present
4828
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4829
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4830
-                    }
4831
-                }
4832
-            }
4833
-        }
4834
-        return $array_of_objects;
4835
-    }
4836
-
4837
-
4838
-
4839
-    /**
4840
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4841
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4842
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4843
-     * object (as set in the model_field!).
4844
-     *
4845
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4846
-     * @throws Exception
4847
-     */
4848
-    public function create_default_object()
4849
-    {
4850
-        $this_model_fields_and_values = array();
4851
-        //setup the row using default values;
4852
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4853
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4854
-        }
4855
-        $classInstance = $this->_instantiate_new_instance_from_db(
4856
-            $this->_get_class_name(),
4857
-            $this_model_fields_and_values
4858
-        );
4859
-        return $classInstance;
4860
-    }
4861
-
4862
-
4863
-
4864
-    /**
4865
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4866
-     *                             or an stdClass where each property is the name of a column,
4867
-     * @return EE_Base_Class
4868
-     * @throws Exception
4869
-     * @throws EE_Error
4870
-     */
4871
-    public function instantiate_class_from_array_or_object($cols_n_values)
4872
-    {
4873
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4874
-            $cols_n_values = get_object_vars($cols_n_values);
4875
-        }
4876
-        $primary_key = null;
4877
-        //make sure the array only has keys that are fields/columns on this model
4878
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4879
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4880
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4881
-        }
4882
-        //check we actually found results that we can use to build our model object
4883
-        //if not, return null
4884
-        if ($this->has_primary_key_field()) {
4885
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4886
-                return null;
4887
-            }
4888
-        } else if ($this->unique_indexes()) {
4889
-            $first_column = reset($this_model_fields_n_values);
4890
-            if (empty($first_column)) {
4891
-                return null;
4892
-            }
4893
-        }
4894
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4895
-        if ($primary_key) {
4896
-            $classInstance = $this->get_from_entity_map($primary_key);
4897
-            if (! $classInstance) {
4898
-                $classInstance = $this->_instantiate_new_instance_from_db(
4899
-                    $this->_get_class_name(),
4900
-                    $this_model_fields_n_values
4901
-                );
4902
-                // add this new object to the entity map
4903
-                $classInstance = $this->add_to_entity_map($classInstance);
4904
-            }
4905
-        } else {
4906
-            $classInstance = $this->_instantiate_new_instance_from_db(
4907
-                $this->_get_class_name(),
4908
-                $this_model_fields_n_values
4909
-            );
4910
-        }
4911
-        // it is entirely possible that the instantiated class object has a set
4912
-        // timezone_string db field and has set it's internal _timezone property accordingly
4913
-        // (see new_instance_from_db in model objects particularly EE_Event for example).
4914
-        // In this case, we want to make sure the model object doesn't have its timezone string
4915
-        // overwritten by any timezone property currently set here on the model so,
4916
-        // we intentionally override the model _timezone property with the model_object timezone property.
4917
-        $this->set_timezone($classInstance->get_timezone());
4918
-        return $classInstance;
4919
-    }
4920
-
4921
-
4922
-
4923
-    /**
4924
-     * Gets the model object from the  entity map if it exists
4925
-     *
4926
-     * @param int|string $id the ID of the model object
4927
-     * @return EE_Base_Class
4928
-     */
4929
-    public function get_from_entity_map($id)
4930
-    {
4931
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4932
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4933
-    }
4934
-
4935
-
4936
-
4937
-    /**
4938
-     * add_to_entity_map
4939
-     * Adds the object to the model's entity mappings
4940
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4941
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4942
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4943
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4944
-     *        then this method should be called immediately after the update query
4945
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4946
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4947
-     *
4948
-     * @param    EE_Base_Class $object
4949
-     * @throws EE_Error
4950
-     * @return \EE_Base_Class
4951
-     */
4952
-    public function add_to_entity_map(EE_Base_Class $object)
4953
-    {
4954
-        $className = $this->_get_class_name();
4955
-        if (! $object instanceof $className) {
4956
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4957
-                is_object($object) ? get_class($object) : $object, $className));
4958
-        }
4959
-        /** @var $object EE_Base_Class */
4960
-        if (! $object->ID()) {
4961
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4962
-                "event_espresso"), get_class($this)));
4963
-        }
4964
-        // double check it's not already there
4965
-        $classInstance = $this->get_from_entity_map($object->ID());
4966
-        if ($classInstance) {
4967
-            return $classInstance;
4968
-        } else {
4969
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4970
-            return $object;
4971
-        }
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4978
-     * if no identifier is provided, then the entire entity map is emptied
4979
-     *
4980
-     * @param int|string $id the ID of the model object
4981
-     * @return boolean
4982
-     */
4983
-    public function clear_entity_map($id = null)
4984
-    {
4985
-        if (empty($id)) {
4986
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4987
-            return true;
4988
-        }
4989
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4990
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4991
-            return true;
4992
-        }
4993
-        return false;
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5000
-     * Given an array where keys are column (or column alias) names and values,
5001
-     * returns an array of their corresponding field names and database values
5002
-     *
5003
-     * @param array $cols_n_values
5004
-     * @return array
5005
-     */
5006
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
-    {
5008
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5009
-    }
5010
-
5011
-
5012
-
5013
-    /**
5014
-     * _deduce_fields_n_values_from_cols_n_values
5015
-     * Given an array where keys are column (or column alias) names and values,
5016
-     * returns an array of their corresponding field names and database values
5017
-     *
5018
-     * @param string $cols_n_values
5019
-     * @return array
5020
-     */
5021
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5022
-    {
5023
-        $this_model_fields_n_values = array();
5024
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5025
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5026
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5027
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5028
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5029
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5030
-                    if (! $field_obj->is_db_only_field()) {
5031
-                        //prepare field as if its coming from db
5032
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5033
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5034
-                    }
5035
-                }
5036
-            } else {
5037
-                //the table's rows existed. Use their values
5038
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5039
-                    if (! $field_obj->is_db_only_field()) {
5040
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5041
-                            $cols_n_values, $field_obj->get_qualified_column(),
5042
-                            $field_obj->get_table_column()
5043
-                        );
5044
-                    }
5045
-                }
5046
-            }
5047
-        }
5048
-        return $this_model_fields_n_values;
5049
-    }
5050
-
5051
-
5052
-
5053
-    /**
5054
-     * @param $cols_n_values
5055
-     * @param $qualified_column
5056
-     * @param $regular_column
5057
-     * @return null
5058
-     */
5059
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5060
-    {
5061
-        $value = null;
5062
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5063
-        //does the field on the model relate to this column retrieved from the db?
5064
-        //or is it a db-only field? (not relating to the model)
5065
-        if (isset($cols_n_values[$qualified_column])) {
5066
-            $value = $cols_n_values[$qualified_column];
5067
-        } elseif (isset($cols_n_values[$regular_column])) {
5068
-            $value = $cols_n_values[$regular_column];
5069
-        }
5070
-        return $value;
5071
-    }
5072
-
5073
-
5074
-
5075
-    /**
5076
-     * refresh_entity_map_from_db
5077
-     * Makes sure the model object in the entity map at $id assumes the values
5078
-     * of the database (opposite of EE_base_Class::save())
5079
-     *
5080
-     * @param int|string $id
5081
-     * @return EE_Base_Class
5082
-     * @throws EE_Error
5083
-     */
5084
-    public function refresh_entity_map_from_db($id)
5085
-    {
5086
-        $obj_in_map = $this->get_from_entity_map($id);
5087
-        if ($obj_in_map) {
5088
-            $wpdb_results = $this->_get_all_wpdb_results(
5089
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5090
-            );
5091
-            if ($wpdb_results && is_array($wpdb_results)) {
5092
-                $one_row = reset($wpdb_results);
5093
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5094
-                    $obj_in_map->set_from_db($field_name, $db_value);
5095
-                }
5096
-                //clear the cache of related model objects
5097
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5098
-                    $obj_in_map->clear_cache($relation_name, null, true);
5099
-                }
5100
-            }
5101
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5102
-            return $obj_in_map;
5103
-        } else {
5104
-            return $this->get_one_by_ID($id);
5105
-        }
5106
-    }
5107
-
5108
-
5109
-
5110
-    /**
5111
-     * refresh_entity_map_with
5112
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5113
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5114
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5115
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5116
-     *
5117
-     * @param int|string    $id
5118
-     * @param EE_Base_Class $replacing_model_obj
5119
-     * @return \EE_Base_Class
5120
-     * @throws EE_Error
5121
-     */
5122
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5123
-    {
5124
-        $obj_in_map = $this->get_from_entity_map($id);
5125
-        if ($obj_in_map) {
5126
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5127
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5128
-                    $obj_in_map->set($field_name, $value);
5129
-                }
5130
-                //make the model object in the entity map's cache match the $replacing_model_obj
5131
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5132
-                    $obj_in_map->clear_cache($relation_name, null, true);
5133
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5134
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5135
-                    }
5136
-                }
5137
-            }
5138
-            return $obj_in_map;
5139
-        } else {
5140
-            $this->add_to_entity_map($replacing_model_obj);
5141
-            return $replacing_model_obj;
5142
-        }
5143
-    }
5144
-
5145
-
5146
-
5147
-    /**
5148
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5149
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5150
-     * require_once($this->_getClassName().".class.php");
5151
-     *
5152
-     * @return string
5153
-     */
5154
-    private function _get_class_name()
5155
-    {
5156
-        return "EE_" . $this->get_this_model_name();
5157
-    }
5158
-
5159
-
5160
-
5161
-    /**
5162
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5163
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5164
-     * it would be 'Events'.
5165
-     *
5166
-     * @param int $quantity
5167
-     * @return string
5168
-     */
5169
-    public function item_name($quantity = 1)
5170
-    {
5171
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5172
-    }
5173
-
5174
-
5175
-
5176
-    /**
5177
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5178
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5179
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5180
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5181
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5182
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5183
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5184
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5185
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5186
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5187
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5188
-     *        return $previousReturnValue.$returnString;
5189
-     * }
5190
-     * require('EEM_Answer.model.php');
5191
-     * $answer=EEM_Answer::instance();
5192
-     * echo $answer->my_callback('monkeys',100);
5193
-     * //will output "you called my_callback! and passed args:monkeys,100"
5194
-     *
5195
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5196
-     * @param array  $args       array of original arguments passed to the function
5197
-     * @throws EE_Error
5198
-     * @return mixed whatever the plugin which calls add_filter decides
5199
-     */
5200
-    public function __call($methodName, $args)
5201
-    {
5202
-        $className = get_class($this);
5203
-        $tagName = "FHEE__{$className}__{$methodName}";
5204
-        if (! has_filter($tagName)) {
5205
-            throw new EE_Error(
5206
-                sprintf(
5207
-                    __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5208
-                        'event_espresso'),
5209
-                    $methodName,
5210
-                    $className,
5211
-                    $tagName,
5212
-                    '<br />'
5213
-                )
5214
-            );
5215
-        }
5216
-        return apply_filters($tagName, null, $this, $args);
5217
-    }
5218
-
5219
-
5220
-
5221
-    /**
5222
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5223
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5224
-     *
5225
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5226
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5227
-     *                                                       the object's class name
5228
-     *                                                       or object's ID
5229
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5230
-     *                                                       exists in the database. If it does not, we add it
5231
-     * @throws EE_Error
5232
-     * @return EE_Base_Class
5233
-     */
5234
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5235
-    {
5236
-        $className = $this->_get_class_name();
5237
-        if ($base_class_obj_or_id instanceof $className) {
5238
-            $model_object = $base_class_obj_or_id;
5239
-        } else {
5240
-            $primary_key_field = $this->get_primary_key_field();
5241
-            if (
5242
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5243
-                && (
5244
-                    is_int($base_class_obj_or_id)
5245
-                    || is_string($base_class_obj_or_id)
5246
-                )
5247
-            ) {
5248
-                // assume it's an ID.
5249
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5250
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5251
-            } else if (
5252
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5253
-                && is_string($base_class_obj_or_id)
5254
-            ) {
5255
-                // assume its a string representation of the object
5256
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5257
-            } else {
5258
-                throw new EE_Error(
5259
-                    sprintf(
5260
-                        __(
5261
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5262
-                            'event_espresso'
5263
-                        ),
5264
-                        $base_class_obj_or_id,
5265
-                        $this->_get_class_name(),
5266
-                        print_r($base_class_obj_or_id, true)
5267
-                    )
5268
-                );
5269
-            }
5270
-        }
5271
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5272
-            $model_object->save();
5273
-        }
5274
-        return $model_object;
5275
-    }
5276
-
5277
-
5278
-
5279
-    /**
5280
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5281
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5282
-     * returns it ID.
5283
-     *
5284
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5285
-     * @return int|string depending on the type of this model object's ID
5286
-     * @throws EE_Error
5287
-     */
5288
-    public function ensure_is_ID($base_class_obj_or_id)
5289
-    {
5290
-        $className = $this->_get_class_name();
5291
-        if ($base_class_obj_or_id instanceof $className) {
5292
-            /** @var $base_class_obj_or_id EE_Base_Class */
5293
-            $id = $base_class_obj_or_id->ID();
5294
-        } elseif (is_int($base_class_obj_or_id)) {
5295
-            //assume it's an ID
5296
-            $id = $base_class_obj_or_id;
5297
-        } elseif (is_string($base_class_obj_or_id)) {
5298
-            //assume its a string representation of the object
5299
-            $id = $base_class_obj_or_id;
5300
-        } else {
5301
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5302
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5303
-                print_r($base_class_obj_or_id, true)));
5304
-        }
5305
-        return $id;
5306
-    }
5307
-
5308
-
5309
-
5310
-    /**
5311
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5312
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5313
-     * been sanitized and converted into the appropriate domain.
5314
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5315
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5316
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5317
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5318
-     * $EVT = EEM_Event::instance(); $old_setting =
5319
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5320
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5321
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5322
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5323
-     *
5324
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5325
-     * @return void
5326
-     */
5327
-    public function assume_values_already_prepared_by_model_object(
5328
-        $values_already_prepared = self::not_prepared_by_model_object
5329
-    ) {
5330
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5331
-    }
5332
-
5333
-
5334
-
5335
-    /**
5336
-     * Read comments for assume_values_already_prepared_by_model_object()
5337
-     *
5338
-     * @return int
5339
-     */
5340
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5341
-    {
5342
-        return $this->_values_already_prepared_by_model_object;
5343
-    }
5344
-
5345
-
5346
-
5347
-    /**
5348
-     * Gets all the indexes on this model
5349
-     *
5350
-     * @return EE_Index[]
5351
-     */
5352
-    public function indexes()
5353
-    {
5354
-        return $this->_indexes;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * Gets all the Unique Indexes on this model
5361
-     *
5362
-     * @return EE_Unique_Index[]
5363
-     */
5364
-    public function unique_indexes()
5365
-    {
5366
-        $unique_indexes = array();
5367
-        foreach ($this->_indexes as $name => $index) {
5368
-            if ($index instanceof EE_Unique_Index) {
5369
-                $unique_indexes [$name] = $index;
5370
-            }
5371
-        }
5372
-        return $unique_indexes;
5373
-    }
5374
-
5375
-
5376
-
5377
-    /**
5378
-     * Gets all the fields which, when combined, make the primary key.
5379
-     * This is usually just an array with 1 element (the primary key), but in cases
5380
-     * where there is no primary key, it's a combination of fields as defined
5381
-     * on a primary index
5382
-     *
5383
-     * @return EE_Model_Field_Base[] indexed by the field's name
5384
-     * @throws EE_Error
5385
-     */
5386
-    public function get_combined_primary_key_fields()
5387
-    {
5388
-        foreach ($this->indexes() as $index) {
5389
-            if ($index instanceof EE_Primary_Key_Index) {
5390
-                return $index->fields();
5391
-            }
5392
-        }
5393
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * Used to build a primary key string (when the model has no primary key),
5400
-     * which can be used a unique string to identify this model object.
5401
-     *
5402
-     * @param array $cols_n_values keys are field names, values are their values
5403
-     * @return string
5404
-     * @throws EE_Error
5405
-     */
5406
-    public function get_index_primary_key_string($cols_n_values)
5407
-    {
5408
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5409
-            $this->get_combined_primary_key_fields());
5410
-        return http_build_query($cols_n_values_for_primary_key_index);
5411
-    }
5412
-
5413
-
5414
-
5415
-    /**
5416
-     * Gets the field values from the primary key string
5417
-     *
5418
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5419
-     * @param string $index_primary_key_string
5420
-     * @return null|array
5421
-     * @throws EE_Error
5422
-     */
5423
-    public function parse_index_primary_key_string($index_primary_key_string)
5424
-    {
5425
-        $key_fields = $this->get_combined_primary_key_fields();
5426
-        //check all of them are in the $id
5427
-        $key_vals_in_combined_pk = array();
5428
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5429
-        foreach ($key_fields as $key_field_name => $field_obj) {
5430
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5431
-                return null;
5432
-            }
5433
-        }
5434
-        return $key_vals_in_combined_pk;
5435
-    }
5436
-
5437
-
5438
-
5439
-    /**
5440
-     * verifies that an array of key-value pairs for model fields has a key
5441
-     * for each field comprising the primary key index
5442
-     *
5443
-     * @param array $key_vals
5444
-     * @return boolean
5445
-     * @throws EE_Error
5446
-     */
5447
-    public function has_all_combined_primary_key_fields($key_vals)
5448
-    {
5449
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5450
-        foreach ($keys_it_should_have as $key) {
5451
-            if (! isset($key_vals[$key])) {
5452
-                return false;
5453
-            }
5454
-        }
5455
-        return true;
5456
-    }
5457
-
5458
-
5459
-
5460
-    /**
5461
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5462
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5463
-     *
5464
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5465
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5466
-     * @throws EE_Error
5467
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5468
-     *                                                              indexed)
5469
-     */
5470
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5471
-    {
5472
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5473
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5474
-        } elseif (is_array($model_object_or_attributes_array)) {
5475
-            $attributes_array = $model_object_or_attributes_array;
5476
-        } else {
5477
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5478
-                "event_espresso"), $model_object_or_attributes_array));
5479
-        }
5480
-        //even copies obviously won't have the same ID, so remove the primary key
5481
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5482
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5483
-            unset($attributes_array[$this->primary_key_name()]);
5484
-        }
5485
-        if (isset($query_params[0])) {
5486
-            $query_params[0] = array_merge($attributes_array, $query_params);
5487
-        } else {
5488
-            $query_params[0] = $attributes_array;
5489
-        }
5490
-        return $this->get_all($query_params);
5491
-    }
5492
-
5493
-
5494
-
5495
-    /**
5496
-     * Gets the first copy we find. See get_all_copies for more details
5497
-     *
5498
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5499
-     * @param array $query_params
5500
-     * @return EE_Base_Class
5501
-     * @throws EE_Error
5502
-     */
5503
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5504
-    {
5505
-        if (! is_array($query_params)) {
5506
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5507
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5508
-                    gettype($query_params)), '4.6.0');
5509
-            $query_params = array();
5510
-        }
5511
-        $query_params['limit'] = 1;
5512
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5513
-        if (is_array($copies)) {
5514
-            return array_shift($copies);
5515
-        } else {
5516
-            return null;
5517
-        }
5518
-    }
5519
-
5520
-
5521
-
5522
-    /**
5523
-     * Updates the item with the specified id. Ignores default query parameters because
5524
-     * we have specified the ID, and its assumed we KNOW what we're doing
5525
-     *
5526
-     * @param array      $fields_n_values keys are field names, values are their new values
5527
-     * @param int|string $id              the value of the primary key to update
5528
-     * @return int number of rows updated
5529
-     * @throws EE_Error
5530
-     */
5531
-    public function update_by_ID($fields_n_values, $id)
5532
-    {
5533
-        $query_params = array(
5534
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5535
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5536
-        );
5537
-        return $this->update($fields_n_values, $query_params);
5538
-    }
5539
-
5540
-
5541
-
5542
-    /**
5543
-     * Changes an operator which was supplied to the models into one usable in SQL
5544
-     *
5545
-     * @param string $operator_supplied
5546
-     * @return string an operator which can be used in SQL
5547
-     * @throws EE_Error
5548
-     */
5549
-    private function _prepare_operator_for_sql($operator_supplied)
5550
-    {
5551
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5552
-            : null;
5553
-        if ($sql_operator) {
5554
-            return $sql_operator;
5555
-        } else {
5556
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5557
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5558
-        }
5559
-    }
5560
-
5561
-
5562
-
5563
-    /**
5564
-     * Gets an array where keys are the primary keys and values are their 'names'
5565
-     * (as determined by the model object's name() function, which is often overridden)
5566
-     *
5567
-     * @param array $query_params like get_all's
5568
-     * @return string[]
5569
-     * @throws EE_Error
5570
-     */
5571
-    public function get_all_names($query_params = array())
5572
-    {
5573
-        $objs = $this->get_all($query_params);
5574
-        $names = array();
5575
-        foreach ($objs as $obj) {
5576
-            $names[$obj->ID()] = $obj->name();
5577
-        }
5578
-        return $names;
5579
-    }
5580
-
5581
-
5582
-
5583
-    /**
5584
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5585
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5586
-     * this is duplicated effort and reduces efficiency) you would be better to use
5587
-     * array_keys() on $model_objects.
5588
-     *
5589
-     * @param \EE_Base_Class[] $model_objects
5590
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5591
-     *                                               in the returned array
5592
-     * @return array
5593
-     * @throws EE_Error
5594
-     */
5595
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5596
-    {
5597
-        if (! $this->has_primary_key_field()) {
5598
-            if (WP_DEBUG) {
5599
-                EE_Error::add_error(
5600
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5601
-                    __FILE__,
5602
-                    __FUNCTION__,
5603
-                    __LINE__
5604
-                );
5605
-            }
5606
-        }
5607
-        $IDs = array();
5608
-        foreach ($model_objects as $model_object) {
5609
-            $id = $model_object->ID();
5610
-            if (! $id) {
5611
-                if ($filter_out_empty_ids) {
5612
-                    continue;
5613
-                }
5614
-                if (WP_DEBUG) {
5615
-                    EE_Error::add_error(
5616
-                        __(
5617
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5618
-                            'event_espresso'
5619
-                        ),
5620
-                        __FILE__,
5621
-                        __FUNCTION__,
5622
-                        __LINE__
5623
-                    );
5624
-                }
5625
-            }
5626
-            $IDs[] = $id;
5627
-        }
5628
-        return $IDs;
5629
-    }
5630
-
5631
-
5632
-
5633
-    /**
5634
-     * Returns the string used in capabilities relating to this model. If there
5635
-     * are no capabilities that relate to this model returns false
5636
-     *
5637
-     * @return string|false
5638
-     */
5639
-    public function cap_slug()
5640
-    {
5641
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5642
-    }
5643
-
5644
-
5645
-
5646
-    /**
5647
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5648
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5649
-     * only returns the cap restrictions array in that context (ie, the array
5650
-     * at that key)
5651
-     *
5652
-     * @param string $context
5653
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5654
-     * @throws EE_Error
5655
-     */
5656
-    public function cap_restrictions($context = EEM_Base::caps_read)
5657
-    {
5658
-        EEM_Base::verify_is_valid_cap_context($context);
5659
-        //check if we ought to run the restriction generator first
5660
-        if (
5661
-            isset($this->_cap_restriction_generators[$context])
5662
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5663
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5664
-        ) {
5665
-            $this->_cap_restrictions[$context] = array_merge(
5666
-                $this->_cap_restrictions[$context],
5667
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5668
-            );
5669
-        }
5670
-        //and make sure we've finalized the construction of each restriction
5671
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5672
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5673
-                $where_conditions_obj->_finalize_construct($this);
5674
-            }
5675
-        }
5676
-        return $this->_cap_restrictions[$context];
5677
-    }
5678
-
5679
-
5680
-
5681
-    /**
5682
-     * Indicating whether or not this model thinks its a wp core model
5683
-     *
5684
-     * @return boolean
5685
-     */
5686
-    public function is_wp_core_model()
5687
-    {
5688
-        return $this->_wp_core_model;
5689
-    }
5690
-
5691
-
5692
-
5693
-    /**
5694
-     * Gets all the caps that are missing which impose a restriction on
5695
-     * queries made in this context
5696
-     *
5697
-     * @param string $context one of EEM_Base::caps_ constants
5698
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5699
-     * @throws EE_Error
5700
-     */
5701
-    public function caps_missing($context = EEM_Base::caps_read)
5702
-    {
5703
-        $missing_caps = array();
5704
-        $cap_restrictions = $this->cap_restrictions($context);
5705
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5706
-            if (! EE_Capabilities::instance()
5707
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5708
-            ) {
5709
-                $missing_caps[$cap] = $restriction_if_no_cap;
5710
-            }
5711
-        }
5712
-        return $missing_caps;
5713
-    }
5714
-
5715
-
5716
-
5717
-    /**
5718
-     * Gets the mapping from capability contexts to action strings used in capability names
5719
-     *
5720
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5721
-     * one of 'read', 'edit', or 'delete'
5722
-     */
5723
-    public function cap_contexts_to_cap_action_map()
5724
-    {
5725
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5726
-            $this);
5727
-    }
5728
-
5729
-
5730
-
5731
-    /**
5732
-     * Gets the action string for the specified capability context
5733
-     *
5734
-     * @param string $context
5735
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5736
-     * @throws EE_Error
5737
-     */
5738
-    public function cap_action_for_context($context)
5739
-    {
5740
-        $mapping = $this->cap_contexts_to_cap_action_map();
5741
-        if (isset($mapping[$context])) {
5742
-            return $mapping[$context];
5743
-        }
5744
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5745
-            return $action;
5746
-        }
5747
-        throw new EE_Error(
5748
-            sprintf(
5749
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5750
-                $context,
5751
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5752
-            )
5753
-        );
5754
-    }
5755
-
5756
-
5757
-
5758
-    /**
5759
-     * Returns all the capability contexts which are valid when querying models
5760
-     *
5761
-     * @return array
5762
-     */
5763
-    public static function valid_cap_contexts()
5764
-    {
5765
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5766
-            self::caps_read,
5767
-            self::caps_read_admin,
5768
-            self::caps_edit,
5769
-            self::caps_delete,
5770
-        ));
5771
-    }
5772
-
5773
-
5774
-
5775
-    /**
5776
-     * Returns all valid options for 'default_where_conditions'
5777
-     *
5778
-     * @return array
5779
-     */
5780
-    public static function valid_default_where_conditions()
5781
-    {
5782
-        return array(
5783
-            EEM_Base::default_where_conditions_all,
5784
-            EEM_Base::default_where_conditions_this_only,
5785
-            EEM_Base::default_where_conditions_others_only,
5786
-            EEM_Base::default_where_conditions_minimum_all,
5787
-            EEM_Base::default_where_conditions_minimum_others,
5788
-            EEM_Base::default_where_conditions_none
5789
-        );
5790
-    }
5791
-
5792
-    // public static function default_where_conditions_full
5793
-    /**
5794
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5795
-     *
5796
-     * @param string $context
5797
-     * @return bool
5798
-     * @throws EE_Error
5799
-     */
5800
-    static public function verify_is_valid_cap_context($context)
5801
-    {
5802
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5803
-        if (in_array($context, $valid_cap_contexts)) {
5804
-            return true;
5805
-        } else {
5806
-            throw new EE_Error(
5807
-                sprintf(
5808
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5809
-                        'event_espresso'),
5810
-                    $context,
5811
-                    'EEM_Base',
5812
-                    implode(',', $valid_cap_contexts)
5813
-                )
5814
-            );
5815
-        }
5816
-    }
5817
-
5818
-
5819
-
5820
-    /**
5821
-     * Clears all the models field caches. This is only useful when a sub-class
5822
-     * might have added a field or something and these caches might be invalidated
5823
-     */
5824
-    protected function _invalidate_field_caches()
5825
-    {
5826
-        $this->_cache_foreign_key_to_fields = array();
5827
-        $this->_cached_fields = null;
5828
-        $this->_cached_fields_non_db_only = null;
5829
-    }
5830
-
5831
-
5832
-
5833
-    /**
5834
-     * _instantiate_new_instance_from_db
5835
-     *
5836
-     * @param string $class_name
5837
-     * @param array  $arguments
5838
-     * @return \EE_Base_Class
5839
-     * @throws Exception
5840
-     */
5841
-    public function _instantiate_new_instance_from_db($class_name, $arguments)
5842
-    {
5843
-        if ( ! class_exists($class_name)) {
5844
-            throw new EE_Error(
5845
-                sprintf(
5846
-                    __('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5847
-                    $class_name
5848
-                )
5849
-            );
5850
-        }
5851
-        return call_user_func_array(
5852
-            array($class_name, 'new_instance'),
5853
-            array((array)$arguments, $this->_timezone, array(), true)
5854
-        );
5855
-    }
5856
-
5857
-
5858
-    /**
5859
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5860
-     * (eg "and", "or", "not").
5861
-     *
5862
-     * @return array
5863
-     */
5864
-    public function logic_query_param_keys()
5865
-    {
5866
-        return $this->_logic_query_param_keys;
5867
-    }
5868
-
5869
-
5870
-
5871
-    /**
5872
-     * Determines whether or not the where query param array key is for a logic query param.
5873
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5874
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5875
-     *
5876
-     * @param $query_param_key
5877
-     * @return bool
5878
-     */
5879
-    public function is_logic_query_param_key($query_param_key)
5880
-    {
5881
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5882
-            if ($query_param_key === $logic_query_param_key
5883
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5884
-            ) {
5885
-                return true;
5886
-            }
5887
-        }
5888
-        return false;
5889
-    }
3615
+		}
3616
+		return $null_friendly_where_conditions;
3617
+	}
3618
+
3619
+
3620
+
3621
+	/**
3622
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3623
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3624
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3625
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3626
+	 *
3627
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3628
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3629
+	 */
3630
+	private function _get_default_where_conditions($model_relation_path = null)
3631
+	{
3632
+		if ($this->_ignore_where_strategy) {
3633
+			return array();
3634
+		}
3635
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3636
+	}
3637
+
3638
+
3639
+
3640
+	/**
3641
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3642
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3643
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3644
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3645
+	 * Similar to _get_default_where_conditions
3646
+	 *
3647
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3648
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3649
+	 */
3650
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3651
+	{
3652
+		if ($this->_ignore_where_strategy) {
3653
+			return array();
3654
+		}
3655
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3656
+	}
3657
+
3658
+
3659
+
3660
+	/**
3661
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3662
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3663
+	 *
3664
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3665
+	 * @return string
3666
+	 * @throws EE_Error
3667
+	 */
3668
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3669
+	{
3670
+		$selects = $this->_get_columns_to_select_for_this_model();
3671
+		foreach (
3672
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3673
+			$name_of_other_model_included
3674
+		) {
3675
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3676
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3677
+			foreach ($other_model_selects as $key => $value) {
3678
+				$selects[] = $value;
3679
+			}
3680
+		}
3681
+		return implode(", ", $selects);
3682
+	}
3683
+
3684
+
3685
+
3686
+	/**
3687
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3688
+	 * So that's going to be the columns for all the fields on the model
3689
+	 *
3690
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3691
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3692
+	 */
3693
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3694
+	{
3695
+		$fields = $this->field_settings();
3696
+		$selects = array();
3697
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3698
+			$this->get_this_model_name());
3699
+		foreach ($fields as $field_obj) {
3700
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3701
+						 . $field_obj->get_table_alias()
3702
+						 . "."
3703
+						 . $field_obj->get_table_column()
3704
+						 . " AS '"
3705
+						 . $table_alias_with_model_relation_chain_prefix
3706
+						 . $field_obj->get_table_alias()
3707
+						 . "."
3708
+						 . $field_obj->get_table_column()
3709
+						 . "'";
3710
+		}
3711
+		//make sure we are also getting the PKs of each table
3712
+		$tables = $this->get_tables();
3713
+		if (count($tables) > 1) {
3714
+			foreach ($tables as $table_obj) {
3715
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3716
+									   . $table_obj->get_fully_qualified_pk_column();
3717
+				if (! in_array($qualified_pk_column, $selects)) {
3718
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3719
+				}
3720
+			}
3721
+		}
3722
+		return $selects;
3723
+	}
3724
+
3725
+
3726
+
3727
+	/**
3728
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3729
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3730
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3731
+	 * SQL for joining, and the data types
3732
+	 *
3733
+	 * @param null|string                 $original_query_param
3734
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3735
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3736
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3737
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3738
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3739
+	 *                                                          or 'Registration's
3740
+	 * @param string                      $original_query_param what it originally was (eg
3741
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3742
+	 *                                                          matches $query_param
3743
+	 * @throws EE_Error
3744
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3745
+	 */
3746
+	private function _extract_related_model_info_from_query_param(
3747
+		$query_param,
3748
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3749
+		$query_param_type,
3750
+		$original_query_param = null
3751
+	) {
3752
+		if ($original_query_param === null) {
3753
+			$original_query_param = $query_param;
3754
+		}
3755
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3756
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3757
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3758
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3759
+		//check to see if we have a field on this model
3760
+		$this_model_fields = $this->field_settings(true);
3761
+		if (array_key_exists($query_param, $this_model_fields)) {
3762
+			if ($allow_fields) {
3763
+				return;
3764
+			} else {
3765
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3766
+					"event_espresso"),
3767
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3768
+			}
3769
+		} //check if this is a special logic query param
3770
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3771
+			if ($allow_logic_query_params) {
3772
+				return;
3773
+			} else {
3774
+				throw new EE_Error(
3775
+					sprintf(
3776
+						__('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3777
+							'event_espresso'),
3778
+						implode('", "', $this->_logic_query_param_keys),
3779
+						$query_param,
3780
+						get_class($this),
3781
+						'<br />',
3782
+						"\t"
3783
+						. ' $passed_in_query_info = <pre>'
3784
+						. print_r($passed_in_query_info, true)
3785
+						. '</pre>'
3786
+						. "\n\t"
3787
+						. ' $query_param_type = '
3788
+						. $query_param_type
3789
+						. "\n\t"
3790
+						. ' $original_query_param = '
3791
+						. $original_query_param
3792
+					)
3793
+				);
3794
+			}
3795
+		} //check if it's a custom selection
3796
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3797
+			return;
3798
+		}
3799
+		//check if has a model name at the beginning
3800
+		//and
3801
+		//check if it's a field on a related model
3802
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3803
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3804
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3805
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3806
+				if ($query_param === '') {
3807
+					//nothing left to $query_param
3808
+					//we should actually end in a field name, not a model like this!
3809
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3810
+						"event_espresso"),
3811
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3812
+				} else {
3813
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3814
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3815
+						$passed_in_query_info, $query_param_type, $original_query_param);
3816
+					return;
3817
+				}
3818
+			} elseif ($query_param === $valid_related_model_name) {
3819
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3820
+				return;
3821
+			}
3822
+		}
3823
+		//ok so $query_param didn't start with a model name
3824
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3825
+		//it's wack, that's what it is
3826
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3827
+			"event_espresso"),
3828
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3829
+	}
3830
+
3831
+
3832
+
3833
+	/**
3834
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3835
+	 * and store it on $passed_in_query_info
3836
+	 *
3837
+	 * @param string                      $model_name
3838
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3839
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3840
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3841
+	 *                                                          and are adding a join to 'Payment' with the original
3842
+	 *                                                          query param key
3843
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3844
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3845
+	 *                                                          Payment wants to add default query params so that it
3846
+	 *                                                          will know what models to prepend onto its default query
3847
+	 *                                                          params or in case it wants to rename tables (in case
3848
+	 *                                                          there are multiple joins to the same table)
3849
+	 * @return void
3850
+	 * @throws EE_Error
3851
+	 */
3852
+	private function _add_join_to_model(
3853
+		$model_name,
3854
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3855
+		$original_query_param
3856
+	) {
3857
+		$relation_obj = $this->related_settings_for($model_name);
3858
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3859
+		//check if the relation is HABTM, because then we're essentially doing two joins
3860
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3861
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3862
+			$join_model_obj = $relation_obj->get_join_model();
3863
+			//replace the model specified with the join model for this relation chain, whi
3864
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3865
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3866
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3867
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3868
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3869
+			$passed_in_query_info->merge($new_query_info);
3870
+		}
3871
+		//now just join to the other table pointed to by the relation object, and add its data types
3872
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3873
+			array($model_relation_chain => $model_name),
3874
+			$relation_obj->get_join_statement($model_relation_chain));
3875
+		$passed_in_query_info->merge($new_query_info);
3876
+	}
3877
+
3878
+
3879
+
3880
+	/**
3881
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3882
+	 *
3883
+	 * @param array $where_params like EEM_Base::get_all
3884
+	 * @return string of SQL
3885
+	 * @throws EE_Error
3886
+	 */
3887
+	private function _construct_where_clause($where_params)
3888
+	{
3889
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3890
+		if ($SQL) {
3891
+			return " WHERE " . $SQL;
3892
+		} else {
3893
+			return '';
3894
+		}
3895
+	}
3896
+
3897
+
3898
+
3899
+	/**
3900
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3901
+	 * and should be passed HAVING parameters, not WHERE parameters
3902
+	 *
3903
+	 * @param array $having_params
3904
+	 * @return string
3905
+	 * @throws EE_Error
3906
+	 */
3907
+	private function _construct_having_clause($having_params)
3908
+	{
3909
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3910
+		if ($SQL) {
3911
+			return " HAVING " . $SQL;
3912
+		} else {
3913
+			return '';
3914
+		}
3915
+	}
3916
+
3917
+
3918
+
3919
+	/**
3920
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3921
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3922
+	 * EEM_Attendee.
3923
+	 *
3924
+	 * @param string $field_name
3925
+	 * @param string $model_name
3926
+	 * @return EE_Model_Field_Base
3927
+	 * @throws EE_Error
3928
+	 */
3929
+	protected function _get_field_on_model($field_name, $model_name)
3930
+	{
3931
+		$model_class = 'EEM_' . $model_name;
3932
+		$model_filepath = $model_class . ".model.php";
3933
+		if (is_readable($model_filepath)) {
3934
+			require_once($model_filepath);
3935
+			$model_instance = call_user_func($model_name . "::instance");
3936
+			/* @var $model_instance EEM_Base */
3937
+			return $model_instance->field_settings_for($field_name);
3938
+		} else {
3939
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3940
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3941
+		}
3942
+	}
3943
+
3944
+
3945
+
3946
+	/**
3947
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3948
+	 * Event_Meta.meta_value = 'foo'))"
3949
+	 *
3950
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3951
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3952
+	 * @throws EE_Error
3953
+	 * @return string of SQL
3954
+	 */
3955
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3956
+	{
3957
+		$where_clauses = array();
3958
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3959
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3960
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3961
+				switch ($query_param) {
3962
+					case 'not':
3963
+					case 'NOT':
3964
+						$where_clauses[] = "! ("
3965
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3966
+								$glue)
3967
+										   . ")";
3968
+						break;
3969
+					case 'and':
3970
+					case 'AND':
3971
+						$where_clauses[] = " ("
3972
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3973
+								' AND ')
3974
+										   . ")";
3975
+						break;
3976
+					case 'or':
3977
+					case 'OR':
3978
+						$where_clauses[] = " ("
3979
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3980
+								' OR ')
3981
+										   . ")";
3982
+						break;
3983
+				}
3984
+			} else {
3985
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3986
+				//if it's not a normal field, maybe it's a custom selection?
3987
+				if (! $field_obj) {
3988
+					if (isset($this->_custom_selections[$query_param][1])) {
3989
+						$field_obj = $this->_custom_selections[$query_param][1];
3990
+					} else {
3991
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3992
+							"event_espresso"), $query_param));
3993
+					}
3994
+				}
3995
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3996
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3997
+			}
3998
+		}
3999
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4000
+	}
4001
+
4002
+
4003
+
4004
+	/**
4005
+	 * Takes the input parameter and extract the table name (alias) and column name
4006
+	 *
4007
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4008
+	 * @throws EE_Error
4009
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4010
+	 */
4011
+	private function _deduce_column_name_from_query_param($query_param)
4012
+	{
4013
+		$field = $this->_deduce_field_from_query_param($query_param);
4014
+		if ($field) {
4015
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4016
+				$query_param);
4017
+			return $table_alias_prefix . $field->get_qualified_column();
4018
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4019
+			//maybe it's custom selection item?
4020
+			//if so, just use it as the "column name"
4021
+			return $query_param;
4022
+		} else {
4023
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4024
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4025
+		}
4026
+	}
4027
+
4028
+
4029
+
4030
+	/**
4031
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4032
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4033
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4034
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4035
+	 *
4036
+	 * @param string $condition_query_param_key
4037
+	 * @return string
4038
+	 */
4039
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4040
+	{
4041
+		$pos_of_star = strpos($condition_query_param_key, '*');
4042
+		if ($pos_of_star === false) {
4043
+			return $condition_query_param_key;
4044
+		} else {
4045
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4046
+			return $condition_query_param_sans_star;
4047
+		}
4048
+	}
4049
+
4050
+
4051
+
4052
+	/**
4053
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4054
+	 *
4055
+	 * @param                            mixed      array | string    $op_and_value
4056
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4057
+	 * @throws EE_Error
4058
+	 * @return string
4059
+	 */
4060
+	private function _construct_op_and_value($op_and_value, $field_obj)
4061
+	{
4062
+		if (is_array($op_and_value)) {
4063
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4064
+			if (! $operator) {
4065
+				$php_array_like_string = array();
4066
+				foreach ($op_and_value as $key => $value) {
4067
+					$php_array_like_string[] = "$key=>$value";
4068
+				}
4069
+				throw new EE_Error(
4070
+					sprintf(
4071
+						__(
4072
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4073
+							"event_espresso"
4074
+						),
4075
+						implode(",", $php_array_like_string)
4076
+					)
4077
+				);
4078
+			}
4079
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4080
+		} else {
4081
+			$operator = '=';
4082
+			$value = $op_and_value;
4083
+		}
4084
+		//check to see if the value is actually another field
4085
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4086
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4087
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4088
+			//in this case, the value should be an array, or at least a comma-separated list
4089
+			//it will need to handle a little differently
4090
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4091
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4092
+			return $operator . SP . $cleaned_value;
4093
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4094
+			//the value should be an array with count of two.
4095
+			if (count($value) !== 2) {
4096
+				throw new EE_Error(
4097
+					sprintf(
4098
+						__(
4099
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4100
+							'event_espresso'
4101
+						),
4102
+						"BETWEEN"
4103
+					)
4104
+				);
4105
+			}
4106
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4107
+			return $operator . SP . $cleaned_value;
4108
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4109
+			if ($value !== null) {
4110
+				throw new EE_Error(
4111
+					sprintf(
4112
+						__(
4113
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4114
+							"event_espresso"
4115
+						),
4116
+						$value,
4117
+						$operator
4118
+					)
4119
+				);
4120
+			}
4121
+			return $operator;
4122
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4123
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4124
+			//remove other junk. So just treat it as a string.
4125
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4126
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4128
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4129
+			throw new EE_Error(
4130
+				sprintf(
4131
+					__(
4132
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4133
+						'event_espresso'
4134
+					),
4135
+					$operator,
4136
+					$operator
4137
+				)
4138
+			);
4139
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4140
+			throw new EE_Error(
4141
+				sprintf(
4142
+					__(
4143
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4144
+						'event_espresso'
4145
+					),
4146
+					$operator,
4147
+					$operator
4148
+				)
4149
+			);
4150
+		} else {
4151
+			throw new EE_Error(
4152
+				sprintf(
4153
+					__(
4154
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4155
+						"event_espresso"
4156
+					),
4157
+					http_build_query($op_and_value)
4158
+				)
4159
+			);
4160
+		}
4161
+	}
4162
+
4163
+
4164
+
4165
+	/**
4166
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4167
+	 *
4168
+	 * @param array                      $values
4169
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4170
+	 *                                              '%s'
4171
+	 * @return string
4172
+	 * @throws EE_Error
4173
+	 */
4174
+	public function _construct_between_value($values, $field_obj)
4175
+	{
4176
+		$cleaned_values = array();
4177
+		foreach ($values as $value) {
4178
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4179
+		}
4180
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Takes an array or a comma-separated list of $values and cleans them
4187
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4188
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4189
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4190
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4191
+	 *
4192
+	 * @param mixed                      $values    array or comma-separated string
4193
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4194
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4195
+	 * @throws EE_Error
4196
+	 */
4197
+	public function _construct_in_value($values, $field_obj)
4198
+	{
4199
+		//check if the value is a CSV list
4200
+		if (is_string($values)) {
4201
+			//in which case, turn it into an array
4202
+			$values = explode(",", $values);
4203
+		}
4204
+		$cleaned_values = array();
4205
+		foreach ($values as $value) {
4206
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4207
+		}
4208
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4209
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4210
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4211
+		if (empty($cleaned_values)) {
4212
+			$all_fields = $this->field_settings();
4213
+			$a_field = array_shift($all_fields);
4214
+			$main_table = $this->_get_main_table();
4215
+			$cleaned_values[] = "SELECT "
4216
+								. $a_field->get_table_column()
4217
+								. " FROM "
4218
+								. $main_table->get_table_name()
4219
+								. " WHERE FALSE";
4220
+		}
4221
+		return "(" . implode(",", $cleaned_values) . ")";
4222
+	}
4223
+
4224
+
4225
+
4226
+	/**
4227
+	 * @param mixed                      $value
4228
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4229
+	 * @throws EE_Error
4230
+	 * @return false|null|string
4231
+	 */
4232
+	private function _wpdb_prepare_using_field($value, $field_obj)
4233
+	{
4234
+		/** @type WPDB $wpdb */
4235
+		global $wpdb;
4236
+		if ($field_obj instanceof EE_Model_Field_Base) {
4237
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4238
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4239
+		} else {//$field_obj should really just be a data type
4240
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4241
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4242
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4243
+			}
4244
+			return $wpdb->prepare($field_obj, $value);
4245
+		}
4246
+	}
4247
+
4248
+
4249
+
4250
+	/**
4251
+	 * Takes the input parameter and finds the model field that it indicates.
4252
+	 *
4253
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4254
+	 * @throws EE_Error
4255
+	 * @return EE_Model_Field_Base
4256
+	 */
4257
+	protected function _deduce_field_from_query_param($query_param_name)
4258
+	{
4259
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4260
+		//which will help us find the database table and column
4261
+		$query_param_parts = explode(".", $query_param_name);
4262
+		if (empty($query_param_parts)) {
4263
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4264
+				'event_espresso'), $query_param_name));
4265
+		}
4266
+		$number_of_parts = count($query_param_parts);
4267
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4268
+		if ($number_of_parts === 1) {
4269
+			$field_name = $last_query_param_part;
4270
+			$model_obj = $this;
4271
+		} else {// $number_of_parts >= 2
4272
+			//the last part is the column name, and there are only 2parts. therefore...
4273
+			$field_name = $last_query_param_part;
4274
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4275
+		}
4276
+		try {
4277
+			return $model_obj->field_settings_for($field_name);
4278
+		} catch (EE_Error $e) {
4279
+			return null;
4280
+		}
4281
+	}
4282
+
4283
+
4284
+
4285
+	/**
4286
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4287
+	 * alias and column which corresponds to it
4288
+	 *
4289
+	 * @param string $field_name
4290
+	 * @throws EE_Error
4291
+	 * @return string
4292
+	 */
4293
+	public function _get_qualified_column_for_field($field_name)
4294
+	{
4295
+		$all_fields = $this->field_settings();
4296
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4297
+		if ($field) {
4298
+			return $field->get_qualified_column();
4299
+		} else {
4300
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4301
+				'event_espresso'), $field_name, get_class($this)));
4302
+		}
4303
+	}
4304
+
4305
+
4306
+
4307
+	/**
4308
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4309
+	 * Example usage:
4310
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4311
+	 *      array(),
4312
+	 *      ARRAY_A,
4313
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4314
+	 *  );
4315
+	 * is equivalent to
4316
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4317
+	 * and
4318
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4319
+	 *      array(
4320
+	 *          array(
4321
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4322
+	 *          ),
4323
+	 *          ARRAY_A,
4324
+	 *          implode(
4325
+	 *              ', ',
4326
+	 *              array_merge(
4327
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4328
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4329
+	 *              )
4330
+	 *          )
4331
+	 *      )
4332
+	 *  );
4333
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4334
+	 *
4335
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4336
+	 *                                            and the one whose fields you are selecting for example: when querying
4337
+	 *                                            tickets model and selecting fields from the tickets model you would
4338
+	 *                                            leave this parameter empty, because no models are needed to join
4339
+	 *                                            between the queried model and the selected one. Likewise when
4340
+	 *                                            querying the datetime model and selecting fields from the tickets
4341
+	 *                                            model, it would also be left empty, because there is a direct
4342
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4343
+	 *                                            them together. However, when querying from the event model and
4344
+	 *                                            selecting fields from the ticket model, you should provide the string
4345
+	 *                                            'Datetime', indicating that the event model must first join to the
4346
+	 *                                            datetime model in order to find its relation to ticket model.
4347
+	 *                                            Also, when querying from the venue model and selecting fields from
4348
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4349
+	 *                                            indicating you need to join the venue model to the event model,
4350
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4351
+	 *                                            This string is used to deduce the prefix that gets added onto the
4352
+	 *                                            models' tables qualified columns
4353
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4354
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4355
+	 *                                            qualified column names
4356
+	 * @return array|string
4357
+	 */
4358
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4359
+	{
4360
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4361
+		$qualified_columns = array();
4362
+		foreach ($this->field_settings() as $field_name => $field) {
4363
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4364
+		}
4365
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4366
+	}
4367
+
4368
+
4369
+
4370
+	/**
4371
+	 * constructs the select use on special limit joins
4372
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4373
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4374
+	 * (as that is typically where the limits would be set).
4375
+	 *
4376
+	 * @param  string       $table_alias The table the select is being built for
4377
+	 * @param  mixed|string $limit       The limit for this select
4378
+	 * @return string                The final select join element for the query.
4379
+	 */
4380
+	public function _construct_limit_join_select($table_alias, $limit)
4381
+	{
4382
+		$SQL = '';
4383
+		foreach ($this->_tables as $table_obj) {
4384
+			if ($table_obj instanceof EE_Primary_Table) {
4385
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4386
+					? $table_obj->get_select_join_limit($limit)
4387
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4388
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4389
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4390
+					? $table_obj->get_select_join_limit_join($limit)
4391
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4392
+			}
4393
+		}
4394
+		return $SQL;
4395
+	}
4396
+
4397
+
4398
+
4399
+	/**
4400
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4401
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4402
+	 *
4403
+	 * @return string SQL
4404
+	 * @throws EE_Error
4405
+	 */
4406
+	public function _construct_internal_join()
4407
+	{
4408
+		$SQL = $this->_get_main_table()->get_table_sql();
4409
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4410
+		return $SQL;
4411
+	}
4412
+
4413
+
4414
+
4415
+	/**
4416
+	 * Constructs the SQL for joining all the tables on this model.
4417
+	 * Normally $alias should be the primary table's alias, but in cases where
4418
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4419
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4420
+	 * alias, this will construct SQL like:
4421
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4423
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
+	 *
4425
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4426
+	 * @return string
4427
+	 */
4428
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4429
+	{
4430
+		$SQL = '';
4431
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4432
+		foreach ($this->_tables as $table_obj) {
4433
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4434
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4435
+					//so we're joining to this table, meaning the table is already in
4436
+					//the FROM statement, BUT the primary table isn't. So we want
4437
+					//to add the inverse join sql
4438
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4439
+				} else {
4440
+					//just add a regular JOIN to this table from the primary table
4441
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4442
+				}
4443
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4444
+		}
4445
+		return $SQL;
4446
+	}
4447
+
4448
+
4449
+
4450
+	/**
4451
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4452
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4453
+	 * their data type (eg, '%s', '%d', etc)
4454
+	 *
4455
+	 * @return array
4456
+	 */
4457
+	public function _get_data_types()
4458
+	{
4459
+		$data_types = array();
4460
+		foreach ($this->field_settings() as $field_obj) {
4461
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4462
+			/** @var $field_obj EE_Model_Field_Base */
4463
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4464
+		}
4465
+		return $data_types;
4466
+	}
4467
+
4468
+
4469
+
4470
+	/**
4471
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4472
+	 *
4473
+	 * @param string $model_name
4474
+	 * @throws EE_Error
4475
+	 * @return EEM_Base
4476
+	 */
4477
+	public function get_related_model_obj($model_name)
4478
+	{
4479
+		$model_classname = "EEM_" . $model_name;
4480
+		if (! class_exists($model_classname)) {
4481
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4482
+				'event_espresso'), $model_name, $model_classname));
4483
+		}
4484
+		return call_user_func($model_classname . "::instance");
4485
+	}
4486
+
4487
+
4488
+
4489
+	/**
4490
+	 * Returns the array of EE_ModelRelations for this model.
4491
+	 *
4492
+	 * @return EE_Model_Relation_Base[]
4493
+	 */
4494
+	public function relation_settings()
4495
+	{
4496
+		return $this->_model_relations;
4497
+	}
4498
+
4499
+
4500
+
4501
+	/**
4502
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4503
+	 * because without THOSE models, this model probably doesn't have much purpose.
4504
+	 * (Eg, without an event, datetimes have little purpose.)
4505
+	 *
4506
+	 * @return EE_Belongs_To_Relation[]
4507
+	 */
4508
+	public function belongs_to_relations()
4509
+	{
4510
+		$belongs_to_relations = array();
4511
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4512
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4513
+				$belongs_to_relations[$model_name] = $relation_obj;
4514
+			}
4515
+		}
4516
+		return $belongs_to_relations;
4517
+	}
4518
+
4519
+
4520
+
4521
+	/**
4522
+	 * Returns the specified EE_Model_Relation, or throws an exception
4523
+	 *
4524
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4525
+	 * @throws EE_Error
4526
+	 * @return EE_Model_Relation_Base
4527
+	 */
4528
+	public function related_settings_for($relation_name)
4529
+	{
4530
+		$relatedModels = $this->relation_settings();
4531
+		if (! array_key_exists($relation_name, $relatedModels)) {
4532
+			throw new EE_Error(
4533
+				sprintf(
4534
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4535
+						'event_espresso'),
4536
+					$relation_name,
4537
+					$this->_get_class_name(),
4538
+					implode(', ', array_keys($relatedModels))
4539
+				)
4540
+			);
4541
+		}
4542
+		return $relatedModels[$relation_name];
4543
+	}
4544
+
4545
+
4546
+
4547
+	/**
4548
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4549
+	 * fields
4550
+	 *
4551
+	 * @param string $fieldName
4552
+	 * @throws EE_Error
4553
+	 * @return EE_Model_Field_Base
4554
+	 */
4555
+	public function field_settings_for($fieldName)
4556
+	{
4557
+		$fieldSettings = $this->field_settings(true);
4558
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4559
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4560
+				get_class($this)));
4561
+		}
4562
+		return $fieldSettings[$fieldName];
4563
+	}
4564
+
4565
+
4566
+
4567
+	/**
4568
+	 * Checks if this field exists on this model
4569
+	 *
4570
+	 * @param string $fieldName a key in the model's _field_settings array
4571
+	 * @return boolean
4572
+	 */
4573
+	public function has_field($fieldName)
4574
+	{
4575
+		$fieldSettings = $this->field_settings(true);
4576
+		if (isset($fieldSettings[$fieldName])) {
4577
+			return true;
4578
+		} else {
4579
+			return false;
4580
+		}
4581
+	}
4582
+
4583
+
4584
+
4585
+	/**
4586
+	 * Returns whether or not this model has a relation to the specified model
4587
+	 *
4588
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4589
+	 * @return boolean
4590
+	 */
4591
+	public function has_relation($relation_name)
4592
+	{
4593
+		$relations = $this->relation_settings();
4594
+		if (isset($relations[$relation_name])) {
4595
+			return true;
4596
+		} else {
4597
+			return false;
4598
+		}
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4605
+	 * Eg, on EE_Answer that would be ANS_ID field object
4606
+	 *
4607
+	 * @param $field_obj
4608
+	 * @return boolean
4609
+	 */
4610
+	public function is_primary_key_field($field_obj)
4611
+	{
4612
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4613
+	}
4614
+
4615
+
4616
+
4617
+	/**
4618
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4619
+	 * Eg, on EE_Answer that would be ANS_ID field object
4620
+	 *
4621
+	 * @return EE_Model_Field_Base
4622
+	 * @throws EE_Error
4623
+	 */
4624
+	public function get_primary_key_field()
4625
+	{
4626
+		if ($this->_primary_key_field === null) {
4627
+			foreach ($this->field_settings(true) as $field_obj) {
4628
+				if ($this->is_primary_key_field($field_obj)) {
4629
+					$this->_primary_key_field = $field_obj;
4630
+					break;
4631
+				}
4632
+			}
4633
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4634
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4635
+					get_class($this)));
4636
+			}
4637
+		}
4638
+		return $this->_primary_key_field;
4639
+	}
4640
+
4641
+
4642
+
4643
+	/**
4644
+	 * Returns whether or not not there is a primary key on this model.
4645
+	 * Internally does some caching.
4646
+	 *
4647
+	 * @return boolean
4648
+	 */
4649
+	public function has_primary_key_field()
4650
+	{
4651
+		if ($this->_has_primary_key_field === null) {
4652
+			try {
4653
+				$this->get_primary_key_field();
4654
+				$this->_has_primary_key_field = true;
4655
+			} catch (EE_Error $e) {
4656
+				$this->_has_primary_key_field = false;
4657
+			}
4658
+		}
4659
+		return $this->_has_primary_key_field;
4660
+	}
4661
+
4662
+
4663
+
4664
+	/**
4665
+	 * Finds the first field of type $field_class_name.
4666
+	 *
4667
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4668
+	 *                                 EE_Foreign_Key_Field, etc
4669
+	 * @return EE_Model_Field_Base or null if none is found
4670
+	 */
4671
+	public function get_a_field_of_type($field_class_name)
4672
+	{
4673
+		foreach ($this->field_settings() as $field) {
4674
+			if ($field instanceof $field_class_name) {
4675
+				return $field;
4676
+			}
4677
+		}
4678
+		return null;
4679
+	}
4680
+
4681
+
4682
+
4683
+	/**
4684
+	 * Gets a foreign key field pointing to model.
4685
+	 *
4686
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4687
+	 * @return EE_Foreign_Key_Field_Base
4688
+	 * @throws EE_Error
4689
+	 */
4690
+	public function get_foreign_key_to($model_name)
4691
+	{
4692
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
+			foreach ($this->field_settings() as $field) {
4694
+				if (
4695
+					$field instanceof EE_Foreign_Key_Field_Base
4696
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4697
+				) {
4698
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4699
+					break;
4700
+				}
4701
+			}
4702
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4703
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4704
+					'event_espresso'), $model_name, get_class($this)));
4705
+			}
4706
+		}
4707
+		return $this->_cache_foreign_key_to_fields[$model_name];
4708
+	}
4709
+
4710
+
4711
+
4712
+	/**
4713
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4714
+	 *
4715
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4716
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4717
+	 *                            Either one works
4718
+	 * @return string
4719
+	 */
4720
+	public function get_table_for_alias($table_alias)
4721
+	{
4722
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4723
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4724
+	}
4725
+
4726
+
4727
+
4728
+	/**
4729
+	 * Returns a flat array of all field son this model, instead of organizing them
4730
+	 * by table_alias as they are in the constructor.
4731
+	 *
4732
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4733
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4734
+	 */
4735
+	public function field_settings($include_db_only_fields = false)
4736
+	{
4737
+		if ($include_db_only_fields) {
4738
+			if ($this->_cached_fields === null) {
4739
+				$this->_cached_fields = array();
4740
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4741
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
+						$this->_cached_fields[$field_name] = $field_obj;
4743
+					}
4744
+				}
4745
+			}
4746
+			return $this->_cached_fields;
4747
+		} else {
4748
+			if ($this->_cached_fields_non_db_only === null) {
4749
+				$this->_cached_fields_non_db_only = array();
4750
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4751
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4752
+						/** @var $field_obj EE_Model_Field_Base */
4753
+						if (! $field_obj->is_db_only_field()) {
4754
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4755
+						}
4756
+					}
4757
+				}
4758
+			}
4759
+			return $this->_cached_fields_non_db_only;
4760
+		}
4761
+	}
4762
+
4763
+
4764
+
4765
+	/**
4766
+	 *        cycle though array of attendees and create objects out of each item
4767
+	 *
4768
+	 * @access        private
4769
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4770
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4771
+	 *                           numerically indexed)
4772
+	 * @throws EE_Error
4773
+	 */
4774
+	protected function _create_objects($rows = array())
4775
+	{
4776
+		$array_of_objects = array();
4777
+		if (empty($rows)) {
4778
+			return array();
4779
+		}
4780
+		$count_if_model_has_no_primary_key = 0;
4781
+		$has_primary_key = $this->has_primary_key_field();
4782
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4783
+		foreach ((array)$rows as $row) {
4784
+			if (empty($row)) {
4785
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4786
+				return array();
4787
+			}
4788
+			//check if we've already set this object in the results array,
4789
+			//in which case there's no need to process it further (again)
4790
+			if ($has_primary_key) {
4791
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4792
+					$row,
4793
+					$primary_key_field->get_qualified_column(),
4794
+					$primary_key_field->get_table_column()
4795
+				);
4796
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4797
+					continue;
4798
+				}
4799
+			}
4800
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4801
+			if (! $classInstance) {
4802
+				throw new EE_Error(
4803
+					sprintf(
4804
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4805
+						$this->get_this_model_name(),
4806
+						http_build_query($row)
4807
+					)
4808
+				);
4809
+			}
4810
+			//set the timezone on the instantiated objects
4811
+			$classInstance->set_timezone($this->_timezone);
4812
+			//make sure if there is any timezone setting present that we set the timezone for the object
4813
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4814
+			$array_of_objects[$key] = $classInstance;
4815
+			//also, for all the relations of type BelongsTo, see if we can cache
4816
+			//those related models
4817
+			//(we could do this for other relations too, but if there are conditions
4818
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4819
+			//so it requires a little more thought than just caching them immediately...)
4820
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4821
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4822
+					//check if this model's INFO is present. If so, cache it on the model
4823
+					$other_model = $relation_obj->get_other_model();
4824
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4825
+					//if we managed to make a model object from the results, cache it on the main model object
4826
+					if ($other_model_obj_maybe) {
4827
+						//set timezone on these other model objects if they are present
4828
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4829
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4830
+					}
4831
+				}
4832
+			}
4833
+		}
4834
+		return $array_of_objects;
4835
+	}
4836
+
4837
+
4838
+
4839
+	/**
4840
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4841
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4842
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4843
+	 * object (as set in the model_field!).
4844
+	 *
4845
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4846
+	 * @throws Exception
4847
+	 */
4848
+	public function create_default_object()
4849
+	{
4850
+		$this_model_fields_and_values = array();
4851
+		//setup the row using default values;
4852
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4853
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4854
+		}
4855
+		$classInstance = $this->_instantiate_new_instance_from_db(
4856
+			$this->_get_class_name(),
4857
+			$this_model_fields_and_values
4858
+		);
4859
+		return $classInstance;
4860
+	}
4861
+
4862
+
4863
+
4864
+	/**
4865
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4866
+	 *                             or an stdClass where each property is the name of a column,
4867
+	 * @return EE_Base_Class
4868
+	 * @throws Exception
4869
+	 * @throws EE_Error
4870
+	 */
4871
+	public function instantiate_class_from_array_or_object($cols_n_values)
4872
+	{
4873
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4874
+			$cols_n_values = get_object_vars($cols_n_values);
4875
+		}
4876
+		$primary_key = null;
4877
+		//make sure the array only has keys that are fields/columns on this model
4878
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4879
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4880
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4881
+		}
4882
+		//check we actually found results that we can use to build our model object
4883
+		//if not, return null
4884
+		if ($this->has_primary_key_field()) {
4885
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4886
+				return null;
4887
+			}
4888
+		} else if ($this->unique_indexes()) {
4889
+			$first_column = reset($this_model_fields_n_values);
4890
+			if (empty($first_column)) {
4891
+				return null;
4892
+			}
4893
+		}
4894
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4895
+		if ($primary_key) {
4896
+			$classInstance = $this->get_from_entity_map($primary_key);
4897
+			if (! $classInstance) {
4898
+				$classInstance = $this->_instantiate_new_instance_from_db(
4899
+					$this->_get_class_name(),
4900
+					$this_model_fields_n_values
4901
+				);
4902
+				// add this new object to the entity map
4903
+				$classInstance = $this->add_to_entity_map($classInstance);
4904
+			}
4905
+		} else {
4906
+			$classInstance = $this->_instantiate_new_instance_from_db(
4907
+				$this->_get_class_name(),
4908
+				$this_model_fields_n_values
4909
+			);
4910
+		}
4911
+		// it is entirely possible that the instantiated class object has a set
4912
+		// timezone_string db field and has set it's internal _timezone property accordingly
4913
+		// (see new_instance_from_db in model objects particularly EE_Event for example).
4914
+		// In this case, we want to make sure the model object doesn't have its timezone string
4915
+		// overwritten by any timezone property currently set here on the model so,
4916
+		// we intentionally override the model _timezone property with the model_object timezone property.
4917
+		$this->set_timezone($classInstance->get_timezone());
4918
+		return $classInstance;
4919
+	}
4920
+
4921
+
4922
+
4923
+	/**
4924
+	 * Gets the model object from the  entity map if it exists
4925
+	 *
4926
+	 * @param int|string $id the ID of the model object
4927
+	 * @return EE_Base_Class
4928
+	 */
4929
+	public function get_from_entity_map($id)
4930
+	{
4931
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4932
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4933
+	}
4934
+
4935
+
4936
+
4937
+	/**
4938
+	 * add_to_entity_map
4939
+	 * Adds the object to the model's entity mappings
4940
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4941
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4942
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4943
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4944
+	 *        then this method should be called immediately after the update query
4945
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4946
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4947
+	 *
4948
+	 * @param    EE_Base_Class $object
4949
+	 * @throws EE_Error
4950
+	 * @return \EE_Base_Class
4951
+	 */
4952
+	public function add_to_entity_map(EE_Base_Class $object)
4953
+	{
4954
+		$className = $this->_get_class_name();
4955
+		if (! $object instanceof $className) {
4956
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4957
+				is_object($object) ? get_class($object) : $object, $className));
4958
+		}
4959
+		/** @var $object EE_Base_Class */
4960
+		if (! $object->ID()) {
4961
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4962
+				"event_espresso"), get_class($this)));
4963
+		}
4964
+		// double check it's not already there
4965
+		$classInstance = $this->get_from_entity_map($object->ID());
4966
+		if ($classInstance) {
4967
+			return $classInstance;
4968
+		} else {
4969
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4970
+			return $object;
4971
+		}
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4978
+	 * if no identifier is provided, then the entire entity map is emptied
4979
+	 *
4980
+	 * @param int|string $id the ID of the model object
4981
+	 * @return boolean
4982
+	 */
4983
+	public function clear_entity_map($id = null)
4984
+	{
4985
+		if (empty($id)) {
4986
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4987
+			return true;
4988
+		}
4989
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4990
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4991
+			return true;
4992
+		}
4993
+		return false;
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5000
+	 * Given an array where keys are column (or column alias) names and values,
5001
+	 * returns an array of their corresponding field names and database values
5002
+	 *
5003
+	 * @param array $cols_n_values
5004
+	 * @return array
5005
+	 */
5006
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
+	{
5008
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5009
+	}
5010
+
5011
+
5012
+
5013
+	/**
5014
+	 * _deduce_fields_n_values_from_cols_n_values
5015
+	 * Given an array where keys are column (or column alias) names and values,
5016
+	 * returns an array of their corresponding field names and database values
5017
+	 *
5018
+	 * @param string $cols_n_values
5019
+	 * @return array
5020
+	 */
5021
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5022
+	{
5023
+		$this_model_fields_n_values = array();
5024
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5025
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5026
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5027
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5028
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5029
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5030
+					if (! $field_obj->is_db_only_field()) {
5031
+						//prepare field as if its coming from db
5032
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5033
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5034
+					}
5035
+				}
5036
+			} else {
5037
+				//the table's rows existed. Use their values
5038
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5039
+					if (! $field_obj->is_db_only_field()) {
5040
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5041
+							$cols_n_values, $field_obj->get_qualified_column(),
5042
+							$field_obj->get_table_column()
5043
+						);
5044
+					}
5045
+				}
5046
+			}
5047
+		}
5048
+		return $this_model_fields_n_values;
5049
+	}
5050
+
5051
+
5052
+
5053
+	/**
5054
+	 * @param $cols_n_values
5055
+	 * @param $qualified_column
5056
+	 * @param $regular_column
5057
+	 * @return null
5058
+	 */
5059
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5060
+	{
5061
+		$value = null;
5062
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5063
+		//does the field on the model relate to this column retrieved from the db?
5064
+		//or is it a db-only field? (not relating to the model)
5065
+		if (isset($cols_n_values[$qualified_column])) {
5066
+			$value = $cols_n_values[$qualified_column];
5067
+		} elseif (isset($cols_n_values[$regular_column])) {
5068
+			$value = $cols_n_values[$regular_column];
5069
+		}
5070
+		return $value;
5071
+	}
5072
+
5073
+
5074
+
5075
+	/**
5076
+	 * refresh_entity_map_from_db
5077
+	 * Makes sure the model object in the entity map at $id assumes the values
5078
+	 * of the database (opposite of EE_base_Class::save())
5079
+	 *
5080
+	 * @param int|string $id
5081
+	 * @return EE_Base_Class
5082
+	 * @throws EE_Error
5083
+	 */
5084
+	public function refresh_entity_map_from_db($id)
5085
+	{
5086
+		$obj_in_map = $this->get_from_entity_map($id);
5087
+		if ($obj_in_map) {
5088
+			$wpdb_results = $this->_get_all_wpdb_results(
5089
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5090
+			);
5091
+			if ($wpdb_results && is_array($wpdb_results)) {
5092
+				$one_row = reset($wpdb_results);
5093
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5094
+					$obj_in_map->set_from_db($field_name, $db_value);
5095
+				}
5096
+				//clear the cache of related model objects
5097
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5098
+					$obj_in_map->clear_cache($relation_name, null, true);
5099
+				}
5100
+			}
5101
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5102
+			return $obj_in_map;
5103
+		} else {
5104
+			return $this->get_one_by_ID($id);
5105
+		}
5106
+	}
5107
+
5108
+
5109
+
5110
+	/**
5111
+	 * refresh_entity_map_with
5112
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5113
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5114
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5115
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5116
+	 *
5117
+	 * @param int|string    $id
5118
+	 * @param EE_Base_Class $replacing_model_obj
5119
+	 * @return \EE_Base_Class
5120
+	 * @throws EE_Error
5121
+	 */
5122
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5123
+	{
5124
+		$obj_in_map = $this->get_from_entity_map($id);
5125
+		if ($obj_in_map) {
5126
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5127
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5128
+					$obj_in_map->set($field_name, $value);
5129
+				}
5130
+				//make the model object in the entity map's cache match the $replacing_model_obj
5131
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5132
+					$obj_in_map->clear_cache($relation_name, null, true);
5133
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5134
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5135
+					}
5136
+				}
5137
+			}
5138
+			return $obj_in_map;
5139
+		} else {
5140
+			$this->add_to_entity_map($replacing_model_obj);
5141
+			return $replacing_model_obj;
5142
+		}
5143
+	}
5144
+
5145
+
5146
+
5147
+	/**
5148
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5149
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5150
+	 * require_once($this->_getClassName().".class.php");
5151
+	 *
5152
+	 * @return string
5153
+	 */
5154
+	private function _get_class_name()
5155
+	{
5156
+		return "EE_" . $this->get_this_model_name();
5157
+	}
5158
+
5159
+
5160
+
5161
+	/**
5162
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5163
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5164
+	 * it would be 'Events'.
5165
+	 *
5166
+	 * @param int $quantity
5167
+	 * @return string
5168
+	 */
5169
+	public function item_name($quantity = 1)
5170
+	{
5171
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5172
+	}
5173
+
5174
+
5175
+
5176
+	/**
5177
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5178
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5179
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5180
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5181
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5182
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5183
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5184
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5185
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5186
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5187
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5188
+	 *        return $previousReturnValue.$returnString;
5189
+	 * }
5190
+	 * require('EEM_Answer.model.php');
5191
+	 * $answer=EEM_Answer::instance();
5192
+	 * echo $answer->my_callback('monkeys',100);
5193
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5194
+	 *
5195
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5196
+	 * @param array  $args       array of original arguments passed to the function
5197
+	 * @throws EE_Error
5198
+	 * @return mixed whatever the plugin which calls add_filter decides
5199
+	 */
5200
+	public function __call($methodName, $args)
5201
+	{
5202
+		$className = get_class($this);
5203
+		$tagName = "FHEE__{$className}__{$methodName}";
5204
+		if (! has_filter($tagName)) {
5205
+			throw new EE_Error(
5206
+				sprintf(
5207
+					__('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5208
+						'event_espresso'),
5209
+					$methodName,
5210
+					$className,
5211
+					$tagName,
5212
+					'<br />'
5213
+				)
5214
+			);
5215
+		}
5216
+		return apply_filters($tagName, null, $this, $args);
5217
+	}
5218
+
5219
+
5220
+
5221
+	/**
5222
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5223
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5224
+	 *
5225
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5226
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5227
+	 *                                                       the object's class name
5228
+	 *                                                       or object's ID
5229
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5230
+	 *                                                       exists in the database. If it does not, we add it
5231
+	 * @throws EE_Error
5232
+	 * @return EE_Base_Class
5233
+	 */
5234
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5235
+	{
5236
+		$className = $this->_get_class_name();
5237
+		if ($base_class_obj_or_id instanceof $className) {
5238
+			$model_object = $base_class_obj_or_id;
5239
+		} else {
5240
+			$primary_key_field = $this->get_primary_key_field();
5241
+			if (
5242
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5243
+				&& (
5244
+					is_int($base_class_obj_or_id)
5245
+					|| is_string($base_class_obj_or_id)
5246
+				)
5247
+			) {
5248
+				// assume it's an ID.
5249
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5250
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5251
+			} else if (
5252
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5253
+				&& is_string($base_class_obj_or_id)
5254
+			) {
5255
+				// assume its a string representation of the object
5256
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5257
+			} else {
5258
+				throw new EE_Error(
5259
+					sprintf(
5260
+						__(
5261
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5262
+							'event_espresso'
5263
+						),
5264
+						$base_class_obj_or_id,
5265
+						$this->_get_class_name(),
5266
+						print_r($base_class_obj_or_id, true)
5267
+					)
5268
+				);
5269
+			}
5270
+		}
5271
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5272
+			$model_object->save();
5273
+		}
5274
+		return $model_object;
5275
+	}
5276
+
5277
+
5278
+
5279
+	/**
5280
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5281
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5282
+	 * returns it ID.
5283
+	 *
5284
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5285
+	 * @return int|string depending on the type of this model object's ID
5286
+	 * @throws EE_Error
5287
+	 */
5288
+	public function ensure_is_ID($base_class_obj_or_id)
5289
+	{
5290
+		$className = $this->_get_class_name();
5291
+		if ($base_class_obj_or_id instanceof $className) {
5292
+			/** @var $base_class_obj_or_id EE_Base_Class */
5293
+			$id = $base_class_obj_or_id->ID();
5294
+		} elseif (is_int($base_class_obj_or_id)) {
5295
+			//assume it's an ID
5296
+			$id = $base_class_obj_or_id;
5297
+		} elseif (is_string($base_class_obj_or_id)) {
5298
+			//assume its a string representation of the object
5299
+			$id = $base_class_obj_or_id;
5300
+		} else {
5301
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5302
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5303
+				print_r($base_class_obj_or_id, true)));
5304
+		}
5305
+		return $id;
5306
+	}
5307
+
5308
+
5309
+
5310
+	/**
5311
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5312
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5313
+	 * been sanitized and converted into the appropriate domain.
5314
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5315
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5316
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5317
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5318
+	 * $EVT = EEM_Event::instance(); $old_setting =
5319
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5320
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5321
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5322
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5323
+	 *
5324
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5325
+	 * @return void
5326
+	 */
5327
+	public function assume_values_already_prepared_by_model_object(
5328
+		$values_already_prepared = self::not_prepared_by_model_object
5329
+	) {
5330
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5331
+	}
5332
+
5333
+
5334
+
5335
+	/**
5336
+	 * Read comments for assume_values_already_prepared_by_model_object()
5337
+	 *
5338
+	 * @return int
5339
+	 */
5340
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5341
+	{
5342
+		return $this->_values_already_prepared_by_model_object;
5343
+	}
5344
+
5345
+
5346
+
5347
+	/**
5348
+	 * Gets all the indexes on this model
5349
+	 *
5350
+	 * @return EE_Index[]
5351
+	 */
5352
+	public function indexes()
5353
+	{
5354
+		return $this->_indexes;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * Gets all the Unique Indexes on this model
5361
+	 *
5362
+	 * @return EE_Unique_Index[]
5363
+	 */
5364
+	public function unique_indexes()
5365
+	{
5366
+		$unique_indexes = array();
5367
+		foreach ($this->_indexes as $name => $index) {
5368
+			if ($index instanceof EE_Unique_Index) {
5369
+				$unique_indexes [$name] = $index;
5370
+			}
5371
+		}
5372
+		return $unique_indexes;
5373
+	}
5374
+
5375
+
5376
+
5377
+	/**
5378
+	 * Gets all the fields which, when combined, make the primary key.
5379
+	 * This is usually just an array with 1 element (the primary key), but in cases
5380
+	 * where there is no primary key, it's a combination of fields as defined
5381
+	 * on a primary index
5382
+	 *
5383
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5384
+	 * @throws EE_Error
5385
+	 */
5386
+	public function get_combined_primary_key_fields()
5387
+	{
5388
+		foreach ($this->indexes() as $index) {
5389
+			if ($index instanceof EE_Primary_Key_Index) {
5390
+				return $index->fields();
5391
+			}
5392
+		}
5393
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * Used to build a primary key string (when the model has no primary key),
5400
+	 * which can be used a unique string to identify this model object.
5401
+	 *
5402
+	 * @param array $cols_n_values keys are field names, values are their values
5403
+	 * @return string
5404
+	 * @throws EE_Error
5405
+	 */
5406
+	public function get_index_primary_key_string($cols_n_values)
5407
+	{
5408
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5409
+			$this->get_combined_primary_key_fields());
5410
+		return http_build_query($cols_n_values_for_primary_key_index);
5411
+	}
5412
+
5413
+
5414
+
5415
+	/**
5416
+	 * Gets the field values from the primary key string
5417
+	 *
5418
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5419
+	 * @param string $index_primary_key_string
5420
+	 * @return null|array
5421
+	 * @throws EE_Error
5422
+	 */
5423
+	public function parse_index_primary_key_string($index_primary_key_string)
5424
+	{
5425
+		$key_fields = $this->get_combined_primary_key_fields();
5426
+		//check all of them are in the $id
5427
+		$key_vals_in_combined_pk = array();
5428
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5429
+		foreach ($key_fields as $key_field_name => $field_obj) {
5430
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5431
+				return null;
5432
+			}
5433
+		}
5434
+		return $key_vals_in_combined_pk;
5435
+	}
5436
+
5437
+
5438
+
5439
+	/**
5440
+	 * verifies that an array of key-value pairs for model fields has a key
5441
+	 * for each field comprising the primary key index
5442
+	 *
5443
+	 * @param array $key_vals
5444
+	 * @return boolean
5445
+	 * @throws EE_Error
5446
+	 */
5447
+	public function has_all_combined_primary_key_fields($key_vals)
5448
+	{
5449
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5450
+		foreach ($keys_it_should_have as $key) {
5451
+			if (! isset($key_vals[$key])) {
5452
+				return false;
5453
+			}
5454
+		}
5455
+		return true;
5456
+	}
5457
+
5458
+
5459
+
5460
+	/**
5461
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5462
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5463
+	 *
5464
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5465
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5466
+	 * @throws EE_Error
5467
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5468
+	 *                                                              indexed)
5469
+	 */
5470
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5471
+	{
5472
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5473
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5474
+		} elseif (is_array($model_object_or_attributes_array)) {
5475
+			$attributes_array = $model_object_or_attributes_array;
5476
+		} else {
5477
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5478
+				"event_espresso"), $model_object_or_attributes_array));
5479
+		}
5480
+		//even copies obviously won't have the same ID, so remove the primary key
5481
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5482
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5483
+			unset($attributes_array[$this->primary_key_name()]);
5484
+		}
5485
+		if (isset($query_params[0])) {
5486
+			$query_params[0] = array_merge($attributes_array, $query_params);
5487
+		} else {
5488
+			$query_params[0] = $attributes_array;
5489
+		}
5490
+		return $this->get_all($query_params);
5491
+	}
5492
+
5493
+
5494
+
5495
+	/**
5496
+	 * Gets the first copy we find. See get_all_copies for more details
5497
+	 *
5498
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5499
+	 * @param array $query_params
5500
+	 * @return EE_Base_Class
5501
+	 * @throws EE_Error
5502
+	 */
5503
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5504
+	{
5505
+		if (! is_array($query_params)) {
5506
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5507
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5508
+					gettype($query_params)), '4.6.0');
5509
+			$query_params = array();
5510
+		}
5511
+		$query_params['limit'] = 1;
5512
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5513
+		if (is_array($copies)) {
5514
+			return array_shift($copies);
5515
+		} else {
5516
+			return null;
5517
+		}
5518
+	}
5519
+
5520
+
5521
+
5522
+	/**
5523
+	 * Updates the item with the specified id. Ignores default query parameters because
5524
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5525
+	 *
5526
+	 * @param array      $fields_n_values keys are field names, values are their new values
5527
+	 * @param int|string $id              the value of the primary key to update
5528
+	 * @return int number of rows updated
5529
+	 * @throws EE_Error
5530
+	 */
5531
+	public function update_by_ID($fields_n_values, $id)
5532
+	{
5533
+		$query_params = array(
5534
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5535
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5536
+		);
5537
+		return $this->update($fields_n_values, $query_params);
5538
+	}
5539
+
5540
+
5541
+
5542
+	/**
5543
+	 * Changes an operator which was supplied to the models into one usable in SQL
5544
+	 *
5545
+	 * @param string $operator_supplied
5546
+	 * @return string an operator which can be used in SQL
5547
+	 * @throws EE_Error
5548
+	 */
5549
+	private function _prepare_operator_for_sql($operator_supplied)
5550
+	{
5551
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5552
+			: null;
5553
+		if ($sql_operator) {
5554
+			return $sql_operator;
5555
+		} else {
5556
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5557
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5558
+		}
5559
+	}
5560
+
5561
+
5562
+
5563
+	/**
5564
+	 * Gets an array where keys are the primary keys and values are their 'names'
5565
+	 * (as determined by the model object's name() function, which is often overridden)
5566
+	 *
5567
+	 * @param array $query_params like get_all's
5568
+	 * @return string[]
5569
+	 * @throws EE_Error
5570
+	 */
5571
+	public function get_all_names($query_params = array())
5572
+	{
5573
+		$objs = $this->get_all($query_params);
5574
+		$names = array();
5575
+		foreach ($objs as $obj) {
5576
+			$names[$obj->ID()] = $obj->name();
5577
+		}
5578
+		return $names;
5579
+	}
5580
+
5581
+
5582
+
5583
+	/**
5584
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5585
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5586
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5587
+	 * array_keys() on $model_objects.
5588
+	 *
5589
+	 * @param \EE_Base_Class[] $model_objects
5590
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5591
+	 *                                               in the returned array
5592
+	 * @return array
5593
+	 * @throws EE_Error
5594
+	 */
5595
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5596
+	{
5597
+		if (! $this->has_primary_key_field()) {
5598
+			if (WP_DEBUG) {
5599
+				EE_Error::add_error(
5600
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5601
+					__FILE__,
5602
+					__FUNCTION__,
5603
+					__LINE__
5604
+				);
5605
+			}
5606
+		}
5607
+		$IDs = array();
5608
+		foreach ($model_objects as $model_object) {
5609
+			$id = $model_object->ID();
5610
+			if (! $id) {
5611
+				if ($filter_out_empty_ids) {
5612
+					continue;
5613
+				}
5614
+				if (WP_DEBUG) {
5615
+					EE_Error::add_error(
5616
+						__(
5617
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5618
+							'event_espresso'
5619
+						),
5620
+						__FILE__,
5621
+						__FUNCTION__,
5622
+						__LINE__
5623
+					);
5624
+				}
5625
+			}
5626
+			$IDs[] = $id;
5627
+		}
5628
+		return $IDs;
5629
+	}
5630
+
5631
+
5632
+
5633
+	/**
5634
+	 * Returns the string used in capabilities relating to this model. If there
5635
+	 * are no capabilities that relate to this model returns false
5636
+	 *
5637
+	 * @return string|false
5638
+	 */
5639
+	public function cap_slug()
5640
+	{
5641
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5642
+	}
5643
+
5644
+
5645
+
5646
+	/**
5647
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5648
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5649
+	 * only returns the cap restrictions array in that context (ie, the array
5650
+	 * at that key)
5651
+	 *
5652
+	 * @param string $context
5653
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5654
+	 * @throws EE_Error
5655
+	 */
5656
+	public function cap_restrictions($context = EEM_Base::caps_read)
5657
+	{
5658
+		EEM_Base::verify_is_valid_cap_context($context);
5659
+		//check if we ought to run the restriction generator first
5660
+		if (
5661
+			isset($this->_cap_restriction_generators[$context])
5662
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5663
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5664
+		) {
5665
+			$this->_cap_restrictions[$context] = array_merge(
5666
+				$this->_cap_restrictions[$context],
5667
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5668
+			);
5669
+		}
5670
+		//and make sure we've finalized the construction of each restriction
5671
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5672
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5673
+				$where_conditions_obj->_finalize_construct($this);
5674
+			}
5675
+		}
5676
+		return $this->_cap_restrictions[$context];
5677
+	}
5678
+
5679
+
5680
+
5681
+	/**
5682
+	 * Indicating whether or not this model thinks its a wp core model
5683
+	 *
5684
+	 * @return boolean
5685
+	 */
5686
+	public function is_wp_core_model()
5687
+	{
5688
+		return $this->_wp_core_model;
5689
+	}
5690
+
5691
+
5692
+
5693
+	/**
5694
+	 * Gets all the caps that are missing which impose a restriction on
5695
+	 * queries made in this context
5696
+	 *
5697
+	 * @param string $context one of EEM_Base::caps_ constants
5698
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5699
+	 * @throws EE_Error
5700
+	 */
5701
+	public function caps_missing($context = EEM_Base::caps_read)
5702
+	{
5703
+		$missing_caps = array();
5704
+		$cap_restrictions = $this->cap_restrictions($context);
5705
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5706
+			if (! EE_Capabilities::instance()
5707
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5708
+			) {
5709
+				$missing_caps[$cap] = $restriction_if_no_cap;
5710
+			}
5711
+		}
5712
+		return $missing_caps;
5713
+	}
5714
+
5715
+
5716
+
5717
+	/**
5718
+	 * Gets the mapping from capability contexts to action strings used in capability names
5719
+	 *
5720
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5721
+	 * one of 'read', 'edit', or 'delete'
5722
+	 */
5723
+	public function cap_contexts_to_cap_action_map()
5724
+	{
5725
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5726
+			$this);
5727
+	}
5728
+
5729
+
5730
+
5731
+	/**
5732
+	 * Gets the action string for the specified capability context
5733
+	 *
5734
+	 * @param string $context
5735
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5736
+	 * @throws EE_Error
5737
+	 */
5738
+	public function cap_action_for_context($context)
5739
+	{
5740
+		$mapping = $this->cap_contexts_to_cap_action_map();
5741
+		if (isset($mapping[$context])) {
5742
+			return $mapping[$context];
5743
+		}
5744
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5745
+			return $action;
5746
+		}
5747
+		throw new EE_Error(
5748
+			sprintf(
5749
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5750
+				$context,
5751
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5752
+			)
5753
+		);
5754
+	}
5755
+
5756
+
5757
+
5758
+	/**
5759
+	 * Returns all the capability contexts which are valid when querying models
5760
+	 *
5761
+	 * @return array
5762
+	 */
5763
+	public static function valid_cap_contexts()
5764
+	{
5765
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5766
+			self::caps_read,
5767
+			self::caps_read_admin,
5768
+			self::caps_edit,
5769
+			self::caps_delete,
5770
+		));
5771
+	}
5772
+
5773
+
5774
+
5775
+	/**
5776
+	 * Returns all valid options for 'default_where_conditions'
5777
+	 *
5778
+	 * @return array
5779
+	 */
5780
+	public static function valid_default_where_conditions()
5781
+	{
5782
+		return array(
5783
+			EEM_Base::default_where_conditions_all,
5784
+			EEM_Base::default_where_conditions_this_only,
5785
+			EEM_Base::default_where_conditions_others_only,
5786
+			EEM_Base::default_where_conditions_minimum_all,
5787
+			EEM_Base::default_where_conditions_minimum_others,
5788
+			EEM_Base::default_where_conditions_none
5789
+		);
5790
+	}
5791
+
5792
+	// public static function default_where_conditions_full
5793
+	/**
5794
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5795
+	 *
5796
+	 * @param string $context
5797
+	 * @return bool
5798
+	 * @throws EE_Error
5799
+	 */
5800
+	static public function verify_is_valid_cap_context($context)
5801
+	{
5802
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5803
+		if (in_array($context, $valid_cap_contexts)) {
5804
+			return true;
5805
+		} else {
5806
+			throw new EE_Error(
5807
+				sprintf(
5808
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5809
+						'event_espresso'),
5810
+					$context,
5811
+					'EEM_Base',
5812
+					implode(',', $valid_cap_contexts)
5813
+				)
5814
+			);
5815
+		}
5816
+	}
5817
+
5818
+
5819
+
5820
+	/**
5821
+	 * Clears all the models field caches. This is only useful when a sub-class
5822
+	 * might have added a field or something and these caches might be invalidated
5823
+	 */
5824
+	protected function _invalidate_field_caches()
5825
+	{
5826
+		$this->_cache_foreign_key_to_fields = array();
5827
+		$this->_cached_fields = null;
5828
+		$this->_cached_fields_non_db_only = null;
5829
+	}
5830
+
5831
+
5832
+
5833
+	/**
5834
+	 * _instantiate_new_instance_from_db
5835
+	 *
5836
+	 * @param string $class_name
5837
+	 * @param array  $arguments
5838
+	 * @return \EE_Base_Class
5839
+	 * @throws Exception
5840
+	 */
5841
+	public function _instantiate_new_instance_from_db($class_name, $arguments)
5842
+	{
5843
+		if ( ! class_exists($class_name)) {
5844
+			throw new EE_Error(
5845
+				sprintf(
5846
+					__('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5847
+					$class_name
5848
+				)
5849
+			);
5850
+		}
5851
+		return call_user_func_array(
5852
+			array($class_name, 'new_instance'),
5853
+			array((array)$arguments, $this->_timezone, array(), true)
5854
+		);
5855
+	}
5856
+
5857
+
5858
+	/**
5859
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5860
+	 * (eg "and", "or", "not").
5861
+	 *
5862
+	 * @return array
5863
+	 */
5864
+	public function logic_query_param_keys()
5865
+	{
5866
+		return $this->_logic_query_param_keys;
5867
+	}
5868
+
5869
+
5870
+
5871
+	/**
5872
+	 * Determines whether or not the where query param array key is for a logic query param.
5873
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5874
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5875
+	 *
5876
+	 * @param $query_param_key
5877
+	 * @return bool
5878
+	 */
5879
+	public function is_logic_query_param_key($query_param_key)
5880
+	{
5881
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5882
+			if ($query_param_key === $logic_query_param_key
5883
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5884
+			) {
5885
+				return true;
5886
+			}
5887
+		}
5888
+		return false;
5889
+	}
5890 5890
 
5891 5891
 
5892 5892
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
      */
680 680
     public static function set_model_query_blog_id($blog_id = 0)
681 681
     {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
682
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
683 683
     }
684 684
 
685 685
 
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
     public static function instance($timezone = null)
710 710
     {
711 711
         // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
712
+        if ( ! static::$_instance instanceof static) {
713 713
             // instantiate Espresso_model
714 714
             static::$_instance = new static($timezone);
715 715
         }
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
             foreach ($r->getDefaultProperties() as $property => $value) {
741 741
                 //don't set instance to null like it was originally,
742 742
                 //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
743
+                if ( ! isset($static_properties[$property])) {
744 744
                     static::$_instance->{$property} = $value;
745 745
                 }
746 746
             }
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
      */
764 764
     public function status_array($translated = false)
765 765
     {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
766
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
767 767
             return array();
768 768
         }
769 769
         $model_name = $this->get_this_model_name();
@@ -966,17 +966,17 @@  discard block
 block discarded – undo
966 966
     public function wp_user_field_name()
967 967
     {
968 968
         try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
969
+            if ( ! empty($this->_model_chain_to_wp_user)) {
970 970
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971 971
                 $last_model_name = end($models_to_follow_to_wp_users);
972 972
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
973
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
974 974
             } else {
975 975
                 $model_with_fk_to_wp_users = $this;
976 976
                 $model_chain_to_wp_user = '';
977 977
             }
978 978
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
979
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
980 980
         } catch (EE_Error $e) {
981 981
             return false;
982 982
         }
@@ -1048,12 +1048,12 @@  discard block
 block discarded – undo
1048 1048
         // remember the custom selections, if any, and type cast as array
1049 1049
         // (unless $columns_to_select is an object, then just set as an empty array)
1050 1050
         // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1051
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1052 1052
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053 1053
         $select_expressions = $columns_to_select !== null
1054 1054
             ? $this->_construct_select_from_input($columns_to_select)
1055 1055
             : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1056
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1057 1057
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058 1058
     }
1059 1059
 
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
         if (is_array($columns_to_select)) {
1099 1099
             $select_sql_array = array();
1100 1100
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1101
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102 1102
                     throw new EE_Error(
1103 1103
                         sprintf(
1104 1104
                             __(
@@ -1110,7 +1110,7 @@  discard block
 block discarded – undo
1110 1110
                         )
1111 1111
                     );
1112 1112
                 }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1113
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114 1114
                     throw new EE_Error(
1115 1115
                         sprintf(
1116 1116
                             __(
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184 1184
     {
1185
-        if (! isset($query_params[0])) {
1185
+        if ( ! isset($query_params[0])) {
1186 1186
             $query_params[0] = array();
1187 1187
         }
1188 1188
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
      */
1208 1208
     public function get_one($query_params = array())
1209 1209
     {
1210
-        if (! is_array($query_params)) {
1210
+        if ( ! is_array($query_params)) {
1211 1211
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1212 1212
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213 1213
                     gettype($query_params)), '4.6.0');
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
                 return array();
1376 1376
             }
1377 1377
         }
1378
-        if (! is_array($query_params)) {
1378
+        if ( ! is_array($query_params)) {
1379 1379
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380 1380
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381 1381
                     gettype($query_params)), '4.6.0');
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386 1386
         $query_params['limit'] = $limit;
1387 1387
         //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1388
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1389 1389
         $query_params['order_by'] = $operand === '>'
1390 1390
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391 1391
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1464,7 +1464,7 @@  discard block
 block discarded – undo
1464 1464
     {
1465 1465
         $field_settings = $this->field_settings_for($field_name);
1466 1466
         //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1467
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1468 1468
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469 1469
                 'event_espresso'), $field_name));
1470 1470
         }
@@ -1543,7 +1543,7 @@  discard block
 block discarded – undo
1543 1543
         //load EEH_DTT_Helper
1544 1544
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545 1545
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1547 1547
     }
1548 1548
 
1549 1549
 
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
      */
1612 1612
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613 1613
     {
1614
-        if (! is_array($query_params)) {
1614
+        if ( ! is_array($query_params)) {
1615 1615
             EE_Error::doing_it_wrong('EEM_Base::update',
1616 1616
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617 1617
                     gettype($query_params)), '4.6.0');
@@ -1633,7 +1633,7 @@  discard block
 block discarded – undo
1633 1633
          * @param EEM_Base $model           the model being queried
1634 1634
          * @param array    $query_params    see EEM_Base::get_all()
1635 1635
          */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637 1637
             $query_params);
1638 1638
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639 1639
         //to do that, for each table, verify that it's PK isn't null.
@@ -1647,7 +1647,7 @@  discard block
 block discarded – undo
1647 1647
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648 1648
         foreach ($wpdb_select_results as $wpdb_result) {
1649 1649
             // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1650
+            $wpdb_result = (array) $wpdb_result;
1651 1651
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652 1652
             if ($this->has_primary_key_field()) {
1653 1653
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1664,13 +1664,13 @@  discard block
 block discarded – undo
1664 1664
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665 1665
                     //if there is no private key for this table on the results, it means there's no entry
1666 1666
                     //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1668 1668
                            && $wpdb_result[$this_table_pk_column])
1669 1669
                     ) {
1670 1670
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671 1671
                             $main_table_pk_value);
1672 1672
                         //if we died here, report the error
1673
-                        if (! $success) {
1673
+                        if ( ! $success) {
1674 1674
                             return false;
1675 1675
                         }
1676 1676
                     }
@@ -1701,7 +1701,7 @@  discard block
 block discarded – undo
1701 1701
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702 1702
                 }
1703 1703
             }
1704
-            if (! $model_objs_affected_ids) {
1704
+            if ( ! $model_objs_affected_ids) {
1705 1705
                 //wait wait wait- if nothing was affected let's stop here
1706 1706
                 return 0;
1707 1707
             }
@@ -1728,7 +1728,7 @@  discard block
 block discarded – undo
1728 1728
                . $model_query_info->get_full_join_sql()
1729 1729
                . " SET "
1730 1730
                . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732 1732
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733 1733
         /**
1734 1734
          * Action called after a model update call has been made.
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
          * @param int      $rows_affected
1740 1740
          */
1741 1741
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1742
+        return $rows_affected; //how many supposedly got updated
1743 1743
     }
1744 1744
 
1745 1745
 
@@ -1767,7 +1767,7 @@  discard block
 block discarded – undo
1767 1767
         }
1768 1768
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769 1769
         $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1771 1771
         return $this->_do_wpdb_query('get_col', array($SQL));
1772 1772
     }
1773 1773
 
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
     {
1786 1786
         $query_params['limit'] = 1;
1787 1787
         $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1788
+        if ( ! empty($col)) {
1789 1789
             return reset($col);
1790 1790
         } else {
1791 1791
             return null;
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818 1818
             $value_sql = $prepared_value === null ? 'NULL'
1819 1819
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1821 1821
         }
1822 1822
         return implode(",", $cols_n_values);
1823 1823
     }
@@ -1949,7 +1949,7 @@  discard block
 block discarded – undo
1949 1949
          * @param int      $rows_deleted
1950 1950
          */
1951 1951
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1952
-        return $rows_deleted;//how many supposedly got deleted
1952
+        return $rows_deleted; //how many supposedly got deleted
1953 1953
     }
1954 1954
 
1955 1955
 
@@ -2042,7 +2042,7 @@  discard block
 block discarded – undo
2042 2042
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2043 2043
                 }
2044 2044
                 //other tables
2045
-                if (! empty($other_tables)) {
2045
+                if ( ! empty($other_tables)) {
2046 2046
                     foreach ($other_tables as $ot) {
2047 2047
                         //first check if we've got the foreign key column here.
2048 2048
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2065,7 +2065,7 @@  discard block
 block discarded – undo
2065 2065
             foreach ($deletes as $column => $values) {
2066 2066
                 //make sure we have unique $values;
2067 2067
                 $values = array_unique($values);
2068
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
+                $query[] = $column.' IN('.implode(",", $values).')';
2069 2069
             }
2070 2070
             return ! empty($query) ? implode(' AND ', $query) : '';
2071 2071
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2081,7 +2081,7 @@  discard block
 block discarded – undo
2081 2081
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2082 2082
                     }
2083 2083
                 }
2084
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2085 2085
             }
2086 2086
             return implode(" OR ", $ways_to_identify_a_row);
2087 2087
         } else {
@@ -2130,9 +2130,9 @@  discard block
 block discarded – undo
2130 2130
                 $column_to_count = '*';
2131 2131
             }
2132 2132
         }
2133
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2134
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2135
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2133
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2134
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2135
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2136 2136
     }
2137 2137
 
2138 2138
 
@@ -2154,13 +2154,13 @@  discard block
 block discarded – undo
2154 2154
             $field_obj = $this->get_primary_key_field();
2155 2155
         }
2156 2156
         $column_to_count = $field_obj->get_qualified_column();
2157
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2158 2158
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2159 2159
         $data_type = $field_obj->get_wpdb_data_type();
2160 2160
         if ($data_type === '%d' || $data_type === '%s') {
2161
-            return (float)$return_value;
2161
+            return (float) $return_value;
2162 2162
         } else {//must be %f
2163
-            return (float)$return_value;
2163
+            return (float) $return_value;
2164 2164
         }
2165 2165
     }
2166 2166
 
@@ -2181,13 +2181,13 @@  discard block
 block discarded – undo
2181 2181
         //if we're in maintenance mode level 2, DON'T run any queries
2182 2182
         //because level 2 indicates the database needs updating and
2183 2183
         //is probably out of sync with the code
2184
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2185 2185
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2186 2186
                 "event_espresso")));
2187 2187
         }
2188 2188
         /** @type WPDB $wpdb */
2189 2189
         global $wpdb;
2190
-        if (! method_exists($wpdb, $wpdb_method)) {
2190
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2191 2191
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2192 2192
                 'event_espresso'), $wpdb_method));
2193 2193
         }
@@ -2199,7 +2199,7 @@  discard block
 block discarded – undo
2199 2199
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2200 2200
         if (WP_DEBUG) {
2201 2201
             $wpdb->show_errors($old_show_errors_value);
2202
-            if (! empty($wpdb->last_error)) {
2202
+            if ( ! empty($wpdb->last_error)) {
2203 2203
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2204 2204
             } elseif ($result === false) {
2205 2205
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2259,7 +2259,7 @@  discard block
 block discarded – undo
2259 2259
                     return $result;
2260 2260
                     break;
2261 2261
             }
2262
-            if (! empty($error_message)) {
2262
+            if ( ! empty($error_message)) {
2263 2263
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2264 2264
                 trigger_error($error_message);
2265 2265
             }
@@ -2335,11 +2335,11 @@  discard block
 block discarded – undo
2335 2335
      */
2336 2336
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2337 2337
     {
2338
-        return " FROM " . $model_query_info->get_full_join_sql() .
2339
-               $model_query_info->get_where_sql() .
2340
-               $model_query_info->get_group_by_sql() .
2341
-               $model_query_info->get_having_sql() .
2342
-               $model_query_info->get_order_by_sql() .
2338
+        return " FROM ".$model_query_info->get_full_join_sql().
2339
+               $model_query_info->get_where_sql().
2340
+               $model_query_info->get_group_by_sql().
2341
+               $model_query_info->get_having_sql().
2342
+               $model_query_info->get_order_by_sql().
2343 2343
                $model_query_info->get_limit_sql();
2344 2344
     }
2345 2345
 
@@ -2535,12 +2535,12 @@  discard block
 block discarded – undo
2535 2535
         $related_model = $this->get_related_model_obj($model_name);
2536 2536
         //we're just going to use the query params on the related model's normal get_all query,
2537 2537
         //except add a condition to say to match the current mod
2538
-        if (! isset($query_params['default_where_conditions'])) {
2538
+        if ( ! isset($query_params['default_where_conditions'])) {
2539 2539
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2540 2540
         }
2541 2541
         $this_model_name = $this->get_this_model_name();
2542 2542
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2543
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2544 2544
         return $related_model->count($query_params, $field_to_count, $distinct);
2545 2545
     }
2546 2546
 
@@ -2560,7 +2560,7 @@  discard block
 block discarded – undo
2560 2560
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2561 2561
     {
2562 2562
         $related_model = $this->get_related_model_obj($model_name);
2563
-        if (! is_array($query_params)) {
2563
+        if ( ! is_array($query_params)) {
2564 2564
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2565 2565
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2566 2566
                     gettype($query_params)), '4.6.0');
@@ -2568,12 +2568,12 @@  discard block
 block discarded – undo
2568 2568
         }
2569 2569
         //we're just going to use the query params on the related model's normal get_all query,
2570 2570
         //except add a condition to say to match the current mod
2571
-        if (! isset($query_params['default_where_conditions'])) {
2571
+        if ( ! isset($query_params['default_where_conditions'])) {
2572 2572
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2573 2573
         }
2574 2574
         $this_model_name = $this->get_this_model_name();
2575 2575
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2576
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2577 2577
         return $related_model->sum($query_params, $field_to_sum);
2578 2578
     }
2579 2579
 
@@ -2627,7 +2627,7 @@  discard block
 block discarded – undo
2627 2627
                 $field_with_model_name = $field;
2628 2628
             }
2629 2629
         }
2630
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2631 2631
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2632 2632
                 $this->get_this_model_name()));
2633 2633
         }
@@ -2660,7 +2660,7 @@  discard block
 block discarded – undo
2660 2660
          * @param array    $fields_n_values keys are the fields and values are their new values
2661 2661
          * @param EEM_Base $model           the model used
2662 2662
          */
2663
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2664 2664
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2665 2665
             $main_table = $this->_get_main_table();
2666 2666
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2768,7 +2768,7 @@  discard block
 block discarded – undo
2768 2768
         }
2769 2769
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2770 2770
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2771
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2772 2772
         }
2773 2773
         //if there is nothing to base this search on, then we shouldn't find anything
2774 2774
         if (empty($query_params)) {
@@ -2855,7 +2855,7 @@  discard block
 block discarded – undo
2855 2855
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2856 2856
             //so add the fk to the main table as a column
2857 2857
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2858
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2859 2859
         }
2860 2860
         //insert the new entry
2861 2861
         $result = $this->_do_wpdb_query('insert',
@@ -3061,7 +3061,7 @@  discard block
 block discarded – undo
3061 3061
                     $query_info_carrier,
3062 3062
                     'group_by'
3063 3063
                 );
3064
-            } elseif (! empty ($query_params['group_by'])) {
3064
+            } elseif ( ! empty ($query_params['group_by'])) {
3065 3065
                 $this->_extract_related_model_info_from_query_param(
3066 3066
                     $query_params['group_by'],
3067 3067
                     $query_info_carrier,
@@ -3083,7 +3083,7 @@  discard block
 block discarded – undo
3083 3083
                     $query_info_carrier,
3084 3084
                     'order_by'
3085 3085
                 );
3086
-            } elseif (! empty($query_params['order_by'])) {
3086
+            } elseif ( ! empty($query_params['order_by'])) {
3087 3087
                 $this->_extract_related_model_info_from_query_param(
3088 3088
                     $query_params['order_by'],
3089 3089
                     $query_info_carrier,
@@ -3118,8 +3118,8 @@  discard block
 block discarded – undo
3118 3118
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3119 3119
         $query_param_type
3120 3120
     ) {
3121
-        if (! empty($sub_query_params)) {
3122
-            $sub_query_params = (array)$sub_query_params;
3121
+        if ( ! empty($sub_query_params)) {
3122
+            $sub_query_params = (array) $sub_query_params;
3123 3123
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3124 3124
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3125 3125
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3130,7 +3130,7 @@  discard block
 block discarded – undo
3130 3130
                 //of array('Registration.TXN_ID'=>23)
3131 3131
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3132 3132
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3133
-                    if (! is_array($possibly_array_of_params)) {
3133
+                    if ( ! is_array($possibly_array_of_params)) {
3134 3134
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3135 3135
                             "event_espresso"),
3136 3136
                             $param, $possibly_array_of_params));
@@ -3146,7 +3146,7 @@  discard block
 block discarded – undo
3146 3146
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3147 3147
                     //indicating that $possible_array_of_params[1] is actually a field name,
3148 3148
                     //from which we should extract query parameters!
3149
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3149
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3150 3150
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3151 3151
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3152 3152
                     }
@@ -3176,8 +3176,8 @@  discard block
 block discarded – undo
3176 3176
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3177 3177
         $query_param_type
3178 3178
     ) {
3179
-        if (! empty($sub_query_params)) {
3180
-            if (! is_array($sub_query_params)) {
3179
+        if ( ! empty($sub_query_params)) {
3180
+            if ( ! is_array($sub_query_params)) {
3181 3181
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3182 3182
                     $sub_query_params));
3183 3183
             }
@@ -3206,7 +3206,7 @@  discard block
 block discarded – undo
3206 3206
      */
3207 3207
     public function _create_model_query_info_carrier($query_params)
3208 3208
     {
3209
-        if (! is_array($query_params)) {
3209
+        if ( ! is_array($query_params)) {
3210 3210
             EE_Error::doing_it_wrong(
3211 3211
                 'EEM_Base::_create_model_query_info_carrier',
3212 3212
                 sprintf(
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
         //set limit
3283 3283
         if (array_key_exists('limit', $query_params)) {
3284 3284
             if (is_array($query_params['limit'])) {
3285
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3285
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3286 3286
                     $e = sprintf(
3287 3287
                         __(
3288 3288
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3290,12 +3290,12 @@  discard block
 block discarded – undo
3290 3290
                         ),
3291 3291
                         http_build_query($query_params['limit'])
3292 3292
                     );
3293
-                    throw new EE_Error($e . "|" . $e);
3293
+                    throw new EE_Error($e."|".$e);
3294 3294
                 }
3295 3295
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3296
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3297
-            } elseif (! empty ($query_params['limit'])) {
3298
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3296
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3297
+            } elseif ( ! empty ($query_params['limit'])) {
3298
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3299 3299
             }
3300 3300
         }
3301 3301
         //set order by
@@ -3327,10 +3327,10 @@  discard block
 block discarded – undo
3327 3327
                 $order_array = array();
3328 3328
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3329 3329
                     $order = $this->_extract_order($order);
3330
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3330
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3331 3331
                 }
3332
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3333
-            } elseif (! empty ($query_params['order_by'])) {
3332
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3333
+            } elseif ( ! empty ($query_params['order_by'])) {
3334 3334
                 $this->_extract_related_model_info_from_query_param(
3335 3335
                     $query_params['order_by'],
3336 3336
                     $query_object,
@@ -3341,18 +3341,18 @@  discard block
 block discarded – undo
3341 3341
                     ? $this->_extract_order($query_params['order'])
3342 3342
                     : 'DESC';
3343 3343
                 $query_object->set_order_by_sql(
3344
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3344
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3345 3345
                 );
3346 3346
             }
3347 3347
         }
3348 3348
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3349
-        if (! array_key_exists('order_by', $query_params)
3349
+        if ( ! array_key_exists('order_by', $query_params)
3350 3350
             && array_key_exists('order', $query_params)
3351 3351
             && ! empty($query_params['order'])
3352 3352
         ) {
3353 3353
             $pk_field = $this->get_primary_key_field();
3354 3354
             $order = $this->_extract_order($query_params['order']);
3355
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3355
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3356 3356
         }
3357 3357
         //set group by
3358 3358
         if (array_key_exists('group_by', $query_params)) {
@@ -3362,10 +3362,10 @@  discard block
 block discarded – undo
3362 3362
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3363 3363
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3364 3364
                 }
3365
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3366
-            } elseif (! empty ($query_params['group_by'])) {
3365
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3366
+            } elseif ( ! empty ($query_params['group_by'])) {
3367 3367
                 $query_object->set_group_by_sql(
3368
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3368
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3369 3369
                 );
3370 3370
             }
3371 3371
         }
@@ -3375,7 +3375,7 @@  discard block
 block discarded – undo
3375 3375
         }
3376 3376
         //now, just verify they didn't pass anything wack
3377 3377
         foreach ($query_params as $query_key => $query_value) {
3378
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3378
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3379 3379
                 throw new EE_Error(
3380 3380
                     sprintf(
3381 3381
                         __(
@@ -3469,22 +3469,22 @@  discard block
 block discarded – undo
3469 3469
         $where_query_params = array()
3470 3470
     ) {
3471 3471
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3472
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3472
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3473 3473
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3474 3474
                 "event_espresso"), $use_default_where_conditions,
3475 3475
                 implode(", ", $allowed_used_default_where_conditions_values)));
3476 3476
         }
3477 3477
         $universal_query_params = array();
3478
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3478
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3479 3479
             $universal_query_params = $this->_get_default_where_conditions();
3480
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3480
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3481 3481
             $universal_query_params = $this->_get_minimum_where_conditions();
3482 3482
         }
3483 3483
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3484 3484
             $related_model = $this->get_related_model_obj($model_name);
3485
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3485
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3486 3486
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3487
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3487
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3488 3488
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3489 3489
             } else {
3490 3490
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3517,7 +3517,7 @@  discard block
 block discarded – undo
3517 3517
      * @param bool $for_this_model false means this is for OTHER related models
3518 3518
      * @return bool
3519 3519
      */
3520
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3520
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3521 3521
     {
3522 3522
         return (
3523 3523
                    $for_this_model
@@ -3596,7 +3596,7 @@  discard block
 block discarded – undo
3596 3596
     ) {
3597 3597
         $null_friendly_where_conditions = array();
3598 3598
         $none_overridden = true;
3599
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3599
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3600 3600
         foreach ($default_where_conditions as $key => $val) {
3601 3601
             if (isset($provided_where_conditions[$key])) {
3602 3602
                 $none_overridden = false;
@@ -3714,7 +3714,7 @@  discard block
 block discarded – undo
3714 3714
             foreach ($tables as $table_obj) {
3715 3715
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3716 3716
                                        . $table_obj->get_fully_qualified_pk_column();
3717
-                if (! in_array($qualified_pk_column, $selects)) {
3717
+                if ( ! in_array($qualified_pk_column, $selects)) {
3718 3718
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3719 3719
                 }
3720 3720
             }
@@ -3800,9 +3800,9 @@  discard block
 block discarded – undo
3800 3800
         //and
3801 3801
         //check if it's a field on a related model
3802 3802
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3803
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3803
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3804 3804
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3805
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3805
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3806 3806
                 if ($query_param === '') {
3807 3807
                     //nothing left to $query_param
3808 3808
                     //we should actually end in a field name, not a model like this!
@@ -3888,7 +3888,7 @@  discard block
 block discarded – undo
3888 3888
     {
3889 3889
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3890 3890
         if ($SQL) {
3891
-            return " WHERE " . $SQL;
3891
+            return " WHERE ".$SQL;
3892 3892
         } else {
3893 3893
             return '';
3894 3894
         }
@@ -3908,7 +3908,7 @@  discard block
 block discarded – undo
3908 3908
     {
3909 3909
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3910 3910
         if ($SQL) {
3911
-            return " HAVING " . $SQL;
3911
+            return " HAVING ".$SQL;
3912 3912
         } else {
3913 3913
             return '';
3914 3914
         }
@@ -3928,11 +3928,11 @@  discard block
 block discarded – undo
3928 3928
      */
3929 3929
     protected function _get_field_on_model($field_name, $model_name)
3930 3930
     {
3931
-        $model_class = 'EEM_' . $model_name;
3932
-        $model_filepath = $model_class . ".model.php";
3931
+        $model_class = 'EEM_'.$model_name;
3932
+        $model_filepath = $model_class.".model.php";
3933 3933
         if (is_readable($model_filepath)) {
3934 3934
             require_once($model_filepath);
3935
-            $model_instance = call_user_func($model_name . "::instance");
3935
+            $model_instance = call_user_func($model_name."::instance");
3936 3936
             /* @var $model_instance EEM_Base */
3937 3937
             return $model_instance->field_settings_for($field_name);
3938 3938
         } else {
@@ -3956,7 +3956,7 @@  discard block
 block discarded – undo
3956 3956
     {
3957 3957
         $where_clauses = array();
3958 3958
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3959
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3959
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3960 3960
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3961 3961
                 switch ($query_param) {
3962 3962
                     case 'not':
@@ -3984,7 +3984,7 @@  discard block
 block discarded – undo
3984 3984
             } else {
3985 3985
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3986 3986
                 //if it's not a normal field, maybe it's a custom selection?
3987
-                if (! $field_obj) {
3987
+                if ( ! $field_obj) {
3988 3988
                     if (isset($this->_custom_selections[$query_param][1])) {
3989 3989
                         $field_obj = $this->_custom_selections[$query_param][1];
3990 3990
                     } else {
@@ -3993,7 +3993,7 @@  discard block
 block discarded – undo
3993 3993
                     }
3994 3994
                 }
3995 3995
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3996
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3996
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3997 3997
             }
3998 3998
         }
3999 3999
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4014,7 +4014,7 @@  discard block
 block discarded – undo
4014 4014
         if ($field) {
4015 4015
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4016 4016
                 $query_param);
4017
-            return $table_alias_prefix . $field->get_qualified_column();
4017
+            return $table_alias_prefix.$field->get_qualified_column();
4018 4018
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4019 4019
             //maybe it's custom selection item?
4020 4020
             //if so, just use it as the "column name"
@@ -4061,7 +4061,7 @@  discard block
 block discarded – undo
4061 4061
     {
4062 4062
         if (is_array($op_and_value)) {
4063 4063
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4064
-            if (! $operator) {
4064
+            if ( ! $operator) {
4065 4065
                 $php_array_like_string = array();
4066 4066
                 foreach ($op_and_value as $key => $value) {
4067 4067
                     $php_array_like_string[] = "$key=>$value";
@@ -4083,13 +4083,13 @@  discard block
 block discarded – undo
4083 4083
         }
4084 4084
         //check to see if the value is actually another field
4085 4085
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4086
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4086
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4087 4087
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4088 4088
             //in this case, the value should be an array, or at least a comma-separated list
4089 4089
             //it will need to handle a little differently
4090 4090
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4091 4091
             //note: $cleaned_value has already been run through $wpdb->prepare()
4092
-            return $operator . SP . $cleaned_value;
4092
+            return $operator.SP.$cleaned_value;
4093 4093
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4094 4094
             //the value should be an array with count of two.
4095 4095
             if (count($value) !== 2) {
@@ -4104,7 +4104,7 @@  discard block
 block discarded – undo
4104 4104
                 );
4105 4105
             }
4106 4106
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4107
-            return $operator . SP . $cleaned_value;
4107
+            return $operator.SP.$cleaned_value;
4108 4108
         } elseif (in_array($operator, $this->_null_style_operators)) {
4109 4109
             if ($value !== null) {
4110 4110
                 throw new EE_Error(
@@ -4122,9 +4122,9 @@  discard block
 block discarded – undo
4122 4122
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4123 4123
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4124 4124
             //remove other junk. So just treat it as a string.
4125
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4126
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4125
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4126
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4128 4128
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4129 4129
             throw new EE_Error(
4130 4130
                 sprintf(
@@ -4136,7 +4136,7 @@  discard block
 block discarded – undo
4136 4136
                     $operator
4137 4137
                 )
4138 4138
             );
4139
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4139
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4140 4140
             throw new EE_Error(
4141 4141
                 sprintf(
4142 4142
                     __(
@@ -4177,7 +4177,7 @@  discard block
 block discarded – undo
4177 4177
         foreach ($values as $value) {
4178 4178
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4179 4179
         }
4180
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4180
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4181 4181
     }
4182 4182
 
4183 4183
 
@@ -4218,7 +4218,7 @@  discard block
 block discarded – undo
4218 4218
                                 . $main_table->get_table_name()
4219 4219
                                 . " WHERE FALSE";
4220 4220
         }
4221
-        return "(" . implode(",", $cleaned_values) . ")";
4221
+        return "(".implode(",", $cleaned_values).")";
4222 4222
     }
4223 4223
 
4224 4224
 
@@ -4237,7 +4237,7 @@  discard block
 block discarded – undo
4237 4237
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4238 4238
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4239 4239
         } else {//$field_obj should really just be a data type
4240
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4240
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4241 4241
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4242 4242
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4243 4243
             }
@@ -4357,10 +4357,10 @@  discard block
 block discarded – undo
4357 4357
      */
4358 4358
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4359 4359
     {
4360
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4360
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4361 4361
         $qualified_columns = array();
4362 4362
         foreach ($this->field_settings() as $field_name => $field) {
4363
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4363
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4364 4364
         }
4365 4365
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4366 4366
     }
@@ -4384,11 +4384,11 @@  discard block
 block discarded – undo
4384 4384
             if ($table_obj instanceof EE_Primary_Table) {
4385 4385
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4386 4386
                     ? $table_obj->get_select_join_limit($limit)
4387
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4387
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4388 4388
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4389 4389
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4390 4390
                     ? $table_obj->get_select_join_limit_join($limit)
4391
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4391
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4392 4392
             }
4393 4393
         }
4394 4394
         return $SQL;
@@ -4476,12 +4476,12 @@  discard block
 block discarded – undo
4476 4476
      */
4477 4477
     public function get_related_model_obj($model_name)
4478 4478
     {
4479
-        $model_classname = "EEM_" . $model_name;
4480
-        if (! class_exists($model_classname)) {
4479
+        $model_classname = "EEM_".$model_name;
4480
+        if ( ! class_exists($model_classname)) {
4481 4481
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4482 4482
                 'event_espresso'), $model_name, $model_classname));
4483 4483
         }
4484
-        return call_user_func($model_classname . "::instance");
4484
+        return call_user_func($model_classname."::instance");
4485 4485
     }
4486 4486
 
4487 4487
 
@@ -4528,7 +4528,7 @@  discard block
 block discarded – undo
4528 4528
     public function related_settings_for($relation_name)
4529 4529
     {
4530 4530
         $relatedModels = $this->relation_settings();
4531
-        if (! array_key_exists($relation_name, $relatedModels)) {
4531
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4532 4532
             throw new EE_Error(
4533 4533
                 sprintf(
4534 4534
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4555,7 +4555,7 @@  discard block
 block discarded – undo
4555 4555
     public function field_settings_for($fieldName)
4556 4556
     {
4557 4557
         $fieldSettings = $this->field_settings(true);
4558
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4558
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4559 4559
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4560 4560
                 get_class($this)));
4561 4561
         }
@@ -4630,7 +4630,7 @@  discard block
 block discarded – undo
4630 4630
                     break;
4631 4631
                 }
4632 4632
             }
4633
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4633
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4634 4634
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4635 4635
                     get_class($this)));
4636 4636
             }
@@ -4689,7 +4689,7 @@  discard block
 block discarded – undo
4689 4689
      */
4690 4690
     public function get_foreign_key_to($model_name)
4691 4691
     {
4692
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4692
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693 4693
             foreach ($this->field_settings() as $field) {
4694 4694
                 if (
4695 4695
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4699,7 +4699,7 @@  discard block
 block discarded – undo
4699 4699
                     break;
4700 4700
                 }
4701 4701
             }
4702
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4702
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4703 4703
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4704 4704
                     'event_espresso'), $model_name, get_class($this)));
4705 4705
             }
@@ -4750,7 +4750,7 @@  discard block
 block discarded – undo
4750 4750
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4751 4751
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4752 4752
                         /** @var $field_obj EE_Model_Field_Base */
4753
-                        if (! $field_obj->is_db_only_field()) {
4753
+                        if ( ! $field_obj->is_db_only_field()) {
4754 4754
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4755 4755
                         }
4756 4756
                     }
@@ -4780,7 +4780,7 @@  discard block
 block discarded – undo
4780 4780
         $count_if_model_has_no_primary_key = 0;
4781 4781
         $has_primary_key = $this->has_primary_key_field();
4782 4782
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4783
-        foreach ((array)$rows as $row) {
4783
+        foreach ((array) $rows as $row) {
4784 4784
             if (empty($row)) {
4785 4785
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4786 4786
                 return array();
@@ -4798,7 +4798,7 @@  discard block
 block discarded – undo
4798 4798
                 }
4799 4799
             }
4800 4800
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4801
-            if (! $classInstance) {
4801
+            if ( ! $classInstance) {
4802 4802
                 throw new EE_Error(
4803 4803
                     sprintf(
4804 4804
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4870,7 +4870,7 @@  discard block
 block discarded – undo
4870 4870
      */
4871 4871
     public function instantiate_class_from_array_or_object($cols_n_values)
4872 4872
     {
4873
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4873
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4874 4874
             $cols_n_values = get_object_vars($cols_n_values);
4875 4875
         }
4876 4876
         $primary_key = null;
@@ -4894,7 +4894,7 @@  discard block
 block discarded – undo
4894 4894
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4895 4895
         if ($primary_key) {
4896 4896
             $classInstance = $this->get_from_entity_map($primary_key);
4897
-            if (! $classInstance) {
4897
+            if ( ! $classInstance) {
4898 4898
                 $classInstance = $this->_instantiate_new_instance_from_db(
4899 4899
                     $this->_get_class_name(),
4900 4900
                     $this_model_fields_n_values
@@ -4952,12 +4952,12 @@  discard block
 block discarded – undo
4952 4952
     public function add_to_entity_map(EE_Base_Class $object)
4953 4953
     {
4954 4954
         $className = $this->_get_class_name();
4955
-        if (! $object instanceof $className) {
4955
+        if ( ! $object instanceof $className) {
4956 4956
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4957 4957
                 is_object($object) ? get_class($object) : $object, $className));
4958 4958
         }
4959 4959
         /** @var $object EE_Base_Class */
4960
-        if (! $object->ID()) {
4960
+        if ( ! $object->ID()) {
4961 4961
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4962 4962
                 "event_espresso"), get_class($this)));
4963 4963
         }
@@ -5027,7 +5027,7 @@  discard block
 block discarded – undo
5027 5027
             //there is a primary key on this table and its not set. Use defaults for all its columns
5028 5028
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5029 5029
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5030
-                    if (! $field_obj->is_db_only_field()) {
5030
+                    if ( ! $field_obj->is_db_only_field()) {
5031 5031
                         //prepare field as if its coming from db
5032 5032
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5033 5033
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5036,7 +5036,7 @@  discard block
 block discarded – undo
5036 5036
             } else {
5037 5037
                 //the table's rows existed. Use their values
5038 5038
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5039
-                    if (! $field_obj->is_db_only_field()) {
5039
+                    if ( ! $field_obj->is_db_only_field()) {
5040 5040
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5041 5041
                             $cols_n_values, $field_obj->get_qualified_column(),
5042 5042
                             $field_obj->get_table_column()
@@ -5153,7 +5153,7 @@  discard block
 block discarded – undo
5153 5153
      */
5154 5154
     private function _get_class_name()
5155 5155
     {
5156
-        return "EE_" . $this->get_this_model_name();
5156
+        return "EE_".$this->get_this_model_name();
5157 5157
     }
5158 5158
 
5159 5159
 
@@ -5168,7 +5168,7 @@  discard block
 block discarded – undo
5168 5168
      */
5169 5169
     public function item_name($quantity = 1)
5170 5170
     {
5171
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5171
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5172 5172
     }
5173 5173
 
5174 5174
 
@@ -5201,7 +5201,7 @@  discard block
 block discarded – undo
5201 5201
     {
5202 5202
         $className = get_class($this);
5203 5203
         $tagName = "FHEE__{$className}__{$methodName}";
5204
-        if (! has_filter($tagName)) {
5204
+        if ( ! has_filter($tagName)) {
5205 5205
             throw new EE_Error(
5206 5206
                 sprintf(
5207 5207
                     __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
@@ -5427,7 +5427,7 @@  discard block
 block discarded – undo
5427 5427
         $key_vals_in_combined_pk = array();
5428 5428
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5429 5429
         foreach ($key_fields as $key_field_name => $field_obj) {
5430
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5430
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5431 5431
                 return null;
5432 5432
             }
5433 5433
         }
@@ -5448,7 +5448,7 @@  discard block
 block discarded – undo
5448 5448
     {
5449 5449
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5450 5450
         foreach ($keys_it_should_have as $key) {
5451
-            if (! isset($key_vals[$key])) {
5451
+            if ( ! isset($key_vals[$key])) {
5452 5452
                 return false;
5453 5453
             }
5454 5454
         }
@@ -5502,7 +5502,7 @@  discard block
 block discarded – undo
5502 5502
      */
5503 5503
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5504 5504
     {
5505
-        if (! is_array($query_params)) {
5505
+        if ( ! is_array($query_params)) {
5506 5506
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5507 5507
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5508 5508
                     gettype($query_params)), '4.6.0');
@@ -5594,7 +5594,7 @@  discard block
 block discarded – undo
5594 5594
      */
5595 5595
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5596 5596
     {
5597
-        if (! $this->has_primary_key_field()) {
5597
+        if ( ! $this->has_primary_key_field()) {
5598 5598
             if (WP_DEBUG) {
5599 5599
                 EE_Error::add_error(
5600 5600
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5607,7 +5607,7 @@  discard block
 block discarded – undo
5607 5607
         $IDs = array();
5608 5608
         foreach ($model_objects as $model_object) {
5609 5609
             $id = $model_object->ID();
5610
-            if (! $id) {
5610
+            if ( ! $id) {
5611 5611
                 if ($filter_out_empty_ids) {
5612 5612
                     continue;
5613 5613
                 }
@@ -5703,8 +5703,8 @@  discard block
 block discarded – undo
5703 5703
         $missing_caps = array();
5704 5704
         $cap_restrictions = $this->cap_restrictions($context);
5705 5705
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5706
-            if (! EE_Capabilities::instance()
5707
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5706
+            if ( ! EE_Capabilities::instance()
5707
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5708 5708
             ) {
5709 5709
                 $missing_caps[$cap] = $restriction_if_no_cap;
5710 5710
             }
@@ -5850,7 +5850,7 @@  discard block
 block discarded – undo
5850 5850
         }
5851 5851
         return call_user_func_array(
5852 5852
             array($class_name, 'new_instance'),
5853
-            array((array)$arguments, $this->_timezone, array(), true)
5853
+            array((array) $arguments, $this->_timezone, array(), true)
5854 5854
         );
5855 5855
     }
5856 5856
 
@@ -5880,7 +5880,7 @@  discard block
 block discarded – undo
5880 5880
     {
5881 5881
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5882 5882
             if ($query_param_key === $logic_query_param_key
5883
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5883
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5884 5884
             ) {
5885 5885
                 return true;
5886 5886
             }
Please login to merge, or discard this patch.
core/EE_Registry.core.php 3 patches
Doc Comments   +1 added lines, -3 removed lines patch added patch discarded remove patch
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 
310 310
 
311 311
     /**
312
-     * @param $module
312
+     * @param string $module
313 313
      * @throws ReflectionException
314 314
      */
315 315
     public function add_module($module)
@@ -575,8 +575,6 @@  discard block
 block discarded – undo
575 575
      * @param bool|string $class_name   Fully Qualified Class Name
576 576
      * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
577 577
      * @param bool        $cache        whether to cache the instantiated object for reuse
578
-     * @param bool        $from_db      some classes are instantiated from the db
579
-     *                                  and thus call a different method to instantiate
580 578
      * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
581 579
      * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
582 580
      * @return mixed                    null = failure to load or instantiate class object.
Please login to merge, or discard this patch.
Indentation   +1427 added lines, -1427 removed lines patch added patch discarded remove patch
@@ -19,1463 +19,1463 @@
 block discarded – undo
19 19
 class EE_Registry implements ResettableInterface
20 20
 {
21 21
 
22
-    /**
23
-     *    EE_Registry Object
24
-     *
25
-     * @var EE_Registry $_instance
26
-     * @access    private
27
-     */
28
-    private static $_instance = null;
29
-
30
-    /**
31
-     * @var EE_Dependency_Map $_dependency_map
32
-     * @access    protected
33
-     */
34
-    protected $_dependency_map = null;
35
-
36
-    /**
37
-     * @var array $_class_abbreviations
38
-     * @access    protected
39
-     */
40
-    protected $_class_abbreviations = array();
41
-
42
-    /**
43
-     * @access public
44
-     * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
45
-     */
46
-    public $BUS;
47
-
48
-    /**
49
-     *    EE_Cart Object
50
-     *
51
-     * @access    public
52
-     * @var    EE_Cart $CART
53
-     */
54
-    public $CART = null;
55
-
56
-    /**
57
-     *    EE_Config Object
58
-     *
59
-     * @access    public
60
-     * @var    EE_Config $CFG
61
-     */
62
-    public $CFG = null;
63
-
64
-    /**
65
-     * EE_Network_Config Object
66
-     *
67
-     * @access public
68
-     * @var EE_Network_Config $NET_CFG
69
-     */
70
-    public $NET_CFG = null;
71
-
72
-    /**
73
-     *    StdClass object for storing library classes in
74
-     *
75
-     * @public LIB
76
-     * @var StdClass $LIB
77
-     */
78
-    public $LIB = null;
79
-
80
-    /**
81
-     *    EE_Request_Handler Object
82
-     *
83
-     * @access    public
84
-     * @var    EE_Request_Handler $REQ
85
-     */
86
-    public $REQ = null;
87
-
88
-    /**
89
-     *    EE_Session Object
90
-     *
91
-     * @access    public
92
-     * @var    EE_Session $SSN
93
-     */
94
-    public $SSN = null;
95
-
96
-    /**
97
-     * holds the ee capabilities object.
98
-     *
99
-     * @since 4.5.0
100
-     * @var EE_Capabilities
101
-     */
102
-    public $CAP = null;
103
-
104
-    /**
105
-     * holds the EE_Message_Resource_Manager object.
106
-     *
107
-     * @since 4.9.0
108
-     * @var EE_Message_Resource_Manager
109
-     */
110
-    public $MRM = null;
111
-
112
-
113
-    /**
114
-     * Holds the Assets Registry instance
115
-     * @var Registry
116
-     */
117
-    public $AssetsRegistry = null;
118
-
119
-    /**
120
-     *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
121
-     *
122
-     * @access    public
123
-     * @var    EE_Addon[]
124
-     */
125
-    public $addons = null;
126
-
127
-    /**
128
-     *    $models
129
-     * @access    public
130
-     * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
131
-     */
132
-    public $models = array();
133
-
134
-    /**
135
-     *    $modules
136
-     * @access    public
137
-     * @var    EED_Module[] $modules
138
-     */
139
-    public $modules = null;
140
-
141
-    /**
142
-     *    $shortcodes
143
-     * @access    public
144
-     * @var    EES_Shortcode[] $shortcodes
145
-     */
146
-    public $shortcodes = null;
147
-
148
-    /**
149
-     *    $widgets
150
-     * @access    public
151
-     * @var    WP_Widget[] $widgets
152
-     */
153
-    public $widgets = null;
154
-
155
-    /**
156
-     * $non_abstract_db_models
157
-     * @access public
158
-     * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
159
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
160
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
161
-     * classnames (eg "EEM_Event")
162
-     */
163
-    public $non_abstract_db_models = array();
164
-
165
-
166
-    /**
167
-     *    $i18n_js_strings - internationalization for JS strings
168
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
169
-     *    in js file:  var translatedString = eei18n.string_key;
170
-     *
171
-     * @access    public
172
-     * @var    array
173
-     */
174
-    public static $i18n_js_strings = array();
175
-
176
-
177
-    /**
178
-     *    $main_file - path to espresso.php
179
-     *
180
-     * @access    public
181
-     * @var    array
182
-     */
183
-    public $main_file;
184
-
185
-    /**
186
-     * array of ReflectionClass objects where the key is the class name
187
-     *
188
-     * @access    public
189
-     * @var ReflectionClass[]
190
-     */
191
-    public $_reflectors;
192
-
193
-    /**
194
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
195
-     *
196
-     * @access    protected
197
-     * @var boolean $_cache_on
198
-     */
199
-    protected $_cache_on = true;
200
-
201
-
202
-
203
-    /**
204
-     * @singleton method used to instantiate class object
205
-     * @access    public
206
-     * @param  \EE_Dependency_Map $dependency_map
207
-     * @return \EE_Registry instance
208
-     */
209
-    public static function instance(\EE_Dependency_Map $dependency_map = null)
210
-    {
211
-        // check if class object is instantiated
212
-        if ( ! self::$_instance instanceof EE_Registry) {
213
-            self::$_instance = new EE_Registry($dependency_map);
214
-        }
215
-        return self::$_instance;
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     *protected constructor to prevent direct creation
222
-     *
223
-     * @Constructor
224
-     * @access protected
225
-     * @param  \EE_Dependency_Map $dependency_map
226
-     */
227
-    protected function __construct(\EE_Dependency_Map $dependency_map)
228
-    {
229
-        $this->_dependency_map = $dependency_map;
230
-        $this->LIB = new stdClass();
231
-        $this->addons = new stdClass();
232
-        $this->modules = new stdClass();
233
-        $this->shortcodes = new stdClass();
234
-        $this->widgets = new stdClass();
235
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
236
-    }
237
-
238
-
239
-
240
-    /**
241
-     * initialize
242
-     */
243
-    public function initialize()
244
-    {
245
-        $this->_class_abbreviations = apply_filters(
246
-            'FHEE__EE_Registry____construct___class_abbreviations',
247
-            array(
248
-                'EE_Config'                                       => 'CFG',
249
-                'EE_Session'                                      => 'SSN',
250
-                'EE_Capabilities'                                 => 'CAP',
251
-                'EE_Cart'                                         => 'CART',
252
-                'EE_Network_Config'                               => 'NET_CFG',
253
-                'EE_Request_Handler'                              => 'REQ',
254
-                'EE_Message_Resource_Manager'                     => 'MRM',
255
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
256
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
257
-            )
258
-        );
259
-        $this->load_core('Base', array(), true);
260
-        // add our request and response objects to the cache
261
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
262
-        $this->_set_cached_class(
263
-            $request_loader(),
264
-            'EE_Request'
265
-        );
266
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
267
-        $this->_set_cached_class(
268
-            $response_loader(),
269
-            'EE_Response'
270
-        );
271
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     *    init
278
-     *
279
-     * @access    public
280
-     * @return    void
281
-     */
282
-    public function init()
283
-    {
284
-        // Get current page protocol
285
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
286
-        // Output admin-ajax.php URL with same protocol as current page
287
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
288
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * localize_i18n_js_strings
295
-     *
296
-     * @return string
297
-     */
298
-    public static function localize_i18n_js_strings()
299
-    {
300
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
301
-        foreach ($i18n_js_strings as $key => $value) {
302
-            if (is_scalar($value)) {
303
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
304
-            }
305
-        }
306
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * @param $module
313
-     * @throws ReflectionException
314
-     */
315
-    public function add_module($module)
316
-    {
317
-        if ($module instanceof EED_Module) {
318
-            $module_class = get_class($module);
319
-            $this->modules->{$module_class} = $module;
320
-        } else {
321
-            if ( ! class_exists('EE_Module_Request_Router')) {
322
-                $this->load_core('Module_Request_Router');
323
-            }
324
-            EE_Module_Request_Router::module_factory($module);
325
-        }
326
-    }
327
-
328
-
329
-
330
-    /**
331
-     * @param string $module_name
332
-     * @return mixed EED_Module | NULL
333
-     */
334
-    public function get_module($module_name = '')
335
-    {
336
-        return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
337
-    }
338
-
339
-
340
-
341
-    /**
342
-     *    loads core classes - must be singletons
343
-     *
344
-     * @access    public
345
-     * @param string $class_name - simple class name ie: session
346
-     * @param mixed  $arguments
347
-     * @param bool   $load_only
348
-     * @return mixed
349
-     */
350
-    public function load_core($class_name, $arguments = array(), $load_only = false)
351
-    {
352
-        $core_paths = apply_filters(
353
-            'FHEE__EE_Registry__load_core__core_paths',
354
-            array(
355
-                EE_CORE,
356
-                EE_ADMIN,
357
-                EE_CPTS,
358
-                EE_CORE . 'data_migration_scripts' . DS,
359
-                EE_CORE . 'request_stack' . DS,
360
-                EE_CORE . 'middleware' . DS,
361
-            )
362
-        );
363
-        // retrieve instantiated class
364
-        return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, true, $load_only);
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     *    loads service classes
371
-     *
372
-     * @access    public
373
-     * @param string $class_name - simple class name ie: session
374
-     * @param mixed  $arguments
375
-     * @param bool   $load_only
376
-     * @return mixed
377
-     */
378
-    public function load_service($class_name, $arguments = array(), $load_only = false)
379
-    {
380
-        $service_paths = apply_filters(
381
-            'FHEE__EE_Registry__load_service__service_paths',
382
-            array(
383
-                EE_CORE . 'services' . DS,
384
-            )
385
-        );
386
-        // retrieve instantiated class
387
-        return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, true, $load_only);
388
-    }
389
-
390
-
391
-
392
-    /**
393
-     *    loads data_migration_scripts
394
-     *
395
-     * @access    public
396
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
397
-     * @param mixed  $arguments
398
-     * @return EE_Data_Migration_Script_Base|mixed
399
-     */
400
-    public function load_dms($class_name, $arguments = array())
401
-    {
402
-        // retrieve instantiated class
403
-        return $this->_load(
404
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
405
-            'EE_DMS_', $class_name, 'dms', $arguments, false, false
406
-        );
407
-    }
408
-
409
-
410
-
411
-    /**
412
-     *    loads object creating classes - must be singletons
413
-     *
414
-     * @param string $class_name - simple class name ie: attendee
415
-     * @param mixed  $arguments  - an array of arguments to pass to the class
416
-     * @param bool   $from_db    - deprecated
417
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then set this to FALSE (ie. when instantiating model objects from client in a loop)
418
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
419
-     * @return EE_Base_Class | bool
420
-     */
421
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
422
-    {
423
-        $paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
424
-            EE_CORE,
425
-            EE_CLASSES,
426
-            EE_BUSINESS,
427
-        ));
428
-        // retrieve instantiated class
429
-        return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $cache, $load_only);
430
-    }
431
-
432
-
433
-
434
-    /**
435
-     *    loads helper classes - must be singletons
436
-     *
437
-     * @param string $class_name - simple class name ie: price
438
-     * @param mixed  $arguments
439
-     * @param bool   $load_only
440
-     * @return EEH_Base | bool
441
-     */
442
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
443
-    {
444
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
445
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
446
-        // retrieve instantiated class
447
-        return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, true, $load_only);
448
-    }
449
-
450
-
451
-
452
-    /**
453
-     *    loads core classes - must be singletons
454
-     *
455
-     * @access    public
456
-     * @param string $class_name - simple class name ie: session
457
-     * @param mixed  $arguments
458
-     * @param bool   $load_only
459
-     * @param bool   $cache      whether to cache the object or not.
460
-     * @return mixed
461
-     */
462
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
463
-    {
464
-        $paths = array(
465
-            EE_LIBRARIES,
466
-            EE_LIBRARIES . 'messages' . DS,
467
-            EE_LIBRARIES . 'shortcodes' . DS,
468
-            EE_LIBRARIES . 'qtips' . DS,
469
-            EE_LIBRARIES . 'payment_methods' . DS,
470
-        );
471
-        // retrieve instantiated class
472
-        return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, $cache, $load_only);
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     *    loads model classes - must be singletons
479
-     *
480
-     * @param string $class_name - simple class name ie: price
481
-     * @param mixed  $arguments
482
-     * @param bool   $load_only
483
-     * @return EEM_Base | bool
484
-     */
485
-    public function load_model($class_name, $arguments = array(), $load_only = false)
486
-    {
487
-        $paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
488
-            EE_MODELS,
489
-            EE_CORE,
490
-        ));
491
-        // retrieve instantiated class
492
-        return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, true, $load_only);
493
-    }
494
-
495
-
496
-
497
-    /**
498
-     *    loads model classes - must be singletons
499
-     *
500
-     * @param string $class_name - simple class name ie: price
501
-     * @param mixed  $arguments
502
-     * @param bool   $load_only
503
-     * @return mixed | bool
504
-     */
505
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
506
-    {
507
-        $paths = array(
508
-            EE_MODELS . 'fields' . DS,
509
-            EE_MODELS . 'helpers' . DS,
510
-            EE_MODELS . 'relations' . DS,
511
-            EE_MODELS . 'strategies' . DS,
512
-        );
513
-        // retrieve instantiated class
514
-        return $this->_load($paths, 'EE_', $class_name, '', $arguments, true, $load_only);
515
-    }
516
-
517
-
518
-
519
-    /**
520
-     * Determines if $model_name is the name of an actual EE model.
521
-     *
522
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
523
-     * @return boolean
524
-     */
525
-    public function is_model_name($model_name)
526
-    {
527
-        return isset($this->models[$model_name]) ? true : false;
528
-    }
529
-
530
-
531
-
532
-    /**
533
-     *    generic class loader
534
-     *
535
-     * @param string $path_to_file - directory path to file location, not including filename
536
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
537
-     * @param string $type         - file type - core? class? helper? model?
538
-     * @param mixed  $arguments
539
-     * @param bool   $load_only
540
-     * @return mixed
541
-     */
542
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
543
-    {
544
-        // retrieve instantiated class
545
-        return $this->_load($path_to_file, '', $file_name, $type, $arguments, true, $load_only);
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     *    load_addon
552
-     *
553
-     * @param string $path_to_file - directory path to file location, not including filename
554
-     * @param string $class_name   - full class name  ie:  My_Class
555
-     * @param string $type         - file type - core? class? helper? model?
556
-     * @param mixed  $arguments
557
-     * @param bool   $load_only
558
-     * @return EE_Addon
559
-     */
560
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
561
-    {
562
-        // retrieve instantiated class
563
-        return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, true, $load_only);
564
-    }
565
-
566
-
567
-
568
-    /**
569
-     * instantiates, caches, and automatically resolves dependencies
570
-     * for classes that use a Fully Qualified Class Name.
571
-     * if the class is not capable of being loaded using PSR-4 autoloading,
572
-     * then you need to use one of the existing load_*() methods
573
-     * which can resolve the classname and filepath from the passed arguments
574
-     *
575
-     * @param bool|string $class_name   Fully Qualified Class Name
576
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
577
-     * @param bool        $cache        whether to cache the instantiated object for reuse
578
-     * @param bool        $from_db      some classes are instantiated from the db
579
-     *                                  and thus call a different method to instantiate
580
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
581
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
582
-     * @return mixed                    null = failure to load or instantiate class object.
583
-     *                                  object = class loaded and instantiated successfully.
584
-     *                                  bool = fail or success when $load_only is true
585
-     */
586
-    public function create(
587
-        $class_name = false,
588
-        $arguments = array(),
589
-        $cache = true,
590
-        $load_only = false,
591
-        $addon = false
592
-    ) {
593
-        $class_name = ltrim($class_name, '\\');
594
-        $class_name = $this->_dependency_map->get_alias($class_name);
595
-        if ( ! class_exists($class_name)) {
596
-            // maybe the class is registered with a preceding \
597
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
598
-            // still doesn't exist ?
599
-            if ( ! class_exists($class_name)) {
600
-                return null;
601
-            }
602
-        }
603
-        // if we're only loading the class and it already exists, then let's just return true immediately
604
-        if ($load_only) {
605
-            return true;
606
-        }
607
-        $addon = $addon ? 'addon' : '';
608
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
609
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
610
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
611
-        if ($this->_cache_on && $cache && ! $load_only) {
612
-            // return object if it's already cached
613
-            $cached_class = $this->_get_cached_class($class_name, $addon);
614
-            if ($cached_class !== null) {
615
-                return $cached_class;
616
-            }
617
-        }
618
-        // instantiate the requested object
619
-        $class_obj = $this->_create_object($class_name, $arguments, $addon);
620
-        if ($this->_cache_on && $cache) {
621
-            // save it for later... kinda like gum  { : $
622
-            $this->_set_cached_class($class_obj, $class_name, $addon);
623
-        }
624
-        $this->_cache_on = true;
625
-        return $class_obj;
626
-    }
627
-
628
-
629
-
630
-    /**
631
-     * instantiates, caches, and injects dependencies for classes
632
-     *
633
-     * @param array       $file_paths   an array of paths to folders to look in
634
-     * @param string      $class_prefix EE  or EEM or... ???
635
-     * @param bool|string $class_name   $class name
636
-     * @param string      $type         file type - core? class? helper? model?
637
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
638
-     * @param bool        $cache        whether to cache the instantiated object for reuse
639
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
640
-     * @return null|object|bool         null = failure to load or instantiate class object.
641
-     *                                  object = class loaded and instantiated successfully.
642
-     *                                  bool = fail or success when $load_only is true
643
-     */
644
-    protected function _load(
645
-        $file_paths = array(),
646
-        $class_prefix = 'EE_',
647
-        $class_name = false,
648
-        $type = 'class',
649
-        $arguments = array(),
650
-        $cache = true,
651
-        $load_only = false
652
-    ) {
653
-        $class_name = ltrim($class_name, '\\');
654
-        // strip php file extension
655
-        $class_name = str_replace('.php', '', trim($class_name));
656
-        // does the class have a prefix ?
657
-        if ( ! empty($class_prefix) && $class_prefix != 'addon') {
658
-            // make sure $class_prefix is uppercase
659
-            $class_prefix = strtoupper(trim($class_prefix));
660
-            // add class prefix ONCE!!!
661
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
662
-        }
663
-        $class_name = $this->_dependency_map->get_alias($class_name);
664
-        $class_exists = class_exists($class_name);
665
-        // if we're only loading the class and it already exists, then let's just return true immediately
666
-        if ($load_only && $class_exists) {
667
-            return true;
668
-        }
669
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
670
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
671
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
672
-        if ($this->_cache_on && $cache && ! $load_only) {
673
-            // return object if it's already cached
674
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
675
-            if ($cached_class !== null) {
676
-                return $cached_class;
677
-            }
678
-        }
679
-        // if the class doesn't already exist.. then we need to try and find the file and load it
680
-        if ( ! $class_exists) {
681
-            // get full path to file
682
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
683
-            // load the file
684
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
685
-            // if loading failed, or we are only loading a file but NOT instantiating an object
686
-            if ( ! $loaded || $load_only) {
687
-                // return boolean if only loading, or null if an object was expected
688
-                return $load_only ? $loaded : null;
689
-            }
690
-        }
691
-        // instantiate the requested object
692
-        $class_obj = $this->_create_object($class_name, $arguments, $type);
693
-        if ($this->_cache_on && $cache) {
694
-            // save it for later... kinda like gum  { : $
695
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix);
696
-        }
697
-        $this->_cache_on = true;
698
-        return $class_obj;
699
-    }
700
-
701
-
702
-
703
-
704
-    /**
705
-     * _get_cached_class
706
-     * attempts to find a cached version of the requested class
707
-     * by looking in the following places:
708
-     *        $this->{$class_abbreviation}            ie:    $this->CART
709
-     *        $this->{$class_name}                        ie:    $this->Some_Class
710
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
711
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
712
-     *
713
-     * @access protected
714
-     * @param string $class_name
715
-     * @param string $class_prefix
716
-     * @return mixed
717
-     */
718
-    protected function _get_cached_class($class_name, $class_prefix = '')
719
-    {
720
-        if ($class_name === 'EE_Registry') {
721
-            return $this;
722
-        }
723
-        // have to specify something, but not anything that will conflict
724
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
-            ? $this->_class_abbreviations[ $class_name ]
726
-            : 'FANCY_BATMAN_PANTS';
727
-        $class_name = str_replace('\\', '_', $class_name);
728
-        // check if class has already been loaded, and return it if it has been
729
-        if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
730
-            return $this->{$class_abbreviation};
731
-        }
732
-        if (isset ($this->{$class_name})) {
733
-            return $this->{$class_name};
734
-        }
735
-        if (isset ($this->LIB->{$class_name})) {
736
-            return $this->LIB->{$class_name};
737
-        }
738
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
739
-            return $this->addons->{$class_name};
740
-        }
741
-        return null;
742
-    }
743
-
744
-
745
-
746
-    /**
747
-     * removes a cached version of the requested class
748
-     *
749
-     * @param string $class_name
750
-     * @param boolean $addon
751
-     * @return boolean
752
-     */
753
-    public function clear_cached_class($class_name, $addon = false)
754
-    {
755
-        // have to specify something, but not anything that will conflict
756
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
-            ? $this->_class_abbreviations[ $class_name ]
758
-            : 'FANCY_BATMAN_PANTS';
759
-        $class_name = str_replace('\\', '_', $class_name);
760
-        // check if class has already been loaded, and return it if it has been
761
-        if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
762
-            $this->{$class_abbreviation} = null;
763
-            return true;
764
-        }
765
-        if (isset($this->{$class_name})) {
766
-            $this->{$class_name} = null;
767
-            return true;
768
-        }
769
-        if (isset($this->LIB->{$class_name})) {
770
-            unset($this->LIB->{$class_name});
771
-            return true;
772
-        }
773
-        if ($addon && isset($this->addons->{$class_name})) {
774
-            unset($this->addons->{$class_name});
775
-            return true;
776
-        }
777
-        return false;
778
-    }
779
-
780
-
781
-    /**
782
-     * _resolve_path
783
-     * attempts to find a full valid filepath for the requested class.
784
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
785
-     * then returns that path if the target file has been found and is readable
786
-     *
787
-     * @access protected
788
-     * @param string $class_name
789
-     * @param string $type
790
-     * @param array  $file_paths
791
-     * @return string | bool
792
-     */
793
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
794
-    {
795
-        // make sure $file_paths is an array
796
-        $file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
797
-        // cycle thru paths
798
-        foreach ($file_paths as $key => $file_path) {
799
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
800
-            $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801
-            // prep file type
802
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
803
-            // build full file path
804
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
805
-            //does the file exist and can be read ?
806
-            if (is_readable($file_paths[$key])) {
807
-                return $file_paths[$key];
808
-            }
809
-        }
810
-        return false;
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * _require_file
817
-     * basically just performs a require_once()
818
-     * but with some error handling
819
-     *
820
-     * @access protected
821
-     * @param  string $path
822
-     * @param  string $class_name
823
-     * @param  string $type
824
-     * @param  array  $file_paths
825
-     * @return boolean
826
-     * @throws \EE_Error
827
-     */
828
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
829
-    {
830
-        // don't give up! you gotta...
831
-        try {
832
-            //does the file exist and can it be read ?
833
-            if ( ! $path) {
834
-                // so sorry, can't find the file
835
-                throw new EE_Error (
836
-                    sprintf(
837
-                        __('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
838
-                        trim($type, '.'),
839
-                        $class_name,
840
-                        '<br />' . implode(',<br />', $file_paths)
841
-                    )
842
-                );
843
-            }
844
-            // get the file
845
-            require_once($path);
846
-            // if the class isn't already declared somewhere
847
-            if (class_exists($class_name, false) === false) {
848
-                // so sorry, not a class
849
-                throw new EE_Error(
850
-                    sprintf(
851
-                        __('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
852
-                        $type,
853
-                        $path,
854
-                        $class_name
855
-                    )
856
-                );
857
-            }
858
-        } catch (EE_Error $e) {
859
-            $e->get_error();
860
-            return false;
861
-        }
862
-        return true;
863
-    }
864
-
865
-
866
-
867
-    /**
868
-     * _create_object
869
-     * Attempts to instantiate the requested class via any of the
870
-     * commonly used instantiation methods employed throughout EE.
871
-     * The priority for instantiation is as follows:
872
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
873
-     *        - model objects via their 'new_instance_from_db' method
874
-     *        - model objects via their 'new_instance' method
875
-     *        - "singleton" classes" via their 'instance' method
876
-     *    - standard instantiable classes via their __constructor
877
-     * Prior to instantiation, if the classname exists in the dependency_map,
878
-     * then the constructor for the requested class will be examined to determine
879
-     * if any dependencies exist, and if they can be injected.
880
-     * If so, then those classes will be added to the array of arguments passed to the constructor
881
-     *
882
-     * @access protected
883
-     * @param string $class_name
884
-     * @param array  $arguments
885
-     * @param string $type
886
-     * @return null | object
887
-     * @throws \EE_Error
888
-     */
889
-    protected function _create_object($class_name, $arguments = array(), $type = '')
890
-    {
891
-        $class_obj = null;
892
-        $instantiation_mode = '0) none';
893
-        // don't give up! you gotta...
894
-        try {
895
-            // create reflection
896
-            $reflector = $this->get_ReflectionClass($class_name);
897
-            // make sure arguments are an array
898
-            $arguments = is_array($arguments) ? $arguments : array($arguments);
899
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
900
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
901
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
902
-                ? $arguments
903
-                : array($arguments);
904
-            // attempt to inject dependencies ?
905
-            if ($this->_dependency_map->has($class_name)) {
906
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
907
-            }
908
-            // instantiate the class if possible
909
-            if ($reflector->isAbstract()) {
910
-                // nothing to instantiate, loading file was enough
911
-                // does not throw an exception so $instantiation_mode is unused
912
-                // $instantiation_mode = "1) no constructor abstract class";
913
-                $class_obj = true;
914
-            } else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
915
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
916
-                $instantiation_mode = "2) no constructor but instantiable";
917
-                $class_obj = $reflector->newInstance();
918
-            } else if (method_exists($class_name, 'new_instance')) {
919
-                $instantiation_mode = "4) new_instance()";
920
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
921
-            } else if (method_exists($class_name, 'instance')) {
922
-                $instantiation_mode = "5) instance()";
923
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
924
-            } else if ($reflector->isInstantiable()) {
925
-                $instantiation_mode = "6) constructor";
926
-                $class_obj = $reflector->newInstanceArgs($arguments);
927
-            } else {
928
-                // heh ? something's not right !
929
-                throw new EE_Error(
930
-                    sprintf(
931
-                        __('The %s file %s could not be instantiated.', 'event_espresso'),
932
-                        $type,
933
-                        $class_name
934
-                    )
935
-                );
936
-            }
937
-        } catch (Exception $e) {
938
-            if ( ! $e instanceof EE_Error) {
939
-                $e = new EE_Error(
940
-                    sprintf(
941
-                        __('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
942
-                        $class_name,
943
-                        '<br />',
944
-                        $e->getMessage(),
945
-                        $instantiation_mode
946
-                    )
947
-                );
948
-            }
949
-            $e->get_error();
950
-        }
951
-        return $class_obj;
952
-    }
953
-
954
-
955
-
956
-    /**
957
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
958
-     * @param array $array
959
-     * @return bool
960
-     */
961
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
962
-    {
963
-        return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
964
-    }
965
-
966
-
967
-
968
-    /**
969
-     * getReflectionClass
970
-     * checks if a ReflectionClass object has already been generated for a class
971
-     * and returns that instead of creating a new one
972
-     *
973
-     * @access public
974
-     * @param string $class_name
975
-     * @return ReflectionClass
976
-     */
977
-    public function get_ReflectionClass($class_name)
978
-    {
979
-        if (
980
-            ! isset($this->_reflectors[$class_name])
981
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
982
-        ) {
983
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
984
-        }
985
-        return $this->_reflectors[$class_name];
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * _resolve_dependencies
992
-     * examines the constructor for the requested class to determine
993
-     * if any dependencies exist, and if they can be injected.
994
-     * If so, then those classes will be added to the array of arguments passed to the constructor
995
-     * PLZ NOTE: this is achieved by type hinting the constructor params
996
-     * For example:
997
-     *        if attempting to load a class "Foo" with the following constructor:
998
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
999
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1000
-     *        but only IF they are NOT already present in the incoming arguments array,
1001
-     *        and the correct classes can be loaded
1002
-     *
1003
-     * @access protected
1004
-     * @param ReflectionClass $reflector
1005
-     * @param string          $class_name
1006
-     * @param array           $arguments
1007
-     * @return array
1008
-     * @throws \ReflectionException
1009
-     */
1010
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1011
-    {
1012
-        // let's examine the constructor
1013
-        $constructor = $reflector->getConstructor();
1014
-        // whu? huh? nothing?
1015
-        if ( ! $constructor) {
1016
-            return $arguments;
1017
-        }
1018
-        // get constructor parameters
1019
-        $params = $constructor->getParameters();
1020
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1021
-        $argument_keys = array_keys($arguments);
1022
-        // now loop thru all of the constructors expected parameters
1023
-        foreach ($params as $index => $param) {
1024
-            // is this a dependency for a specific class ?
1025
-            $param_class = $param->getClass() ? $param->getClass()->name : null;
1026
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1027
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1028
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1029
-                : $param_class;
1030
-            if (
1031
-                // param is not even a class
1032
-                empty($param_class)
1033
-                // and something already exists in the incoming arguments for this param
1034
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1035
-            ) {
1036
-                // so let's skip this argument and move on to the next
1037
-                continue;
1038
-            }
1039
-            if (
1040
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1041
-                ! empty($param_class)
1042
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1043
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1044
-            ) {
1045
-                // skip this argument and move on to the next
1046
-                continue;
1047
-            }
1048
-            if (
1049
-                // parameter is type hinted as a class, and should be injected
1050
-                ! empty($param_class)
1051
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1052
-            ) {
1053
-                $arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1054
-            } else {
1055
-                try {
1056
-                    $arguments[$index] = $param->getDefaultValue();
1057
-                } catch (ReflectionException $e) {
1058
-                    throw new ReflectionException(
1059
-                        sprintf(
1060
-                            __('%1$s for parameter "$%2$s"', 'event_espresso'),
1061
-                            $e->getMessage(),
1062
-                            $param->getName()
1063
-                        )
1064
-                    );
1065
-                }
1066
-            }
1067
-        }
1068
-        return $arguments;
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     * @access protected
1075
-     * @param string $class_name
1076
-     * @param string $param_class
1077
-     * @param array  $arguments
1078
-     * @param mixed  $index
1079
-     * @return array
1080
-     */
1081
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1082
-    {
1083
-        $dependency = null;
1084
-        // should dependency be loaded from cache ?
1085
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1086
-                    !== EE_Dependency_Map::load_new_object
1087
-            ? true
1088
-            : false;
1089
-        // we might have a dependency...
1090
-        // let's MAYBE try and find it in our cache if that's what's been requested
1091
-        $cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1092
-        // and grab it if it exists
1093
-        if ($cached_class instanceof $param_class) {
1094
-            $dependency = $cached_class;
1095
-        } else if ($param_class !== $class_name) {
1096
-            // obtain the loader method from the dependency map
1097
-            $loader = $this->_dependency_map->class_loader($param_class);
1098
-            // is loader a custom closure ?
1099
-            if ($loader instanceof Closure) {
1100
-                $dependency = $loader();
1101
-            } else {
1102
-                // set the cache on property for the recursive loading call
1103
-                $this->_cache_on = $cache_on;
1104
-                // if not, then let's try and load it via the registry
1105
-                if ($loader && method_exists($this, $loader)) {
1106
-                    $dependency = $this->{$loader}($param_class);
1107
-                } else {
1108
-                    $dependency = $this->create($param_class, array(), $cache_on);
1109
-                }
1110
-            }
1111
-        }
1112
-        // did we successfully find the correct dependency ?
1113
-        if ($dependency instanceof $param_class) {
1114
-            // then let's inject it into the incoming array of arguments at the correct location
1115
-            if (isset($argument_keys[$index])) {
1116
-                $arguments[$argument_keys[$index]] = $dependency;
1117
-            } else {
1118
-                $arguments[$index] = $dependency;
1119
-            }
1120
-        }
1121
-        return $arguments;
1122
-    }
1123
-
1124
-
1125
-
1126
-    /**
1127
-     * _set_cached_class
1128
-     * attempts to cache the instantiated class locally
1129
-     * in one of the following places, in the following order:
1130
-     *        $this->{class_abbreviation}   ie:    $this->CART
1131
-     *        $this->{$class_name}          ie:    $this->Some_Class
1132
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1133
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1134
-     *
1135
-     * @access protected
1136
-     * @param object $class_obj
1137
-     * @param string $class_name
1138
-     * @param string $class_prefix
1139
-     * @return void
1140
-     */
1141
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1142
-    {
1143
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1144
-            return;
1145
-        }
1146
-        // return newly instantiated class
1147
-        if (isset($this->_class_abbreviations[$class_name])) {
1148
-            $class_abbreviation = $this->_class_abbreviations[$class_name];
1149
-            $this->{$class_abbreviation} = $class_obj;
1150
-            return;
1151
-        }
1152
-        $class_name = str_replace('\\', '_', $class_name);
1153
-        if (property_exists($this, $class_name)) {
1154
-            $this->{$class_name} = $class_obj;
1155
-            return;
1156
-        }
1157
-        if ($class_prefix === 'addon') {
1158
-            $this->addons->{$class_name} = $class_obj;
1159
-            return;
1160
-        }
1161
-        $this->LIB->{$class_name} = $class_obj;
1162
-    }
1163
-
1164
-
1165
-
1166
-    /**
1167
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1168
-     *
1169
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1170
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1171
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1172
-     * @param array  $arguments
1173
-     * @return object
1174
-     */
1175
-    public static function factory($classname, $arguments = array())
1176
-    {
1177
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1178
-        if ($loader instanceof Closure) {
1179
-            return $loader($arguments);
1180
-        }
1181
-        if (method_exists(EE_Registry::instance(), $loader)) {
1182
-            return EE_Registry::instance()->{$loader}($classname, $arguments);
1183
-        }
1184
-        return null;
1185
-    }
1186
-
1187
-
1188
-
1189
-    /**
1190
-     * Gets the addon by its name/slug (not classname. For that, just
1191
-     * use the classname as the property name on EE_Config::instance()->addons)
1192
-     *
1193
-     * @param string $name
1194
-     * @return EE_Addon
1195
-     */
1196
-    public function get_addon_by_name($name)
1197
-    {
1198
-        foreach ($this->addons as $addon) {
1199
-            if ($addon->name() == $name) {
1200
-                return $addon;
1201
-            }
1202
-        }
1203
-        return null;
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their name() function) They're already available on EE_Config::instance()->addons as properties, where each property's name is
1210
-     * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1211
-     *
1212
-     * @return EE_Addon[] where the KEYS are the addon's name()
1213
-     */
1214
-    public function get_addons_by_name()
1215
-    {
1216
-        $addons = array();
1217
-        foreach ($this->addons as $addon) {
1218
-            $addons[$addon->name()] = $addon;
1219
-        }
1220
-        return $addons;
1221
-    }
1222
-
1223
-
1224
-
1225
-    /**
1226
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1227
-     * a stale copy of it around
1228
-     *
1229
-     * @param string $model_name
1230
-     * @return \EEM_Base
1231
-     * @throws \EE_Error
1232
-     */
1233
-    public function reset_model($model_name)
1234
-    {
1235
-        $model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1236
-        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1237
-            return null;
1238
-        }
1239
-        //get that model reset it and make sure we nuke the old reference to it
1240
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1241
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1242
-        } else {
1243
-            throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1244
-        }
1245
-        return $this->LIB->{$model_class_name};
1246
-    }
1247
-
1248
-
1249
-
1250
-    /**
1251
-     * Resets the registry.
1252
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1253
-     * is used in a multisite install.  Here is a list of things that are NOT reset.
1254
-     * - $_dependency_map
1255
-     * - $_class_abbreviations
1256
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1257
-     * - $REQ:  Still on the same request so no need to change.
1258
-     * - $CAP: There is no site specific state in the EE_Capability class.
1259
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1260
-     *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1261
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1262
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1263
-     *             switch or on the restore.
1264
-     * - $modules
1265
-     * - $shortcodes
1266
-     * - $widgets
1267
-     *
1268
-     * @param boolean $hard             whether to reset data in the database too, or just refresh
1269
-     *                                  the Registry to its state at the beginning of the request
1270
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1271
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1272
-     *                                  currently reinstantiate the singletons at the moment)
1273
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1274
-     *                                  code instead can just change the model context to a different blog id if necessary
1275
-     * @return EE_Registry
1276
-     */
1277
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1278
-    {
1279
-        $instance = self::instance();
1280
-        $instance->_cache_on = true;
1281
-        // reset some "special" classes
1282
-        EEH_Activation::reset();
1283
-        $instance->CFG = $instance->CFG->reset($hard, $reinstantiate);
1284
-        $instance->CART = null;
1285
-        $instance->MRM = null;
1286
-        $instance->AssetsRegistry = null;
1287
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1288
-        //messages reset
1289
-        EED_Messages::reset();
1290
-        //handle of objects cached on LIB
1291
-        foreach (array('LIB', 'modules') as $cache) {
1292
-            foreach ($instance->{$cache} as $class_name => $class) {
1293
-                if (EE_Registry::_reset_and_unset_object($class, $reset_models)) {
1294
-                    unset($instance->{$cache}->{$class_name});
1295
-                }
1296
-            }
1297
-        }
1298
-        return $instance;
1299
-    }
1300
-
1301
-
1302
-
1303
-    /**
1304
-     * if passed object implements ResettableInterface, then call it's reset() method
1305
-     * if passed object implements InterminableInterface, then return false,
1306
-     * to indicate that it should NOT be cleared from the Registry cache
1307
-     *
1308
-     * @param      $object
1309
-     * @param bool $reset_models
1310
-     * @return bool returns true if cached object should be unset
1311
-     */
1312
-    private static function _reset_and_unset_object($object, $reset_models)
1313
-    {
1314
-        if (! is_object($object)) {
1315
-            // don't unset anything that's not an object
1316
-            return false;
1317
-        }
1318
-        if ($object instanceof EED_Module) {
1319
-            $object::reset();
1320
-            // don't unset modules
1321
-            return false;
1322
-        }
1323
-        if ($object instanceof ResettableInterface) {
1324
-            if ($object instanceof EEM_Base) {
1325
-                if ($reset_models) {
1326
-                    $object->reset();
1327
-                    return true;
1328
-                }
1329
-                return false;
1330
-            }
1331
-            $object->reset();
1332
-            return true;
1333
-        }
1334
-        if ( ! $object instanceof InterminableInterface) {
1335
-            return true;
1336
-        }
1337
-        return false;
1338
-    }
1339
-
1340
-
1341
-
1342
-    /**
1343
-     * @override magic methods
1344
-     * @return void
1345
-     */
1346
-    public final function __destruct()
1347
-    {
1348
-    }
1349
-
1350
-
1351
-
1352
-    /**
1353
-     * @param $a
1354
-     * @param $b
1355
-     */
1356
-    public final function __call($a, $b)
1357
-    {
1358
-    }
1359
-
1360
-
1361
-
1362
-    /**
1363
-     * @param $a
1364
-     */
1365
-    public final function __get($a)
1366
-    {
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * @param $a
1373
-     * @param $b
1374
-     */
1375
-    public final function __set($a, $b)
1376
-    {
1377
-    }
1378
-
1379
-
1380
-
1381
-    /**
1382
-     * @param $a
1383
-     */
1384
-    public final function __isset($a)
1385
-    {
1386
-    }
22
+	/**
23
+	 *    EE_Registry Object
24
+	 *
25
+	 * @var EE_Registry $_instance
26
+	 * @access    private
27
+	 */
28
+	private static $_instance = null;
29
+
30
+	/**
31
+	 * @var EE_Dependency_Map $_dependency_map
32
+	 * @access    protected
33
+	 */
34
+	protected $_dependency_map = null;
35
+
36
+	/**
37
+	 * @var array $_class_abbreviations
38
+	 * @access    protected
39
+	 */
40
+	protected $_class_abbreviations = array();
41
+
42
+	/**
43
+	 * @access public
44
+	 * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
45
+	 */
46
+	public $BUS;
47
+
48
+	/**
49
+	 *    EE_Cart Object
50
+	 *
51
+	 * @access    public
52
+	 * @var    EE_Cart $CART
53
+	 */
54
+	public $CART = null;
55
+
56
+	/**
57
+	 *    EE_Config Object
58
+	 *
59
+	 * @access    public
60
+	 * @var    EE_Config $CFG
61
+	 */
62
+	public $CFG = null;
63
+
64
+	/**
65
+	 * EE_Network_Config Object
66
+	 *
67
+	 * @access public
68
+	 * @var EE_Network_Config $NET_CFG
69
+	 */
70
+	public $NET_CFG = null;
71
+
72
+	/**
73
+	 *    StdClass object for storing library classes in
74
+	 *
75
+	 * @public LIB
76
+	 * @var StdClass $LIB
77
+	 */
78
+	public $LIB = null;
79
+
80
+	/**
81
+	 *    EE_Request_Handler Object
82
+	 *
83
+	 * @access    public
84
+	 * @var    EE_Request_Handler $REQ
85
+	 */
86
+	public $REQ = null;
87
+
88
+	/**
89
+	 *    EE_Session Object
90
+	 *
91
+	 * @access    public
92
+	 * @var    EE_Session $SSN
93
+	 */
94
+	public $SSN = null;
95
+
96
+	/**
97
+	 * holds the ee capabilities object.
98
+	 *
99
+	 * @since 4.5.0
100
+	 * @var EE_Capabilities
101
+	 */
102
+	public $CAP = null;
103
+
104
+	/**
105
+	 * holds the EE_Message_Resource_Manager object.
106
+	 *
107
+	 * @since 4.9.0
108
+	 * @var EE_Message_Resource_Manager
109
+	 */
110
+	public $MRM = null;
111
+
112
+
113
+	/**
114
+	 * Holds the Assets Registry instance
115
+	 * @var Registry
116
+	 */
117
+	public $AssetsRegistry = null;
118
+
119
+	/**
120
+	 *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
121
+	 *
122
+	 * @access    public
123
+	 * @var    EE_Addon[]
124
+	 */
125
+	public $addons = null;
126
+
127
+	/**
128
+	 *    $models
129
+	 * @access    public
130
+	 * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
131
+	 */
132
+	public $models = array();
133
+
134
+	/**
135
+	 *    $modules
136
+	 * @access    public
137
+	 * @var    EED_Module[] $modules
138
+	 */
139
+	public $modules = null;
140
+
141
+	/**
142
+	 *    $shortcodes
143
+	 * @access    public
144
+	 * @var    EES_Shortcode[] $shortcodes
145
+	 */
146
+	public $shortcodes = null;
147
+
148
+	/**
149
+	 *    $widgets
150
+	 * @access    public
151
+	 * @var    WP_Widget[] $widgets
152
+	 */
153
+	public $widgets = null;
154
+
155
+	/**
156
+	 * $non_abstract_db_models
157
+	 * @access public
158
+	 * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
159
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
160
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
161
+	 * classnames (eg "EEM_Event")
162
+	 */
163
+	public $non_abstract_db_models = array();
164
+
165
+
166
+	/**
167
+	 *    $i18n_js_strings - internationalization for JS strings
168
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
169
+	 *    in js file:  var translatedString = eei18n.string_key;
170
+	 *
171
+	 * @access    public
172
+	 * @var    array
173
+	 */
174
+	public static $i18n_js_strings = array();
175
+
176
+
177
+	/**
178
+	 *    $main_file - path to espresso.php
179
+	 *
180
+	 * @access    public
181
+	 * @var    array
182
+	 */
183
+	public $main_file;
184
+
185
+	/**
186
+	 * array of ReflectionClass objects where the key is the class name
187
+	 *
188
+	 * @access    public
189
+	 * @var ReflectionClass[]
190
+	 */
191
+	public $_reflectors;
192
+
193
+	/**
194
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
195
+	 *
196
+	 * @access    protected
197
+	 * @var boolean $_cache_on
198
+	 */
199
+	protected $_cache_on = true;
200
+
201
+
202
+
203
+	/**
204
+	 * @singleton method used to instantiate class object
205
+	 * @access    public
206
+	 * @param  \EE_Dependency_Map $dependency_map
207
+	 * @return \EE_Registry instance
208
+	 */
209
+	public static function instance(\EE_Dependency_Map $dependency_map = null)
210
+	{
211
+		// check if class object is instantiated
212
+		if ( ! self::$_instance instanceof EE_Registry) {
213
+			self::$_instance = new EE_Registry($dependency_map);
214
+		}
215
+		return self::$_instance;
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 *protected constructor to prevent direct creation
222
+	 *
223
+	 * @Constructor
224
+	 * @access protected
225
+	 * @param  \EE_Dependency_Map $dependency_map
226
+	 */
227
+	protected function __construct(\EE_Dependency_Map $dependency_map)
228
+	{
229
+		$this->_dependency_map = $dependency_map;
230
+		$this->LIB = new stdClass();
231
+		$this->addons = new stdClass();
232
+		$this->modules = new stdClass();
233
+		$this->shortcodes = new stdClass();
234
+		$this->widgets = new stdClass();
235
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 * initialize
242
+	 */
243
+	public function initialize()
244
+	{
245
+		$this->_class_abbreviations = apply_filters(
246
+			'FHEE__EE_Registry____construct___class_abbreviations',
247
+			array(
248
+				'EE_Config'                                       => 'CFG',
249
+				'EE_Session'                                      => 'SSN',
250
+				'EE_Capabilities'                                 => 'CAP',
251
+				'EE_Cart'                                         => 'CART',
252
+				'EE_Network_Config'                               => 'NET_CFG',
253
+				'EE_Request_Handler'                              => 'REQ',
254
+				'EE_Message_Resource_Manager'                     => 'MRM',
255
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
256
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
257
+			)
258
+		);
259
+		$this->load_core('Base', array(), true);
260
+		// add our request and response objects to the cache
261
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
262
+		$this->_set_cached_class(
263
+			$request_loader(),
264
+			'EE_Request'
265
+		);
266
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
267
+		$this->_set_cached_class(
268
+			$response_loader(),
269
+			'EE_Response'
270
+		);
271
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 *    init
278
+	 *
279
+	 * @access    public
280
+	 * @return    void
281
+	 */
282
+	public function init()
283
+	{
284
+		// Get current page protocol
285
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
286
+		// Output admin-ajax.php URL with same protocol as current page
287
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
288
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * localize_i18n_js_strings
295
+	 *
296
+	 * @return string
297
+	 */
298
+	public static function localize_i18n_js_strings()
299
+	{
300
+		$i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
301
+		foreach ($i18n_js_strings as $key => $value) {
302
+			if (is_scalar($value)) {
303
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
304
+			}
305
+		}
306
+		return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * @param $module
313
+	 * @throws ReflectionException
314
+	 */
315
+	public function add_module($module)
316
+	{
317
+		if ($module instanceof EED_Module) {
318
+			$module_class = get_class($module);
319
+			$this->modules->{$module_class} = $module;
320
+		} else {
321
+			if ( ! class_exists('EE_Module_Request_Router')) {
322
+				$this->load_core('Module_Request_Router');
323
+			}
324
+			EE_Module_Request_Router::module_factory($module);
325
+		}
326
+	}
327
+
328
+
329
+
330
+	/**
331
+	 * @param string $module_name
332
+	 * @return mixed EED_Module | NULL
333
+	 */
334
+	public function get_module($module_name = '')
335
+	{
336
+		return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
337
+	}
338
+
339
+
340
+
341
+	/**
342
+	 *    loads core classes - must be singletons
343
+	 *
344
+	 * @access    public
345
+	 * @param string $class_name - simple class name ie: session
346
+	 * @param mixed  $arguments
347
+	 * @param bool   $load_only
348
+	 * @return mixed
349
+	 */
350
+	public function load_core($class_name, $arguments = array(), $load_only = false)
351
+	{
352
+		$core_paths = apply_filters(
353
+			'FHEE__EE_Registry__load_core__core_paths',
354
+			array(
355
+				EE_CORE,
356
+				EE_ADMIN,
357
+				EE_CPTS,
358
+				EE_CORE . 'data_migration_scripts' . DS,
359
+				EE_CORE . 'request_stack' . DS,
360
+				EE_CORE . 'middleware' . DS,
361
+			)
362
+		);
363
+		// retrieve instantiated class
364
+		return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, true, $load_only);
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 *    loads service classes
371
+	 *
372
+	 * @access    public
373
+	 * @param string $class_name - simple class name ie: session
374
+	 * @param mixed  $arguments
375
+	 * @param bool   $load_only
376
+	 * @return mixed
377
+	 */
378
+	public function load_service($class_name, $arguments = array(), $load_only = false)
379
+	{
380
+		$service_paths = apply_filters(
381
+			'FHEE__EE_Registry__load_service__service_paths',
382
+			array(
383
+				EE_CORE . 'services' . DS,
384
+			)
385
+		);
386
+		// retrieve instantiated class
387
+		return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, true, $load_only);
388
+	}
389
+
390
+
391
+
392
+	/**
393
+	 *    loads data_migration_scripts
394
+	 *
395
+	 * @access    public
396
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
397
+	 * @param mixed  $arguments
398
+	 * @return EE_Data_Migration_Script_Base|mixed
399
+	 */
400
+	public function load_dms($class_name, $arguments = array())
401
+	{
402
+		// retrieve instantiated class
403
+		return $this->_load(
404
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
405
+			'EE_DMS_', $class_name, 'dms', $arguments, false, false
406
+		);
407
+	}
408
+
409
+
410
+
411
+	/**
412
+	 *    loads object creating classes - must be singletons
413
+	 *
414
+	 * @param string $class_name - simple class name ie: attendee
415
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
416
+	 * @param bool   $from_db    - deprecated
417
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then set this to FALSE (ie. when instantiating model objects from client in a loop)
418
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
419
+	 * @return EE_Base_Class | bool
420
+	 */
421
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
422
+	{
423
+		$paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
424
+			EE_CORE,
425
+			EE_CLASSES,
426
+			EE_BUSINESS,
427
+		));
428
+		// retrieve instantiated class
429
+		return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $cache, $load_only);
430
+	}
431
+
432
+
433
+
434
+	/**
435
+	 *    loads helper classes - must be singletons
436
+	 *
437
+	 * @param string $class_name - simple class name ie: price
438
+	 * @param mixed  $arguments
439
+	 * @param bool   $load_only
440
+	 * @return EEH_Base | bool
441
+	 */
442
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
443
+	{
444
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
445
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
446
+		// retrieve instantiated class
447
+		return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, true, $load_only);
448
+	}
449
+
450
+
451
+
452
+	/**
453
+	 *    loads core classes - must be singletons
454
+	 *
455
+	 * @access    public
456
+	 * @param string $class_name - simple class name ie: session
457
+	 * @param mixed  $arguments
458
+	 * @param bool   $load_only
459
+	 * @param bool   $cache      whether to cache the object or not.
460
+	 * @return mixed
461
+	 */
462
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
463
+	{
464
+		$paths = array(
465
+			EE_LIBRARIES,
466
+			EE_LIBRARIES . 'messages' . DS,
467
+			EE_LIBRARIES . 'shortcodes' . DS,
468
+			EE_LIBRARIES . 'qtips' . DS,
469
+			EE_LIBRARIES . 'payment_methods' . DS,
470
+		);
471
+		// retrieve instantiated class
472
+		return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, $cache, $load_only);
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 *    loads model classes - must be singletons
479
+	 *
480
+	 * @param string $class_name - simple class name ie: price
481
+	 * @param mixed  $arguments
482
+	 * @param bool   $load_only
483
+	 * @return EEM_Base | bool
484
+	 */
485
+	public function load_model($class_name, $arguments = array(), $load_only = false)
486
+	{
487
+		$paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
488
+			EE_MODELS,
489
+			EE_CORE,
490
+		));
491
+		// retrieve instantiated class
492
+		return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, true, $load_only);
493
+	}
494
+
495
+
496
+
497
+	/**
498
+	 *    loads model classes - must be singletons
499
+	 *
500
+	 * @param string $class_name - simple class name ie: price
501
+	 * @param mixed  $arguments
502
+	 * @param bool   $load_only
503
+	 * @return mixed | bool
504
+	 */
505
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
506
+	{
507
+		$paths = array(
508
+			EE_MODELS . 'fields' . DS,
509
+			EE_MODELS . 'helpers' . DS,
510
+			EE_MODELS . 'relations' . DS,
511
+			EE_MODELS . 'strategies' . DS,
512
+		);
513
+		// retrieve instantiated class
514
+		return $this->_load($paths, 'EE_', $class_name, '', $arguments, true, $load_only);
515
+	}
516
+
517
+
518
+
519
+	/**
520
+	 * Determines if $model_name is the name of an actual EE model.
521
+	 *
522
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
523
+	 * @return boolean
524
+	 */
525
+	public function is_model_name($model_name)
526
+	{
527
+		return isset($this->models[$model_name]) ? true : false;
528
+	}
529
+
530
+
531
+
532
+	/**
533
+	 *    generic class loader
534
+	 *
535
+	 * @param string $path_to_file - directory path to file location, not including filename
536
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
537
+	 * @param string $type         - file type - core? class? helper? model?
538
+	 * @param mixed  $arguments
539
+	 * @param bool   $load_only
540
+	 * @return mixed
541
+	 */
542
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
543
+	{
544
+		// retrieve instantiated class
545
+		return $this->_load($path_to_file, '', $file_name, $type, $arguments, true, $load_only);
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 *    load_addon
552
+	 *
553
+	 * @param string $path_to_file - directory path to file location, not including filename
554
+	 * @param string $class_name   - full class name  ie:  My_Class
555
+	 * @param string $type         - file type - core? class? helper? model?
556
+	 * @param mixed  $arguments
557
+	 * @param bool   $load_only
558
+	 * @return EE_Addon
559
+	 */
560
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
561
+	{
562
+		// retrieve instantiated class
563
+		return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, true, $load_only);
564
+	}
565
+
566
+
567
+
568
+	/**
569
+	 * instantiates, caches, and automatically resolves dependencies
570
+	 * for classes that use a Fully Qualified Class Name.
571
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
572
+	 * then you need to use one of the existing load_*() methods
573
+	 * which can resolve the classname and filepath from the passed arguments
574
+	 *
575
+	 * @param bool|string $class_name   Fully Qualified Class Name
576
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
577
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
578
+	 * @param bool        $from_db      some classes are instantiated from the db
579
+	 *                                  and thus call a different method to instantiate
580
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
581
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
582
+	 * @return mixed                    null = failure to load or instantiate class object.
583
+	 *                                  object = class loaded and instantiated successfully.
584
+	 *                                  bool = fail or success when $load_only is true
585
+	 */
586
+	public function create(
587
+		$class_name = false,
588
+		$arguments = array(),
589
+		$cache = true,
590
+		$load_only = false,
591
+		$addon = false
592
+	) {
593
+		$class_name = ltrim($class_name, '\\');
594
+		$class_name = $this->_dependency_map->get_alias($class_name);
595
+		if ( ! class_exists($class_name)) {
596
+			// maybe the class is registered with a preceding \
597
+			$class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
598
+			// still doesn't exist ?
599
+			if ( ! class_exists($class_name)) {
600
+				return null;
601
+			}
602
+		}
603
+		// if we're only loading the class and it already exists, then let's just return true immediately
604
+		if ($load_only) {
605
+			return true;
606
+		}
607
+		$addon = $addon ? 'addon' : '';
608
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
609
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
610
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
611
+		if ($this->_cache_on && $cache && ! $load_only) {
612
+			// return object if it's already cached
613
+			$cached_class = $this->_get_cached_class($class_name, $addon);
614
+			if ($cached_class !== null) {
615
+				return $cached_class;
616
+			}
617
+		}
618
+		// instantiate the requested object
619
+		$class_obj = $this->_create_object($class_name, $arguments, $addon);
620
+		if ($this->_cache_on && $cache) {
621
+			// save it for later... kinda like gum  { : $
622
+			$this->_set_cached_class($class_obj, $class_name, $addon);
623
+		}
624
+		$this->_cache_on = true;
625
+		return $class_obj;
626
+	}
627
+
628
+
629
+
630
+	/**
631
+	 * instantiates, caches, and injects dependencies for classes
632
+	 *
633
+	 * @param array       $file_paths   an array of paths to folders to look in
634
+	 * @param string      $class_prefix EE  or EEM or... ???
635
+	 * @param bool|string $class_name   $class name
636
+	 * @param string      $type         file type - core? class? helper? model?
637
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
638
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
639
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
640
+	 * @return null|object|bool         null = failure to load or instantiate class object.
641
+	 *                                  object = class loaded and instantiated successfully.
642
+	 *                                  bool = fail or success when $load_only is true
643
+	 */
644
+	protected function _load(
645
+		$file_paths = array(),
646
+		$class_prefix = 'EE_',
647
+		$class_name = false,
648
+		$type = 'class',
649
+		$arguments = array(),
650
+		$cache = true,
651
+		$load_only = false
652
+	) {
653
+		$class_name = ltrim($class_name, '\\');
654
+		// strip php file extension
655
+		$class_name = str_replace('.php', '', trim($class_name));
656
+		// does the class have a prefix ?
657
+		if ( ! empty($class_prefix) && $class_prefix != 'addon') {
658
+			// make sure $class_prefix is uppercase
659
+			$class_prefix = strtoupper(trim($class_prefix));
660
+			// add class prefix ONCE!!!
661
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
662
+		}
663
+		$class_name = $this->_dependency_map->get_alias($class_name);
664
+		$class_exists = class_exists($class_name);
665
+		// if we're only loading the class and it already exists, then let's just return true immediately
666
+		if ($load_only && $class_exists) {
667
+			return true;
668
+		}
669
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
670
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
671
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
672
+		if ($this->_cache_on && $cache && ! $load_only) {
673
+			// return object if it's already cached
674
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
675
+			if ($cached_class !== null) {
676
+				return $cached_class;
677
+			}
678
+		}
679
+		// if the class doesn't already exist.. then we need to try and find the file and load it
680
+		if ( ! $class_exists) {
681
+			// get full path to file
682
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
683
+			// load the file
684
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
685
+			// if loading failed, or we are only loading a file but NOT instantiating an object
686
+			if ( ! $loaded || $load_only) {
687
+				// return boolean if only loading, or null if an object was expected
688
+				return $load_only ? $loaded : null;
689
+			}
690
+		}
691
+		// instantiate the requested object
692
+		$class_obj = $this->_create_object($class_name, $arguments, $type);
693
+		if ($this->_cache_on && $cache) {
694
+			// save it for later... kinda like gum  { : $
695
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix);
696
+		}
697
+		$this->_cache_on = true;
698
+		return $class_obj;
699
+	}
700
+
701
+
702
+
703
+
704
+	/**
705
+	 * _get_cached_class
706
+	 * attempts to find a cached version of the requested class
707
+	 * by looking in the following places:
708
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
709
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
710
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
711
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
712
+	 *
713
+	 * @access protected
714
+	 * @param string $class_name
715
+	 * @param string $class_prefix
716
+	 * @return mixed
717
+	 */
718
+	protected function _get_cached_class($class_name, $class_prefix = '')
719
+	{
720
+		if ($class_name === 'EE_Registry') {
721
+			return $this;
722
+		}
723
+		// have to specify something, but not anything that will conflict
724
+		$class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
+			? $this->_class_abbreviations[ $class_name ]
726
+			: 'FANCY_BATMAN_PANTS';
727
+		$class_name = str_replace('\\', '_', $class_name);
728
+		// check if class has already been loaded, and return it if it has been
729
+		if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
730
+			return $this->{$class_abbreviation};
731
+		}
732
+		if (isset ($this->{$class_name})) {
733
+			return $this->{$class_name};
734
+		}
735
+		if (isset ($this->LIB->{$class_name})) {
736
+			return $this->LIB->{$class_name};
737
+		}
738
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
739
+			return $this->addons->{$class_name};
740
+		}
741
+		return null;
742
+	}
743
+
744
+
745
+
746
+	/**
747
+	 * removes a cached version of the requested class
748
+	 *
749
+	 * @param string $class_name
750
+	 * @param boolean $addon
751
+	 * @return boolean
752
+	 */
753
+	public function clear_cached_class($class_name, $addon = false)
754
+	{
755
+		// have to specify something, but not anything that will conflict
756
+		$class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
+			? $this->_class_abbreviations[ $class_name ]
758
+			: 'FANCY_BATMAN_PANTS';
759
+		$class_name = str_replace('\\', '_', $class_name);
760
+		// check if class has already been loaded, and return it if it has been
761
+		if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
762
+			$this->{$class_abbreviation} = null;
763
+			return true;
764
+		}
765
+		if (isset($this->{$class_name})) {
766
+			$this->{$class_name} = null;
767
+			return true;
768
+		}
769
+		if (isset($this->LIB->{$class_name})) {
770
+			unset($this->LIB->{$class_name});
771
+			return true;
772
+		}
773
+		if ($addon && isset($this->addons->{$class_name})) {
774
+			unset($this->addons->{$class_name});
775
+			return true;
776
+		}
777
+		return false;
778
+	}
779
+
780
+
781
+	/**
782
+	 * _resolve_path
783
+	 * attempts to find a full valid filepath for the requested class.
784
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
785
+	 * then returns that path if the target file has been found and is readable
786
+	 *
787
+	 * @access protected
788
+	 * @param string $class_name
789
+	 * @param string $type
790
+	 * @param array  $file_paths
791
+	 * @return string | bool
792
+	 */
793
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
794
+	{
795
+		// make sure $file_paths is an array
796
+		$file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
797
+		// cycle thru paths
798
+		foreach ($file_paths as $key => $file_path) {
799
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
800
+			$file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801
+			// prep file type
802
+			$type = ! empty($type) ? trim($type, '.') . '.' : '';
803
+			// build full file path
804
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
805
+			//does the file exist and can be read ?
806
+			if (is_readable($file_paths[$key])) {
807
+				return $file_paths[$key];
808
+			}
809
+		}
810
+		return false;
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * _require_file
817
+	 * basically just performs a require_once()
818
+	 * but with some error handling
819
+	 *
820
+	 * @access protected
821
+	 * @param  string $path
822
+	 * @param  string $class_name
823
+	 * @param  string $type
824
+	 * @param  array  $file_paths
825
+	 * @return boolean
826
+	 * @throws \EE_Error
827
+	 */
828
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
829
+	{
830
+		// don't give up! you gotta...
831
+		try {
832
+			//does the file exist and can it be read ?
833
+			if ( ! $path) {
834
+				// so sorry, can't find the file
835
+				throw new EE_Error (
836
+					sprintf(
837
+						__('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
838
+						trim($type, '.'),
839
+						$class_name,
840
+						'<br />' . implode(',<br />', $file_paths)
841
+					)
842
+				);
843
+			}
844
+			// get the file
845
+			require_once($path);
846
+			// if the class isn't already declared somewhere
847
+			if (class_exists($class_name, false) === false) {
848
+				// so sorry, not a class
849
+				throw new EE_Error(
850
+					sprintf(
851
+						__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
852
+						$type,
853
+						$path,
854
+						$class_name
855
+					)
856
+				);
857
+			}
858
+		} catch (EE_Error $e) {
859
+			$e->get_error();
860
+			return false;
861
+		}
862
+		return true;
863
+	}
864
+
865
+
866
+
867
+	/**
868
+	 * _create_object
869
+	 * Attempts to instantiate the requested class via any of the
870
+	 * commonly used instantiation methods employed throughout EE.
871
+	 * The priority for instantiation is as follows:
872
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
873
+	 *        - model objects via their 'new_instance_from_db' method
874
+	 *        - model objects via their 'new_instance' method
875
+	 *        - "singleton" classes" via their 'instance' method
876
+	 *    - standard instantiable classes via their __constructor
877
+	 * Prior to instantiation, if the classname exists in the dependency_map,
878
+	 * then the constructor for the requested class will be examined to determine
879
+	 * if any dependencies exist, and if they can be injected.
880
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
881
+	 *
882
+	 * @access protected
883
+	 * @param string $class_name
884
+	 * @param array  $arguments
885
+	 * @param string $type
886
+	 * @return null | object
887
+	 * @throws \EE_Error
888
+	 */
889
+	protected function _create_object($class_name, $arguments = array(), $type = '')
890
+	{
891
+		$class_obj = null;
892
+		$instantiation_mode = '0) none';
893
+		// don't give up! you gotta...
894
+		try {
895
+			// create reflection
896
+			$reflector = $this->get_ReflectionClass($class_name);
897
+			// make sure arguments are an array
898
+			$arguments = is_array($arguments) ? $arguments : array($arguments);
899
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
900
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
901
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
902
+				? $arguments
903
+				: array($arguments);
904
+			// attempt to inject dependencies ?
905
+			if ($this->_dependency_map->has($class_name)) {
906
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
907
+			}
908
+			// instantiate the class if possible
909
+			if ($reflector->isAbstract()) {
910
+				// nothing to instantiate, loading file was enough
911
+				// does not throw an exception so $instantiation_mode is unused
912
+				// $instantiation_mode = "1) no constructor abstract class";
913
+				$class_obj = true;
914
+			} else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
915
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
916
+				$instantiation_mode = "2) no constructor but instantiable";
917
+				$class_obj = $reflector->newInstance();
918
+			} else if (method_exists($class_name, 'new_instance')) {
919
+				$instantiation_mode = "4) new_instance()";
920
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
921
+			} else if (method_exists($class_name, 'instance')) {
922
+				$instantiation_mode = "5) instance()";
923
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
924
+			} else if ($reflector->isInstantiable()) {
925
+				$instantiation_mode = "6) constructor";
926
+				$class_obj = $reflector->newInstanceArgs($arguments);
927
+			} else {
928
+				// heh ? something's not right !
929
+				throw new EE_Error(
930
+					sprintf(
931
+						__('The %s file %s could not be instantiated.', 'event_espresso'),
932
+						$type,
933
+						$class_name
934
+					)
935
+				);
936
+			}
937
+		} catch (Exception $e) {
938
+			if ( ! $e instanceof EE_Error) {
939
+				$e = new EE_Error(
940
+					sprintf(
941
+						__('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
942
+						$class_name,
943
+						'<br />',
944
+						$e->getMessage(),
945
+						$instantiation_mode
946
+					)
947
+				);
948
+			}
949
+			$e->get_error();
950
+		}
951
+		return $class_obj;
952
+	}
953
+
954
+
955
+
956
+	/**
957
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
958
+	 * @param array $array
959
+	 * @return bool
960
+	 */
961
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
962
+	{
963
+		return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
964
+	}
965
+
966
+
967
+
968
+	/**
969
+	 * getReflectionClass
970
+	 * checks if a ReflectionClass object has already been generated for a class
971
+	 * and returns that instead of creating a new one
972
+	 *
973
+	 * @access public
974
+	 * @param string $class_name
975
+	 * @return ReflectionClass
976
+	 */
977
+	public function get_ReflectionClass($class_name)
978
+	{
979
+		if (
980
+			! isset($this->_reflectors[$class_name])
981
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
982
+		) {
983
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
984
+		}
985
+		return $this->_reflectors[$class_name];
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * _resolve_dependencies
992
+	 * examines the constructor for the requested class to determine
993
+	 * if any dependencies exist, and if they can be injected.
994
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
995
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
996
+	 * For example:
997
+	 *        if attempting to load a class "Foo" with the following constructor:
998
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
999
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1000
+	 *        but only IF they are NOT already present in the incoming arguments array,
1001
+	 *        and the correct classes can be loaded
1002
+	 *
1003
+	 * @access protected
1004
+	 * @param ReflectionClass $reflector
1005
+	 * @param string          $class_name
1006
+	 * @param array           $arguments
1007
+	 * @return array
1008
+	 * @throws \ReflectionException
1009
+	 */
1010
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1011
+	{
1012
+		// let's examine the constructor
1013
+		$constructor = $reflector->getConstructor();
1014
+		// whu? huh? nothing?
1015
+		if ( ! $constructor) {
1016
+			return $arguments;
1017
+		}
1018
+		// get constructor parameters
1019
+		$params = $constructor->getParameters();
1020
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1021
+		$argument_keys = array_keys($arguments);
1022
+		// now loop thru all of the constructors expected parameters
1023
+		foreach ($params as $index => $param) {
1024
+			// is this a dependency for a specific class ?
1025
+			$param_class = $param->getClass() ? $param->getClass()->name : null;
1026
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1027
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1028
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1029
+				: $param_class;
1030
+			if (
1031
+				// param is not even a class
1032
+				empty($param_class)
1033
+				// and something already exists in the incoming arguments for this param
1034
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1035
+			) {
1036
+				// so let's skip this argument and move on to the next
1037
+				continue;
1038
+			}
1039
+			if (
1040
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1041
+				! empty($param_class)
1042
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1043
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1044
+			) {
1045
+				// skip this argument and move on to the next
1046
+				continue;
1047
+			}
1048
+			if (
1049
+				// parameter is type hinted as a class, and should be injected
1050
+				! empty($param_class)
1051
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1052
+			) {
1053
+				$arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1054
+			} else {
1055
+				try {
1056
+					$arguments[$index] = $param->getDefaultValue();
1057
+				} catch (ReflectionException $e) {
1058
+					throw new ReflectionException(
1059
+						sprintf(
1060
+							__('%1$s for parameter "$%2$s"', 'event_espresso'),
1061
+							$e->getMessage(),
1062
+							$param->getName()
1063
+						)
1064
+					);
1065
+				}
1066
+			}
1067
+		}
1068
+		return $arguments;
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 * @access protected
1075
+	 * @param string $class_name
1076
+	 * @param string $param_class
1077
+	 * @param array  $arguments
1078
+	 * @param mixed  $index
1079
+	 * @return array
1080
+	 */
1081
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1082
+	{
1083
+		$dependency = null;
1084
+		// should dependency be loaded from cache ?
1085
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1086
+					!== EE_Dependency_Map::load_new_object
1087
+			? true
1088
+			: false;
1089
+		// we might have a dependency...
1090
+		// let's MAYBE try and find it in our cache if that's what's been requested
1091
+		$cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1092
+		// and grab it if it exists
1093
+		if ($cached_class instanceof $param_class) {
1094
+			$dependency = $cached_class;
1095
+		} else if ($param_class !== $class_name) {
1096
+			// obtain the loader method from the dependency map
1097
+			$loader = $this->_dependency_map->class_loader($param_class);
1098
+			// is loader a custom closure ?
1099
+			if ($loader instanceof Closure) {
1100
+				$dependency = $loader();
1101
+			} else {
1102
+				// set the cache on property for the recursive loading call
1103
+				$this->_cache_on = $cache_on;
1104
+				// if not, then let's try and load it via the registry
1105
+				if ($loader && method_exists($this, $loader)) {
1106
+					$dependency = $this->{$loader}($param_class);
1107
+				} else {
1108
+					$dependency = $this->create($param_class, array(), $cache_on);
1109
+				}
1110
+			}
1111
+		}
1112
+		// did we successfully find the correct dependency ?
1113
+		if ($dependency instanceof $param_class) {
1114
+			// then let's inject it into the incoming array of arguments at the correct location
1115
+			if (isset($argument_keys[$index])) {
1116
+				$arguments[$argument_keys[$index]] = $dependency;
1117
+			} else {
1118
+				$arguments[$index] = $dependency;
1119
+			}
1120
+		}
1121
+		return $arguments;
1122
+	}
1123
+
1124
+
1125
+
1126
+	/**
1127
+	 * _set_cached_class
1128
+	 * attempts to cache the instantiated class locally
1129
+	 * in one of the following places, in the following order:
1130
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1131
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1132
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1133
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1134
+	 *
1135
+	 * @access protected
1136
+	 * @param object $class_obj
1137
+	 * @param string $class_name
1138
+	 * @param string $class_prefix
1139
+	 * @return void
1140
+	 */
1141
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1142
+	{
1143
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1144
+			return;
1145
+		}
1146
+		// return newly instantiated class
1147
+		if (isset($this->_class_abbreviations[$class_name])) {
1148
+			$class_abbreviation = $this->_class_abbreviations[$class_name];
1149
+			$this->{$class_abbreviation} = $class_obj;
1150
+			return;
1151
+		}
1152
+		$class_name = str_replace('\\', '_', $class_name);
1153
+		if (property_exists($this, $class_name)) {
1154
+			$this->{$class_name} = $class_obj;
1155
+			return;
1156
+		}
1157
+		if ($class_prefix === 'addon') {
1158
+			$this->addons->{$class_name} = $class_obj;
1159
+			return;
1160
+		}
1161
+		$this->LIB->{$class_name} = $class_obj;
1162
+	}
1163
+
1164
+
1165
+
1166
+	/**
1167
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1168
+	 *
1169
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1170
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1171
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1172
+	 * @param array  $arguments
1173
+	 * @return object
1174
+	 */
1175
+	public static function factory($classname, $arguments = array())
1176
+	{
1177
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1178
+		if ($loader instanceof Closure) {
1179
+			return $loader($arguments);
1180
+		}
1181
+		if (method_exists(EE_Registry::instance(), $loader)) {
1182
+			return EE_Registry::instance()->{$loader}($classname, $arguments);
1183
+		}
1184
+		return null;
1185
+	}
1186
+
1187
+
1188
+
1189
+	/**
1190
+	 * Gets the addon by its name/slug (not classname. For that, just
1191
+	 * use the classname as the property name on EE_Config::instance()->addons)
1192
+	 *
1193
+	 * @param string $name
1194
+	 * @return EE_Addon
1195
+	 */
1196
+	public function get_addon_by_name($name)
1197
+	{
1198
+		foreach ($this->addons as $addon) {
1199
+			if ($addon->name() == $name) {
1200
+				return $addon;
1201
+			}
1202
+		}
1203
+		return null;
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their name() function) They're already available on EE_Config::instance()->addons as properties, where each property's name is
1210
+	 * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1211
+	 *
1212
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1213
+	 */
1214
+	public function get_addons_by_name()
1215
+	{
1216
+		$addons = array();
1217
+		foreach ($this->addons as $addon) {
1218
+			$addons[$addon->name()] = $addon;
1219
+		}
1220
+		return $addons;
1221
+	}
1222
+
1223
+
1224
+
1225
+	/**
1226
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1227
+	 * a stale copy of it around
1228
+	 *
1229
+	 * @param string $model_name
1230
+	 * @return \EEM_Base
1231
+	 * @throws \EE_Error
1232
+	 */
1233
+	public function reset_model($model_name)
1234
+	{
1235
+		$model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1236
+		if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1237
+			return null;
1238
+		}
1239
+		//get that model reset it and make sure we nuke the old reference to it
1240
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1241
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1242
+		} else {
1243
+			throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1244
+		}
1245
+		return $this->LIB->{$model_class_name};
1246
+	}
1247
+
1248
+
1249
+
1250
+	/**
1251
+	 * Resets the registry.
1252
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1253
+	 * is used in a multisite install.  Here is a list of things that are NOT reset.
1254
+	 * - $_dependency_map
1255
+	 * - $_class_abbreviations
1256
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1257
+	 * - $REQ:  Still on the same request so no need to change.
1258
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1259
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1260
+	 *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1261
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1262
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1263
+	 *             switch or on the restore.
1264
+	 * - $modules
1265
+	 * - $shortcodes
1266
+	 * - $widgets
1267
+	 *
1268
+	 * @param boolean $hard             whether to reset data in the database too, or just refresh
1269
+	 *                                  the Registry to its state at the beginning of the request
1270
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1271
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1272
+	 *                                  currently reinstantiate the singletons at the moment)
1273
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1274
+	 *                                  code instead can just change the model context to a different blog id if necessary
1275
+	 * @return EE_Registry
1276
+	 */
1277
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1278
+	{
1279
+		$instance = self::instance();
1280
+		$instance->_cache_on = true;
1281
+		// reset some "special" classes
1282
+		EEH_Activation::reset();
1283
+		$instance->CFG = $instance->CFG->reset($hard, $reinstantiate);
1284
+		$instance->CART = null;
1285
+		$instance->MRM = null;
1286
+		$instance->AssetsRegistry = null;
1287
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1288
+		//messages reset
1289
+		EED_Messages::reset();
1290
+		//handle of objects cached on LIB
1291
+		foreach (array('LIB', 'modules') as $cache) {
1292
+			foreach ($instance->{$cache} as $class_name => $class) {
1293
+				if (EE_Registry::_reset_and_unset_object($class, $reset_models)) {
1294
+					unset($instance->{$cache}->{$class_name});
1295
+				}
1296
+			}
1297
+		}
1298
+		return $instance;
1299
+	}
1300
+
1301
+
1302
+
1303
+	/**
1304
+	 * if passed object implements ResettableInterface, then call it's reset() method
1305
+	 * if passed object implements InterminableInterface, then return false,
1306
+	 * to indicate that it should NOT be cleared from the Registry cache
1307
+	 *
1308
+	 * @param      $object
1309
+	 * @param bool $reset_models
1310
+	 * @return bool returns true if cached object should be unset
1311
+	 */
1312
+	private static function _reset_and_unset_object($object, $reset_models)
1313
+	{
1314
+		if (! is_object($object)) {
1315
+			// don't unset anything that's not an object
1316
+			return false;
1317
+		}
1318
+		if ($object instanceof EED_Module) {
1319
+			$object::reset();
1320
+			// don't unset modules
1321
+			return false;
1322
+		}
1323
+		if ($object instanceof ResettableInterface) {
1324
+			if ($object instanceof EEM_Base) {
1325
+				if ($reset_models) {
1326
+					$object->reset();
1327
+					return true;
1328
+				}
1329
+				return false;
1330
+			}
1331
+			$object->reset();
1332
+			return true;
1333
+		}
1334
+		if ( ! $object instanceof InterminableInterface) {
1335
+			return true;
1336
+		}
1337
+		return false;
1338
+	}
1339
+
1340
+
1341
+
1342
+	/**
1343
+	 * @override magic methods
1344
+	 * @return void
1345
+	 */
1346
+	public final function __destruct()
1347
+	{
1348
+	}
1349
+
1350
+
1351
+
1352
+	/**
1353
+	 * @param $a
1354
+	 * @param $b
1355
+	 */
1356
+	public final function __call($a, $b)
1357
+	{
1358
+	}
1359
+
1360
+
1361
+
1362
+	/**
1363
+	 * @param $a
1364
+	 */
1365
+	public final function __get($a)
1366
+	{
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * @param $a
1373
+	 * @param $b
1374
+	 */
1375
+	public final function __set($a, $b)
1376
+	{
1377
+	}
1378
+
1379
+
1380
+
1381
+	/**
1382
+	 * @param $a
1383
+	 */
1384
+	public final function __isset($a)
1385
+	{
1386
+	}
1387 1387
 
1388 1388
 
1389 1389
 
1390
-    /**
1391
-     * @param $a
1392
-     */
1393
-    public final function __unset($a)
1394
-    {
1395
-    }
1390
+	/**
1391
+	 * @param $a
1392
+	 */
1393
+	public final function __unset($a)
1394
+	{
1395
+	}
1396 1396
 
1397 1397
 
1398 1398
 
1399
-    /**
1400
-     * @return array
1401
-     */
1402
-    public final function __sleep()
1403
-    {
1404
-        return array();
1405
-    }
1399
+	/**
1400
+	 * @return array
1401
+	 */
1402
+	public final function __sleep()
1403
+	{
1404
+		return array();
1405
+	}
1406 1406
 
1407 1407
 
1408 1408
 
1409
-    public final function __wakeup()
1410
-    {
1411
-    }
1409
+	public final function __wakeup()
1410
+	{
1411
+	}
1412 1412
 
1413 1413
 
1414 1414
 
1415
-    /**
1416
-     * @return string
1417
-     */
1418
-    public final function __toString()
1419
-    {
1420
-        return '';
1421
-    }
1415
+	/**
1416
+	 * @return string
1417
+	 */
1418
+	public final function __toString()
1419
+	{
1420
+		return '';
1421
+	}
1422 1422
 
1423 1423
 
1424 1424
 
1425
-    public final function __invoke()
1426
-    {
1427
-    }
1425
+	public final function __invoke()
1426
+	{
1427
+	}
1428 1428
 
1429 1429
 
1430 1430
 
1431
-    public final static function __set_state($array = array())
1432
-    {
1433
-        return EE_Registry::instance();
1434
-    }
1431
+	public final static function __set_state($array = array())
1432
+	{
1433
+		return EE_Registry::instance();
1434
+	}
1435 1435
 
1436 1436
 
1437 1437
 
1438
-    public final function __clone()
1439
-    {
1440
-    }
1438
+	public final function __clone()
1439
+	{
1440
+	}
1441 1441
 
1442 1442
 
1443 1443
 
1444
-    /**
1445
-     * @param $a
1446
-     * @param $b
1447
-     */
1448
-    public final static function __callStatic($a, $b)
1449
-    {
1450
-    }
1444
+	/**
1445
+	 * @param $a
1446
+	 * @param $b
1447
+	 */
1448
+	public final static function __callStatic($a, $b)
1449
+	{
1450
+	}
1451 1451
 
1452 1452
 
1453 1453
 
1454
-    /**
1455
-     * Gets all the custom post type models defined
1456
-     *
1457
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1458
-     */
1459
-    public function cpt_models()
1460
-    {
1461
-        $cpt_models = array();
1462
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1463
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1464
-                $cpt_models[$short_name] = $classname;
1465
-            }
1466
-        }
1467
-        return $cpt_models;
1468
-    }
1454
+	/**
1455
+	 * Gets all the custom post type models defined
1456
+	 *
1457
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1458
+	 */
1459
+	public function cpt_models()
1460
+	{
1461
+		$cpt_models = array();
1462
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1463
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1464
+				$cpt_models[$short_name] = $classname;
1465
+			}
1466
+		}
1467
+		return $cpt_models;
1468
+	}
1469 1469
 
1470 1470
 
1471 1471
 
1472
-    /**
1473
-     * @return \EE_Config
1474
-     */
1475
-    public static function CFG()
1476
-    {
1477
-        return self::instance()->CFG;
1478
-    }
1472
+	/**
1473
+	 * @return \EE_Config
1474
+	 */
1475
+	public static function CFG()
1476
+	{
1477
+		return self::instance()->CFG;
1478
+	}
1479 1479
 
1480 1480
 
1481 1481
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -297,13 +297,13 @@  discard block
 block discarded – undo
297 297
      */
298 298
     public static function localize_i18n_js_strings()
299 299
     {
300
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
300
+        $i18n_js_strings = (array) EE_Registry::$i18n_js_strings;
301 301
         foreach ($i18n_js_strings as $key => $value) {
302 302
             if (is_scalar($value)) {
303
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
303
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
304 304
             }
305 305
         }
306
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
306
+        return "/* <![CDATA[ */ var eei18n = ".wp_json_encode($i18n_js_strings).'; /* ]]> */';
307 307
     }
308 308
 
309 309
 
@@ -355,9 +355,9 @@  discard block
 block discarded – undo
355 355
                 EE_CORE,
356 356
                 EE_ADMIN,
357 357
                 EE_CPTS,
358
-                EE_CORE . 'data_migration_scripts' . DS,
359
-                EE_CORE . 'request_stack' . DS,
360
-                EE_CORE . 'middleware' . DS,
358
+                EE_CORE.'data_migration_scripts'.DS,
359
+                EE_CORE.'request_stack'.DS,
360
+                EE_CORE.'middleware'.DS,
361 361
             )
362 362
         );
363 363
         // retrieve instantiated class
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
         $service_paths = apply_filters(
381 381
             'FHEE__EE_Registry__load_service__service_paths',
382 382
             array(
383
-                EE_CORE . 'services' . DS,
383
+                EE_CORE.'services'.DS,
384 384
             )
385 385
         );
386 386
         // retrieve instantiated class
@@ -463,10 +463,10 @@  discard block
 block discarded – undo
463 463
     {
464 464
         $paths = array(
465 465
             EE_LIBRARIES,
466
-            EE_LIBRARIES . 'messages' . DS,
467
-            EE_LIBRARIES . 'shortcodes' . DS,
468
-            EE_LIBRARIES . 'qtips' . DS,
469
-            EE_LIBRARIES . 'payment_methods' . DS,
466
+            EE_LIBRARIES.'messages'.DS,
467
+            EE_LIBRARIES.'shortcodes'.DS,
468
+            EE_LIBRARIES.'qtips'.DS,
469
+            EE_LIBRARIES.'payment_methods'.DS,
470 470
         );
471 471
         // retrieve instantiated class
472 472
         return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, $cache, $load_only);
@@ -505,10 +505,10 @@  discard block
 block discarded – undo
505 505
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
506 506
     {
507 507
         $paths = array(
508
-            EE_MODELS . 'fields' . DS,
509
-            EE_MODELS . 'helpers' . DS,
510
-            EE_MODELS . 'relations' . DS,
511
-            EE_MODELS . 'strategies' . DS,
508
+            EE_MODELS.'fields'.DS,
509
+            EE_MODELS.'helpers'.DS,
510
+            EE_MODELS.'relations'.DS,
511
+            EE_MODELS.'strategies'.DS,
512 512
         );
513 513
         // retrieve instantiated class
514 514
         return $this->_load($paths, 'EE_', $class_name, '', $arguments, true, $load_only);
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
         $class_name = $this->_dependency_map->get_alias($class_name);
595 595
         if ( ! class_exists($class_name)) {
596 596
             // maybe the class is registered with a preceding \
597
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
597
+            $class_name = strpos($class_name, '\\') !== 0 ? '\\'.$class_name : $class_name;
598 598
             // still doesn't exist ?
599 599
             if ( ! class_exists($class_name)) {
600 600
                 return null;
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
             // make sure $class_prefix is uppercase
659 659
             $class_prefix = strtoupper(trim($class_prefix));
660 660
             // add class prefix ONCE!!!
661
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
661
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
662 662
         }
663 663
         $class_name = $this->_dependency_map->get_alias($class_name);
664 664
         $class_exists = class_exists($class_name);
@@ -721,8 +721,8 @@  discard block
 block discarded – undo
721 721
             return $this;
722 722
         }
723 723
         // have to specify something, but not anything that will conflict
724
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
-            ? $this->_class_abbreviations[ $class_name ]
724
+        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
725
+            ? $this->_class_abbreviations[$class_name]
726 726
             : 'FANCY_BATMAN_PANTS';
727 727
         $class_name = str_replace('\\', '_', $class_name);
728 728
         // check if class has already been loaded, and return it if it has been
@@ -753,8 +753,8 @@  discard block
 block discarded – undo
753 753
     public function clear_cached_class($class_name, $addon = false)
754 754
     {
755 755
         // have to specify something, but not anything that will conflict
756
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
-            ? $this->_class_abbreviations[ $class_name ]
756
+        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
757
+            ? $this->_class_abbreviations[$class_name]
758 758
             : 'FANCY_BATMAN_PANTS';
759 759
         $class_name = str_replace('\\', '_', $class_name);
760 760
         // check if class has already been loaded, and return it if it has been
@@ -799,9 +799,9 @@  discard block
 block discarded – undo
799 799
             // convert all separators to proper DS, if no filepath, then use EE_CLASSES
800 800
             $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801 801
             // prep file type
802
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
802
+            $type = ! empty($type) ? trim($type, '.').'.' : '';
803 803
             // build full file path
804
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
804
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
805 805
             //does the file exist and can be read ?
806 806
             if (is_readable($file_paths[$key])) {
807 807
                 return $file_paths[$key];
@@ -832,12 +832,12 @@  discard block
 block discarded – undo
832 832
             //does the file exist and can it be read ?
833 833
             if ( ! $path) {
834 834
                 // so sorry, can't find the file
835
-                throw new EE_Error (
835
+                throw new EE_Error(
836 836
                     sprintf(
837 837
                         __('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
838 838
                         trim($type, '.'),
839 839
                         $class_name,
840
-                        '<br />' . implode(',<br />', $file_paths)
840
+                        '<br />'.implode(',<br />', $file_paths)
841 841
                     )
842 842
                 );
843 843
             }
@@ -1311,7 +1311,7 @@  discard block
 block discarded – undo
1311 1311
      */
1312 1312
     private static function _reset_and_unset_object($object, $reset_models)
1313 1313
     {
1314
-        if (! is_object($object)) {
1314
+        if ( ! is_object($object)) {
1315 1315
             // don't unset anything that's not an object
1316 1316
             return false;
1317 1317
         }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 1 patch
Indentation   +1660 added lines, -1660 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\exceptions\EntityNotFoundException;
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 /**
@@ -15,1665 +15,1665 @@  discard block
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * Used to reference when a registration has never been checked in.
20
-     *
21
-     * @type int
22
-     */
23
-    const checkin_status_never = 2;
24
-
25
-    /**
26
-     * Used to reference when a registration has been checked in.
27
-     *
28
-     * @type int
29
-     */
30
-    const checkin_status_in = 1;
31
-
32
-
33
-    /**
34
-     * Used to reference when a registration has been checked out.
35
-     *
36
-     * @type int
37
-     */
38
-    const checkin_status_out = 0;
39
-
40
-
41
-    /**
42
-     * extra meta key for tracking reg status os trashed registrations
43
-     *
44
-     * @type string
45
-     */
46
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
47
-
48
-
49
-    /**
50
-     * extra meta key for tracking if registration has reserved ticket
51
-     *
52
-     * @type string
53
-     */
54
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
55
-
56
-
57
-
58
-    /**
59
-     * Set Event ID
60
-     *
61
-     * @param int $EVT_ID Event ID
62
-     */
63
-    public function set_event($EVT_ID = 0)
64
-    {
65
-        $this->set('EVT_ID', $EVT_ID);
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
72
-     * be routed to internal methods
73
-     *
74
-     * @param string $field_name
75
-     * @param mixed  $field_value
76
-     * @param bool   $use_default
77
-     * @throws \EE_Error
78
-     * @throws \RuntimeException
79
-     */
80
-    public function set($field_name, $field_value, $use_default = false)
81
-    {
82
-        switch ($field_name) {
83
-            case 'REG_code' :
84
-                if (! empty($field_value) && $this->reg_code() === null) {
85
-                    $this->set_reg_code($field_value, $use_default);
86
-                }
87
-                break;
88
-            case 'STS_ID' :
89
-                $this->set_status($field_value, $use_default);
90
-                break;
91
-            default :
92
-                parent::set($field_name, $field_value, $use_default);
93
-        }
94
-    }
95
-
96
-
97
-    /**
98
-     * Set Status ID
99
-     * updates the registration status and ALSO...
100
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
101
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
102
-     *
103
-     * @param string  $new_STS_ID
104
-     * @param boolean $use_default
105
-     * @return bool
106
-     * @throws \RuntimeException
107
-     * @throws \EE_Error
108
-     */
109
-    public function set_status($new_STS_ID = null, $use_default = false)
110
-    {
111
-        // get current REG_Status
112
-        $old_STS_ID = $this->status_ID();
113
-        // if status has changed
114
-        if (
115
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
116
-            && ! empty($old_STS_ID) // and that old status is actually set
117
-            && ! empty($new_STS_ID) // as well as the new status
118
-            && $this->ID() // ensure registration is in the db
119
-        ) {
120
-            // TO approved
121
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
122
-                // reserve a space by incrementing ticket and datetime sold values
123
-                $this->_reserve_registration_space();
124
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID);
125
-                // OR FROM  approved
126
-            } else if ($old_STS_ID === EEM_Registration::status_id_approved) {
127
-                // release a space by decrementing ticket and datetime sold values
128
-                $this->_release_registration_space();
129
-                do_action('AHEE__EE_Registration__set_status__from_approved', $this, $old_STS_ID, $new_STS_ID);
130
-            }
131
-            // update status
132
-            parent::set('STS_ID', $new_STS_ID, $use_default);
133
-            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID);
134
-            /** @type EE_Transaction_Payments $transaction_payments */
135
-            $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
136
-            $transaction_payments->recalculate_transaction_total($this->transaction(), false);
137
-            $this->transaction()->update_status_based_on_total_paid(true);
138
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID);
139
-            return true;
140
-        }
141
-        //even though the old value matches the new value, it's still good to
142
-        //allow the parent set method to have a say
143
-        parent::set('STS_ID', $new_STS_ID, $use_default);
144
-        return true;
145
-    }
146
-
147
-
148
-    /**
149
-     * update REGs and TXN when cancelled or declined registrations involved
150
-     *
151
-     * @param string $new_STS_ID
152
-     * @param string $old_STS_ID
153
-     * @throws \EE_Error
154
-     */
155
-    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID)
156
-    {
157
-        // these reg statuses should not be considered in any calculations involving monies owing
158
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
159
-        // true if registration has been cancelled or declined
160
-        if (
161
-            in_array($new_STS_ID, $closed_reg_statuses, true)
162
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
163
-        ) {
164
-            /** @type EE_Registration_Processor $registration_processor */
165
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
166
-            /** @type EE_Transaction_Processor $transaction_processor */
167
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
168
-            // cancelled or declined registration
169
-            $registration_processor->update_registration_after_being_canceled_or_declined(
170
-                $this,
171
-                $closed_reg_statuses
172
-            );
173
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
174
-                $this,
175
-                $closed_reg_statuses,
176
-                false
177
-            );
178
-            do_action('AHEE__EE_Registration__set_status__canceled_or_declined', $this, $old_STS_ID, $new_STS_ID);
179
-            return;
180
-        }
181
-        // true if reinstating cancelled or declined registration
182
-        if (
183
-            in_array($old_STS_ID, $closed_reg_statuses, true)
184
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
185
-        ) {
186
-            /** @type EE_Registration_Processor $registration_processor */
187
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
188
-            /** @type EE_Transaction_Processor $transaction_processor */
189
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
190
-            // reinstating cancelled or declined registration
191
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
192
-                $this,
193
-                $closed_reg_statuses
194
-            );
195
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
196
-                $this,
197
-                $closed_reg_statuses,
198
-                false
199
-            );
200
-            do_action('AHEE__EE_Registration__set_status__after_reinstated', $this, $old_STS_ID, $new_STS_ID);
201
-        }
202
-    }
203
-
204
-
205
-    /**
206
-     *        get Status ID
207
-     */
208
-    public function status_ID()
209
-    {
210
-        return $this->get('STS_ID');
211
-    }
212
-
213
-
214
-    /**
215
-     * increments this registration's related ticket sold and corresponding datetime sold values
216
-     *
217
-     * @return void
218
-     * @throws \EE_Error
219
-     */
220
-    private function _reserve_registration_space()
221
-    {
222
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
223
-        // so stop tracking that this reg has a ticket reserved
224
-        $this->release_reserved_ticket();
225
-        $ticket = $this->ticket();
226
-        $ticket->increase_sold();
227
-        $ticket->save();
228
-        // possibly set event status to sold out
229
-        $this->event()->perform_sold_out_status_check();
230
-    }
231
-
232
-
233
-    /**
234
-     * Gets the ticket this registration is for
235
-     *
236
-     * @param boolean $include_archived whether to include archived tickets or not.
237
-     * @return EE_Ticket|EE_Base_Class
238
-     * @throws \EE_Error
239
-     */
240
-    public function ticket($include_archived = true)
241
-    {
242
-        $query_params = array();
243
-        if ($include_archived) {
244
-            $query_params['default_where_conditions'] = 'none';
245
-        }
246
-        return $this->get_first_related('Ticket', $query_params);
247
-    }
248
-
249
-
250
-    /**
251
-     * Gets the event this registration is for
252
-     *
253
-     * @return EE_Event
254
-     */
255
-    public function event()
256
-    {
257
-        $event = $this->get_first_related('Event');
258
-        if (! $event instanceof \EE_Event) {
259
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
260
-        }
261
-        return $event;
262
-    }
263
-
264
-
265
-    /**
266
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
267
-     * with the author of the event this registration is for.
268
-     *
269
-     * @since 4.5.0
270
-     * @return int
271
-     */
272
-    public function wp_user()
273
-    {
274
-        $event = $this->event();
275
-        if ($event instanceof EE_Event) {
276
-            return $event->wp_user();
277
-        }
278
-        return 0;
279
-    }
280
-
281
-
282
-    /**
283
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
284
-     *
285
-     * @return void
286
-     * @throws \EE_Error
287
-     */
288
-    private function _release_registration_space()
289
-    {
290
-        $ticket = $this->ticket();
291
-        $ticket->decrease_sold();
292
-        $ticket->save();
293
-    }
294
-
295
-
296
-    /**
297
-     * tracks this registration's ticket reservation in extra meta
298
-     * and can increment related ticket reserved and corresponding datetime reserved values
299
-     *
300
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
301
-     * @return void
302
-     * @throws \EE_Error
303
-     */
304
-    public function reserve_ticket($update_ticket = false)
305
-    {
306
-        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) === false) {
307
-            // PLZ NOTE: although checking $update_ticket first would be more efficient,
308
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
309
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) && $update_ticket) {
310
-                $ticket = $this->ticket();
311
-                $ticket->increase_reserved();
312
-                $ticket->save();
313
-            }
314
-        }
315
-    }
316
-
317
-
318
-    /**
319
-     * stops tracking this registration's ticket reservation in extra meta
320
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
321
-     *
322
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
323
-     * @return void
324
-     * @throws \EE_Error
325
-     */
326
-    public function release_reserved_ticket($update_ticket = false)
327
-    {
328
-        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) !== false) {
329
-            // PLZ NOTE: although checking $update_ticket first would be more efficient,
330
-            // we NEED to ALWAYS call delete_extra_meta(), which is why that is done first
331
-            if ($this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY) && $update_ticket) {
332
-                $ticket = $this->ticket();
333
-                $ticket->decrease_reserved();
334
-                $ticket->save();
335
-            }
336
-        }
337
-    }
338
-
339
-
340
-    /**
341
-     * Set Attendee ID
342
-     *
343
-     * @param        int $ATT_ID Attendee ID
344
-     */
345
-    public function set_attendee_id($ATT_ID = 0)
346
-    {
347
-        $this->set('ATT_ID', $ATT_ID);
348
-    }
349
-
350
-
351
-    /**
352
-     *        Set Transaction ID
353
-     *
354
-     * @param        int $TXN_ID Transaction ID
355
-     */
356
-    public function set_transaction_id($TXN_ID = 0)
357
-    {
358
-        $this->set('TXN_ID', $TXN_ID);
359
-    }
360
-
361
-
362
-    /**
363
-     *        Set Session
364
-     *
365
-     * @param    string $REG_session PHP Session ID
366
-     */
367
-    public function set_session($REG_session = '')
368
-    {
369
-        $this->set('REG_session', $REG_session);
370
-    }
371
-
372
-
373
-    /**
374
-     *        Set Registration URL Link
375
-     *
376
-     * @param    string $REG_url_link Registration URL Link
377
-     */
378
-    public function set_reg_url_link($REG_url_link = '')
379
-    {
380
-        $this->set('REG_url_link', $REG_url_link);
381
-    }
382
-
383
-
384
-    /**
385
-     *        Set Attendee Counter
386
-     *
387
-     * @param        int $REG_count Primary Attendee
388
-     */
389
-    public function set_count($REG_count = 1)
390
-    {
391
-        $this->set('REG_count', $REG_count);
392
-    }
393
-
394
-
395
-    /**
396
-     *        Set Group Size
397
-     *
398
-     * @param        boolean $REG_group_size Group Registration
399
-     */
400
-    public function set_group_size($REG_group_size = false)
401
-    {
402
-        $this->set('REG_group_size', $REG_group_size);
403
-    }
404
-
405
-
406
-    /**
407
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
408
-     *    EEM_Registration::status_id_not_approved
409
-     *
410
-     * @return        boolean
411
-     */
412
-    public function is_not_approved()
413
-    {
414
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
415
-    }
416
-
417
-
418
-    /**
419
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
420
-     *    EEM_Registration::status_id_pending_payment
421
-     *
422
-     * @return        boolean
423
-     */
424
-    public function is_pending_payment()
425
-    {
426
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
427
-    }
428
-
429
-
430
-    /**
431
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
432
-     *
433
-     * @return        boolean
434
-     */
435
-    public function is_approved()
436
-    {
437
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
438
-    }
439
-
440
-
441
-    /**
442
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
443
-     *
444
-     * @return        boolean
445
-     */
446
-    public function is_cancelled()
447
-    {
448
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
449
-    }
450
-
451
-
452
-    /**
453
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
454
-     *
455
-     * @return        boolean
456
-     */
457
-    public function is_declined()
458
-    {
459
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
460
-    }
461
-
462
-
463
-    /**
464
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
465
-     *    EEM_Registration::status_id_incomplete
466
-     *
467
-     * @return        boolean
468
-     */
469
-    public function is_incomplete()
470
-    {
471
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
472
-    }
473
-
474
-
475
-    /**
476
-     *        Set Registration Date
477
-     *
478
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
479
-     *                       Date
480
-     */
481
-    public function set_reg_date($REG_date = false)
482
-    {
483
-        $this->set('REG_date', $REG_date);
484
-    }
485
-
486
-
487
-    /**
488
-     *    Set final price owing for this registration after all ticket/price modifications
489
-     *
490
-     * @access    public
491
-     * @param    float $REG_final_price
492
-     */
493
-    public function set_final_price($REG_final_price = 0.00)
494
-    {
495
-        $this->set('REG_final_price', $REG_final_price);
496
-    }
497
-
498
-
499
-    /**
500
-     *    Set amount paid towards this registration's final price
501
-     *
502
-     * @access    public
503
-     * @param    float $REG_paid
504
-     */
505
-    public function set_paid($REG_paid = 0.00)
506
-    {
507
-        $this->set('REG_paid', $REG_paid);
508
-    }
509
-
510
-
511
-    /**
512
-     *        Attendee Is Going
513
-     *
514
-     * @param        boolean $REG_att_is_going Attendee Is Going
515
-     */
516
-    public function set_att_is_going($REG_att_is_going = false)
517
-    {
518
-        $this->set('REG_att_is_going', $REG_att_is_going);
519
-    }
520
-
521
-
522
-    /**
523
-     * Gets the related attendee
524
-     *
525
-     * @return EE_Attendee
526
-     */
527
-    public function attendee()
528
-    {
529
-        return $this->get_first_related('Attendee');
530
-    }
531
-
532
-
533
-    /**
534
-     *        get Event ID
535
-     */
536
-    public function event_ID()
537
-    {
538
-        return $this->get('EVT_ID');
539
-    }
540
-
541
-
542
-    /**
543
-     *        get Event ID
544
-     */
545
-    public function event_name()
546
-    {
547
-        $event = $this->event_obj();
548
-        if ($event) {
549
-            return $event->name();
550
-        } else {
551
-            return null;
552
-        }
553
-    }
554
-
555
-
556
-    /**
557
-     * Fetches the event this registration is for
558
-     *
559
-     * @return EE_Event
560
-     */
561
-    public function event_obj()
562
-    {
563
-        return $this->get_first_related('Event');
564
-    }
565
-
566
-
567
-    /**
568
-     *        get Attendee ID
569
-     */
570
-    public function attendee_ID()
571
-    {
572
-        return $this->get('ATT_ID');
573
-    }
574
-
575
-
576
-    /**
577
-     *        get PHP Session ID
578
-     */
579
-    public function session_ID()
580
-    {
581
-        return $this->get('REG_session');
582
-    }
583
-
584
-
585
-    /**
586
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
587
-     *
588
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
589
-     * @return string
590
-     */
591
-    public function receipt_url($messenger = 'html')
592
-    {
593
-
594
-        /**
595
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template already in use on old system.  If there is then we just return the standard url for it.
596
-         *
597
-         * @since 4.5.0
598
-         */
599
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
600
-        $has_custom             = EEH_Template::locate_template($template_relative_path, array(), true, true, true);
601
-
602
-        if ($has_custom) {
603
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
604
-        }
605
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
606
-    }
607
-
608
-
609
-    /**
610
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
611
-     *
612
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
613
-     * @return string
614
-     */
615
-    public function invoice_url($messenger = 'html')
616
-    {
617
-        /**
618
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template already in use on old system.  If there is then we just return the standard url for it.
619
-         *
620
-         * @since 4.5.0
621
-         */
622
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
623
-        $has_custom             = EEH_Template::locate_template($template_relative_path, array(), true, true, true);
624
-
625
-        if ($has_custom) {
626
-            if ($messenger == 'html') {
627
-                return $this->invoice_url('launch');
628
-            }
629
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
630
-
631
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
632
-            if ($messenger == 'html') {
633
-                $query_args['html'] = true;
634
-            }
635
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
636
-        }
637
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
638
-    }
639
-
640
-
641
-    /**
642
-     * get Registration URL Link
643
-     *
644
-     * @access public
645
-     * @return string
646
-     * @throws \EE_Error
647
-     */
648
-    public function reg_url_link()
649
-    {
650
-        return (string)$this->get('REG_url_link');
651
-    }
652
-
653
-
654
-    /**
655
-     * Echoes out invoice_url()
656
-     *
657
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
658
-     * @return void
659
-     */
660
-    public function e_invoice_url($type = 'launch')
661
-    {
662
-        echo $this->invoice_url($type);
663
-    }
664
-
665
-
666
-    /**
667
-     * Echoes out payment_overview_url
668
-     */
669
-    public function e_payment_overview_url()
670
-    {
671
-        echo $this->payment_overview_url();
672
-    }
673
-
674
-
675
-    /**
676
-     * Gets the URL of the thank you page with this registration REG_url_link added as
677
-     * a query parameter
678
-     *
679
-     * @return string
680
-     */
681
-    public function payment_overview_url()
682
-    {
683
-        return add_query_arg(array(
684
-            'e_reg_url_link' => $this->reg_url_link(),
685
-            'step'           => 'payment_options',
686
-            'revisit'        => true,
687
-        ), EE_Registry::instance()->CFG->core->reg_page_url());
688
-    }
689
-
690
-
691
-    /**
692
-     * Gets the URL of the thank you page with this registration REG_url_link added as
693
-     * a query parameter
694
-     *
695
-     * @return string
696
-     */
697
-    public function edit_attendee_information_url()
698
-    {
699
-        return add_query_arg(array(
700
-            'e_reg_url_link' => $this->reg_url_link(),
701
-            'step'           => 'attendee_information',
702
-            'revisit'        => true,
703
-        ), EE_Registry::instance()->CFG->core->reg_page_url());
704
-    }
705
-
706
-
707
-    /**
708
-     * Simply generates and returns the appropriate admin_url link to edit this registration
709
-     *
710
-     * @return string
711
-     */
712
-    public function get_admin_edit_url()
713
-    {
714
-        return EEH_URL::add_query_args_and_nonce(array(
715
-            'page'    => 'espresso_registrations',
716
-            'action'  => 'view_registration',
717
-            '_REG_ID' => $this->ID(),
718
-        ), admin_url('admin.php'));
719
-    }
720
-
721
-
722
-    /**
723
-     *    is_primary_registrant?
724
-     */
725
-    public function is_primary_registrant()
726
-    {
727
-        return $this->get('REG_count') == 1 ? true : false;
728
-    }
729
-
730
-
731
-    /**
732
-     * This returns the primary registration object for this registration group (which may be this object).
733
-     *
734
-     * @return EE_Registration
735
-     */
736
-    public function get_primary_registration()
737
-    {
738
-        if ($this->is_primary_registrant()) {
739
-            return $this;
740
-        }
741
-
742
-        //k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
743
-        $primary_registrant = EEM_Registration::instance()->get_one(array(
744
-            array(
745
-                'TXN_ID'    => $this->transaction_ID(),
746
-                'REG_count' => 1,
747
-            ),
748
-        ));
749
-        return $primary_registrant;
750
-    }
751
-
752
-
753
-    /**
754
-     *        get  Attendee Number
755
-     *
756
-     * @access        public
757
-     */
758
-    public function count()
759
-    {
760
-        return $this->get('REG_count');
761
-    }
762
-
763
-
764
-    /**
765
-     *        get Group Size
766
-     */
767
-    public function group_size()
768
-    {
769
-        return $this->get('REG_group_size');
770
-    }
771
-
772
-
773
-    /**
774
-     *        get Registration Date
775
-     */
776
-    public function date()
777
-    {
778
-        return $this->get('REG_date');
779
-    }
780
-
781
-
782
-    /**
783
-     * gets a pretty date
784
-     *
785
-     * @param string $date_format
786
-     * @param string $time_format
787
-     * @return string
788
-     */
789
-    public function pretty_date($date_format = null, $time_format = null)
790
-    {
791
-        return $this->get_datetime('REG_date', $date_format, $time_format);
792
-    }
793
-
794
-
795
-    /**
796
-     * final_price
797
-     * the registration's share of the transaction total, so that the
798
-     * sum of all the transaction's REG_final_prices equal the transaction's total
799
-     *
800
-     * @return    float
801
-     */
802
-    public function final_price()
803
-    {
804
-        return $this->get('REG_final_price');
805
-    }
806
-
807
-
808
-    /**
809
-     * pretty_final_price
810
-     *  final price as formatted string, with correct decimal places and currency symbol
811
-     *
812
-     * @return string
813
-     */
814
-    public function pretty_final_price()
815
-    {
816
-        return $this->get_pretty('REG_final_price');
817
-    }
818
-
819
-
820
-    /**
821
-     * get paid (yeah)
822
-     *
823
-     * @return    float
824
-     */
825
-    public function paid()
826
-    {
827
-        return $this->get('REG_paid');
828
-    }
829
-
830
-
831
-    /**
832
-     * pretty_paid
833
-     *
834
-     * @return    float
835
-     */
836
-    public function pretty_paid()
837
-    {
838
-        return $this->get_pretty('REG_paid');
839
-    }
840
-
841
-
842
-    /**
843
-     * owes_monies_and_can_pay
844
-     * whether or not this registration has monies owing and it's' status allows payment
845
-     *
846
-     * @param array $requires_payment
847
-     * @return bool
848
-     */
849
-    public function owes_monies_and_can_pay($requires_payment = array())
850
-    {
851
-        // these reg statuses require payment (if event is not free)
852
-        $requires_payment = ! empty($requires_payment) ? $requires_payment : EEM_Registration::reg_statuses_that_allow_payment();
853
-        if (
854
-            in_array($this->status_ID(), $requires_payment) &&
855
-            $this->final_price() != 0 &&
856
-            $this->final_price() != $this->paid()
857
-        ) {
858
-            return true;
859
-        } else {
860
-            return false;
861
-        }
862
-    }
863
-
864
-
865
-    /**
866
-     * Prints out the return value of $this->pretty_status()
867
-     *
868
-     * @param bool $show_icons
869
-     * @return void
870
-     */
871
-    public function e_pretty_status($show_icons = false)
872
-    {
873
-        echo $this->pretty_status($show_icons);
874
-    }
875
-
876
-
877
-    /**
878
-     * Returns a nice version of the status for displaying to customers
879
-     *
880
-     * @param bool $show_icons
881
-     * @return string
882
-     */
883
-    public function pretty_status($show_icons = false)
884
-    {
885
-        $status = EEM_Status::instance()->localized_status(array($this->status_ID() => __('unknown', 'event_espresso')),
886
-            false, 'sentence');
887
-        $icon   = '';
888
-        switch ($this->status_ID()) {
889
-            case EEM_Registration::status_id_approved:
890
-                $icon = $show_icons ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>' : '';
891
-                break;
892
-            case EEM_Registration::status_id_pending_payment:
893
-                $icon = $show_icons ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>' : '';
894
-                break;
895
-            case EEM_Registration::status_id_not_approved:
896
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>' : '';
897
-                break;
898
-            case EEM_Registration::status_id_cancelled:
899
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>' : '';
900
-                break;
901
-            case EEM_Registration::status_id_incomplete:
902
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>' : '';
903
-                break;
904
-            case EEM_Registration::status_id_declined:
905
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
906
-                break;
907
-            case EEM_Registration::status_id_wait_list:
908
-                $icon = $show_icons ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>' : '';
909
-                break;
910
-        }
911
-        return $icon . $status[$this->status_ID()];
912
-    }
913
-
914
-
915
-    /**
916
-     *        get Attendee Is Going
917
-     */
918
-    public function att_is_going()
919
-    {
920
-        return $this->get('REG_att_is_going');
921
-    }
922
-
923
-
924
-    /**
925
-     * Gets related answers
926
-     *
927
-     * @param array $query_params like EEM_Base::get_all
928
-     * @return EE_Answer[]
929
-     */
930
-    public function answers($query_params = null)
931
-    {
932
-        return $this->get_many_related('Answer', $query_params);
933
-    }
934
-
935
-
936
-    /**
937
-     * Gets the registration's answer value to the specified question
938
-     * (either the question's ID or a question object)
939
-     *
940
-     * @param EE_Question|int $question
941
-     * @param bool            $pretty_value
942
-     * @return array|string if pretty_value= true, the result will always be a string
943
-     * (because the answer might be an array of answer values, so passing pretty_value=true
944
-     * will convert it into some kind of string)
945
-     */
946
-    public function answer_value_to_question($question, $pretty_value = true)
947
-    {
948
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
949
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
950
-    }
951
-
952
-
953
-    /**
954
-     * question_groups
955
-     * returns an array of EE_Question_Group objects for this registration
956
-     *
957
-     * @return EE_Question_Group[]
958
-     */
959
-    public function question_groups()
960
-    {
961
-        $question_groups = array();
962
-        if ($this->event() instanceof EE_Event) {
963
-            $question_groups = $this->event()->question_groups(
964
-                array(
965
-                    array(
966
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
967
-                    ),
968
-                    'order_by' => array('QSG_order' => 'ASC'),
969
-                )
970
-            );
971
-        }
972
-        return $question_groups;
973
-    }
974
-
975
-
976
-    /**
977
-     * count_question_groups
978
-     * returns a count of the number of EE_Question_Group objects for this registration
979
-     *
980
-     * @return int
981
-     */
982
-    public function count_question_groups()
983
-    {
984
-        $qg_count = 0;
985
-        if ($this->event() instanceof EE_Event) {
986
-            $qg_count = $this->event()->count_related(
987
-                'Question_Group',
988
-                array(
989
-                    array(
990
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
991
-                    ),
992
-                )
993
-            );
994
-        }
995
-        return $qg_count;
996
-    }
997
-
998
-
999
-    /**
1000
-     * Returns the registration date in the 'standard' string format
1001
-     * (function may be improved in the future to allow for different formats and timezones)
1002
-     *
1003
-     * @return string
1004
-     */
1005
-    public function reg_date()
1006
-    {
1007
-        return $this->get_datetime('REG_date');
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1013
-     * the ticket this registration purchased, or the datetime they have registered
1014
-     * to attend)
1015
-     *
1016
-     * @return EE_Datetime_Ticket
1017
-     */
1018
-    public function datetime_ticket()
1019
-    {
1020
-        return $this->get_first_related('Datetime_Ticket');
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * Sets the registration's datetime_ticket.
1026
-     *
1027
-     * @param EE_Datetime_Ticket $datetime_ticket
1028
-     * @return EE_Datetime_Ticket
1029
-     */
1030
-    public function set_datetime_ticket($datetime_ticket)
1031
-    {
1032
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1033
-    }
1034
-
1035
-    /**
1036
-     * Gets deleted
1037
-     *
1038
-     * @return boolean
1039
-     */
1040
-    public function deleted()
1041
-    {
1042
-        return $this->get('REG_deleted');
1043
-    }
1044
-
1045
-    /**
1046
-     * Sets deleted
1047
-     *
1048
-     * @param boolean $deleted
1049
-     * @return boolean
1050
-     */
1051
-    public function set_deleted($deleted)
1052
-    {
1053
-        if ($deleted) {
1054
-            $this->delete();
1055
-        } else {
1056
-            $this->restore();
1057
-        }
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * Get the status object of this object
1063
-     *
1064
-     * @return EE_Status
1065
-     */
1066
-    public function status_obj()
1067
-    {
1068
-        return $this->get_first_related('Status');
1069
-    }
1070
-
1071
-
1072
-    /**
1073
-     * Returns the number of times this registration has checked into any of the datetimes
1074
-     * its available for
1075
-     *
1076
-     * @return int
1077
-     */
1078
-    public function count_checkins()
1079
-    {
1080
-        return $this->get_model()->count_related($this, 'Checkin');
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1086
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1087
-     *
1088
-     * @return int
1089
-     */
1090
-    public function count_checkins_not_checkedout()
1091
-    {
1092
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1098
-     *
1099
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1100
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1101
-     *                                          consider registration status as well as datetime access.
1102
-     * @return bool
1103
-     */
1104
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1105
-    {
1106
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1107
-
1108
-        //first check registration status
1109
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1110
-            return false;
1111
-        }
1112
-        //is there a datetime ticket that matches this dtt_ID?
1113
-        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1114
-            array(
1115
-                'TKT_ID' => $this->get('TKT_ID'),
1116
-                'DTT_ID' => $DTT_ID,
1117
-            ),
1118
-        )))
1119
-        ) {
1120
-            return false;
1121
-        }
1122
-
1123
-        //final check is against TKT_uses
1124
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1130
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1131
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1132
-     * then return false.  Otherwise return true.
1133
-     *
1134
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1135
-     * @return bool   true means can checkin.  false means cannot checkin.
1136
-     */
1137
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1138
-    {
1139
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1140
-
1141
-        if (! $DTT_ID) {
1142
-            return false;
1143
-        }
1144
-
1145
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1146
-
1147
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can check-in
1148
-        // or not.
1149
-        if (! $max_uses || $max_uses === EE_INF) {
1150
-            return true;
1151
-        }
1152
-
1153
-        //does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1154
-        //go ahead and toggle.
1155
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1156
-            return true;
1157
-        }
1158
-
1159
-        //made it here so the last check is whether the number of checkins per unique datetime on this registration
1160
-        //disallows further check-ins.
1161
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1162
-            array(
1163
-                'REG_ID' => $this->ID(),
1164
-                'CHK_in' => true,
1165
-            ),
1166
-        ), 'DTT_ID', true);
1167
-        // checkins have already reached their max number of uses
1168
-        // so registrant can NOT checkin
1169
-        if ($count_unique_dtt_checkins >= $max_uses) {
1170
-            EE_Error::add_error(__('Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1171
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1172
-            return false;
1173
-        }
1174
-        return true;
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * toggle Check-in status for this registration
1180
-     * Check-ins are toggled in the following order:
1181
-     * never checked in -> checked in
1182
-     * checked in -> checked out
1183
-     * checked out -> checked in
1184
-     *
1185
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1186
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1187
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1188
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1189
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1193
-    {
1194
-        if (empty($DTT_ID)) {
1195
-            $datetime = $this->get_latest_related_datetime();
1196
-            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1197
-            // verify the registration can checkin for the given DTT_ID
1198
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1199
-            EE_Error::add_error(
1200
-                sprintf(
1201
-                    __('The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1202
-                        'event_espresso'),
1203
-                    $this->ID(),
1204
-                    $DTT_ID
1205
-                ),
1206
-                __FILE__, __FUNCTION__, __LINE__
1207
-            );
1208
-            return false;
1209
-        }
1210
-        $status_paths = array(
1211
-            EE_Registration::checkin_status_never => EE_Registration::checkin_status_in,
1212
-            EE_Registration::checkin_status_in    => EE_Registration::checkin_status_out,
1213
-            EE_Registration::checkin_status_out   => EE_Registration::checkin_status_in,
1214
-        );
1215
-        //start by getting the current status so we know what status we'll be changing to.
1216
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1217
-        $status_to  = $status_paths[$cur_status];
1218
-        // database only records true for checked IN or false for checked OUT
1219
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1220
-        $new_status = $status_to === EE_Registration::checkin_status_in ? true : false;
1221
-        // add relation - note Check-ins are always creating new rows
1222
-        // because we are keeping track of Check-ins over time.
1223
-        // Eventually we'll probably want to show a list table
1224
-        // for the individual Check-ins so that they can be managed.
1225
-        $checkin = EE_Checkin::new_instance(array(
1226
-            'REG_ID' => $this->ID(),
1227
-            'DTT_ID' => $DTT_ID,
1228
-            'CHK_in' => $new_status,
1229
-        ));
1230
-        // if the record could not be saved then return false
1231
-        if ($checkin->save() === 0) {
1232
-            if (WP_DEBUG) {
1233
-                global $wpdb;
1234
-                $error = sprintf(
1235
-                    __('Registration check in update failed because of the following database error: %1$s%2$s',
1236
-                        'event_espresso'),
1237
-                    '<br />',
1238
-                    $wpdb->last_error
1239
-                );
1240
-            } else {
1241
-                $error = __('Registration check in update failed because of an unknown database error',
1242
-                    'event_espresso');
1243
-            }
1244
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1245
-            return false;
1246
-        }
1247
-        return $status_to;
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1253
-     * "Latest" is defined by the `DTT_EVT_start` column.
1254
-     *
1255
-     * @return EE_Datetime|null
1256
-     * @throws \EE_Error
1257
-     */
1258
-    public function get_latest_related_datetime()
1259
-    {
1260
-        return EEM_Datetime::instance()->get_one(
1261
-            array(
1262
-                array(
1263
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1264
-                ),
1265
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1266
-            )
1267
-        );
1268
-    }
1269
-
1270
-
1271
-    /**
1272
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1273
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1274
-     *
1275
-     * @throws \EE_Error
1276
-     */
1277
-    public function get_earliest_related_datetime()
1278
-    {
1279
-        return EEM_Datetime::instance()->get_one(
1280
-            array(
1281
-                array(
1282
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1283
-                ),
1284
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1285
-            )
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * This method simply returns the check-in status for this registration and the given datetime.
1292
-     * If neither the datetime nor the checkin values are provided as arguments,
1293
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1294
-     *
1295
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1296
-     *                            (if empty we'll get the primary datetime for
1297
-     *                            this registration (via event) and use it's ID);
1298
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1299
-     * @return int                Integer representing Check-in status.
1300
-     * @throws \EE_Error
1301
-     */
1302
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1303
-    {
1304
-        $checkin_query_params = array(
1305
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1306
-        );
1307
-
1308
-        if ($DTT_ID > 0) {
1309
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1310
-        }
1311
-
1312
-        //get checkin object (if exists)
1313
-        $checkin = $checkin instanceof EE_Checkin
1314
-            ? $checkin
1315
-            : $this->get_first_related('Checkin', $checkin_query_params);
1316
-        if ($checkin instanceof EE_Checkin) {
1317
-            if ($checkin->get('CHK_in')) {
1318
-                return EE_Registration::checkin_status_in; //checked in
1319
-            }
1320
-            return EE_Registration::checkin_status_out; //had checked in but is now checked out.
1321
-        }
1322
-        return EE_Registration::checkin_status_never; //never been checked in
1323
-    }
1324
-
1325
-
1326
-    /**
1327
-     * This method returns a localized message for the toggled Check-in message.
1328
-     *
1329
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1330
-     *                     then it is assumed Check-in for primary datetime was toggled.
1331
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1332
-     *                     message can be customized with the attendee name.
1333
-     * @return string         internationalized message
1334
-     */
1335
-    public function get_checkin_msg($DTT_ID, $error = false)
1336
-    {
1337
-        //let's get the attendee first so we can include the name of the attendee
1338
-        $attendee = $this->get_first_related('Attendee');
1339
-        if ($attendee instanceof EE_Attendee) {
1340
-            if ($error) {
1341
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1342
-            }
1343
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1344
-            //what is the status message going to be?
1345
-            switch ($cur_status) {
1346
-                case EE_Registration::checkin_status_never :
1347
-                    return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1348
-                        $attendee->full_name());
1349
-                    break;
1350
-                case EE_Registration::checkin_status_in :
1351
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1352
-                    break;
1353
-                case EE_Registration::checkin_status_out :
1354
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1355
-                    break;
1356
-            }
1357
-        }
1358
-        return __("The check-in status could not be determined.", "event_espresso");
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * Returns the related EE_Transaction to this registration
1364
-     *
1365
-     * @return EE_Transaction
1366
-     */
1367
-    public function transaction()
1368
-    {
1369
-        $transaction = $this->get_first_related('Transaction');
1370
-        if (! $transaction instanceof \EE_Transaction) {
1371
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1372
-        }
1373
-        return $transaction;
1374
-    }
1375
-
1376
-
1377
-    /**
1378
-     *        get Registration Code
1379
-     */
1380
-    public function reg_code()
1381
-    {
1382
-        return $this->get('REG_code');
1383
-    }
1384
-
1385
-
1386
-    /**
1387
-     *        get Transaction ID
1388
-     */
1389
-    public function transaction_ID()
1390
-    {
1391
-        return $this->get('TXN_ID');
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * @return int
1397
-     */
1398
-    public function ticket_ID()
1399
-    {
1400
-        return $this->get('TKT_ID');
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     *        Set Registration Code
1406
-     *
1407
-     * @access    public
1408
-     * @param    string  $REG_code Registration Code
1409
-     * @param    boolean $use_default
1410
-     */
1411
-    public function set_reg_code($REG_code, $use_default = false)
1412
-    {
1413
-        if (empty($REG_code)) {
1414
-            EE_Error::add_error(__('REG_code can not be empty.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1415
-            return;
1416
-        }
1417
-        if (! $this->reg_code()) {
1418
-            parent::set('REG_code', $REG_code, $use_default);
1419
-        } else {
1420
-            EE_Error::doing_it_wrong(
1421
-                __CLASS__ . '::' . __FUNCTION__,
1422
-                __('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1423
-                '4.6.0'
1424
-            );
1425
-        }
1426
-    }
1427
-
1428
-
1429
-    /**
1430
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1431
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1432
-     *    $registration->transaction()->registrations();
1433
-     *
1434
-     * @since 4.5.0
1435
-     * @return EE_Registration[]  or empty array if this isn't a group registration.
1436
-     */
1437
-    public function get_all_other_registrations_in_group()
1438
-    {
1439
-        if ($this->group_size() < 2) {
1440
-            return array();
1441
-        }
1442
-
1443
-        $query[0] = array(
1444
-            'TXN_ID' => $this->transaction_ID(),
1445
-            'REG_ID' => array('!=', $this->ID()),
1446
-            'TKT_ID' => $this->ticket_ID(),
1447
-        );
1448
-
1449
-        $registrations = $this->get_model()->get_all($query);
1450
-        return $registrations;
1451
-    }
1452
-
1453
-    /**
1454
-     * Return the link to the admin details for the object.
1455
-     *
1456
-     * @return string
1457
-     */
1458
-    public function get_admin_details_link()
1459
-    {
1460
-        EE_Registry::instance()->load_helper('URL');
1461
-        return EEH_URL::add_query_args_and_nonce(
1462
-            array(
1463
-                'page'    => 'espresso_registrations',
1464
-                'action'  => 'view_registration',
1465
-                '_REG_ID' => $this->ID(),
1466
-            ),
1467
-            admin_url('admin.php')
1468
-        );
1469
-    }
1470
-
1471
-    /**
1472
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1473
-     *
1474
-     * @return string
1475
-     */
1476
-    public function get_admin_edit_link()
1477
-    {
1478
-        return $this->get_admin_details_link();
1479
-    }
1480
-
1481
-    /**
1482
-     * Returns the link to a settings page for the object.
1483
-     *
1484
-     * @return string
1485
-     */
1486
-    public function get_admin_settings_link()
1487
-    {
1488
-        return $this->get_admin_details_link();
1489
-    }
1490
-
1491
-    /**
1492
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1493
-     *
1494
-     * @return string
1495
-     */
1496
-    public function get_admin_overview_link()
1497
-    {
1498
-        EE_Registry::instance()->load_helper('URL');
1499
-        return EEH_URL::add_query_args_and_nonce(
1500
-            array(
1501
-                'page' => 'espresso_registrations',
1502
-            ),
1503
-            admin_url('admin.php')
1504
-        );
1505
-    }
1506
-
1507
-
1508
-    /**
1509
-     * @param array $query_params
1510
-     * @return \EE_Registration[]
1511
-     * @throws \EE_Error
1512
-     */
1513
-    public function payments($query_params = array())
1514
-    {
1515
-        return $this->get_many_related('Payment', $query_params);
1516
-    }
1517
-
1518
-
1519
-    /**
1520
-     * @param array $query_params
1521
-     * @return \EE_Registration_Payment[]
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function registration_payments($query_params = array())
1525
-    {
1526
-        return $this->get_many_related('Registration_Payment', $query_params);
1527
-    }
1528
-
1529
-
1530
-    /**
1531
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1532
-     * Note: if there are no payments on the registration there will be no payment method returned.
1533
-     *
1534
-     * @return EE_Payment_Method|null
1535
-     */
1536
-    public function payment_method()
1537
-    {
1538
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1539
-    }
1540
-
1541
-
1542
-    /**
1543
-     * @return \EE_Line_Item
1544
-     * @throws EntityNotFoundException
1545
-     * @throws \EE_Error
1546
-     */
1547
-    public function ticket_line_item()
1548
-    {
1549
-        $ticket            = $this->ticket();
1550
-        $transaction       = $this->transaction();
1551
-        $line_item         = null;
1552
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1553
-            $transaction->total_line_item(),
1554
-            'Ticket',
1555
-            array($ticket->ID())
1556
-        );
1557
-        foreach ($ticket_line_items as $ticket_line_item) {
1558
-            if (
1559
-                $ticket_line_item instanceof \EE_Line_Item
1560
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1561
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1562
-            ) {
1563
-                $line_item = $ticket_line_item;
1564
-                break;
1565
-            }
1566
-        }
1567
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1568
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1569
-        }
1570
-        return $line_item;
1571
-    }
1572
-
1573
-
1574
-    /**
1575
-     * Soft Deletes this model object.
1576
-     *
1577
-     * @return boolean | int
1578
-     * @throws \RuntimeException
1579
-     * @throws \EE_Error
1580
-     */
1581
-    public function delete()
1582
-    {
1583
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1584
-            $this->set_status(EEM_Registration::status_id_cancelled);
1585
-        }
1586
-        return parent::delete();
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1592
-     *
1593
-     * @throws \EE_Error
1594
-     * @throws \RuntimeException
1595
-     */
1596
-    public function restore()
1597
-    {
1598
-        $previous_status = $this->get_extra_meta(
1599
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1600
-            true,
1601
-            EEM_Registration::status_id_cancelled
1602
-        );
1603
-        if ($previous_status) {
1604
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1605
-            $this->set_status($previous_status);
1606
-        }
1607
-        return parent::restore();
1608
-    }
1609
-
1610
-
1611
-
1612
-    /*************************** DEPRECATED ***************************/
1613
-
1614
-
1615
-    /**
1616
-     * @deprecated
1617
-     * @since     4.7.0
1618
-     * @access    public
1619
-     */
1620
-    public function price_paid()
1621
-    {
1622
-        EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1623
-            __('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1624
-            '4.7.0');
1625
-        return $this->final_price();
1626
-    }
1627
-
1628
-
1629
-    /**
1630
-     * @deprecated
1631
-     * @since     4.7.0
1632
-     * @access    public
1633
-     * @param    float $REG_final_price
1634
-     */
1635
-    public function set_price_paid($REG_final_price = 0.00)
1636
-    {
1637
-        EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
1638
-            __('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
1639
-            '4.7.0');
1640
-        $this->set_final_price($REG_final_price);
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * @deprecated
1646
-     * @since 4.7.0
1647
-     * @return string
1648
-     */
1649
-    public function pretty_price_paid()
1650
-    {
1651
-        EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
1652
-            __('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
1653
-                'event_espresso'), '4.7.0');
1654
-        return $this->pretty_final_price();
1655
-    }
1656
-
1657
-
1658
-    /**
1659
-     * Gets the primary datetime related to this registration via the related Event to this registration
1660
-     *
1661
-     * @deprecated 4.9.17
1662
-     * @return EE_Datetime
1663
-     */
1664
-    public function get_related_primary_datetime()
1665
-    {
1666
-        EE_Error::doing_it_wrong(
1667
-            __METHOD__,
1668
-            esc_html__(
1669
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
1670
-                'event_espresso'
1671
-            ),
1672
-            '4.9.17',
1673
-            '5.0.0'
1674
-        );
1675
-        return $this->event()->primary_datetime();
1676
-    }
18
+	/**
19
+	 * Used to reference when a registration has never been checked in.
20
+	 *
21
+	 * @type int
22
+	 */
23
+	const checkin_status_never = 2;
24
+
25
+	/**
26
+	 * Used to reference when a registration has been checked in.
27
+	 *
28
+	 * @type int
29
+	 */
30
+	const checkin_status_in = 1;
31
+
32
+
33
+	/**
34
+	 * Used to reference when a registration has been checked out.
35
+	 *
36
+	 * @type int
37
+	 */
38
+	const checkin_status_out = 0;
39
+
40
+
41
+	/**
42
+	 * extra meta key for tracking reg status os trashed registrations
43
+	 *
44
+	 * @type string
45
+	 */
46
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
47
+
48
+
49
+	/**
50
+	 * extra meta key for tracking if registration has reserved ticket
51
+	 *
52
+	 * @type string
53
+	 */
54
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
55
+
56
+
57
+
58
+	/**
59
+	 * Set Event ID
60
+	 *
61
+	 * @param int $EVT_ID Event ID
62
+	 */
63
+	public function set_event($EVT_ID = 0)
64
+	{
65
+		$this->set('EVT_ID', $EVT_ID);
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
72
+	 * be routed to internal methods
73
+	 *
74
+	 * @param string $field_name
75
+	 * @param mixed  $field_value
76
+	 * @param bool   $use_default
77
+	 * @throws \EE_Error
78
+	 * @throws \RuntimeException
79
+	 */
80
+	public function set($field_name, $field_value, $use_default = false)
81
+	{
82
+		switch ($field_name) {
83
+			case 'REG_code' :
84
+				if (! empty($field_value) && $this->reg_code() === null) {
85
+					$this->set_reg_code($field_value, $use_default);
86
+				}
87
+				break;
88
+			case 'STS_ID' :
89
+				$this->set_status($field_value, $use_default);
90
+				break;
91
+			default :
92
+				parent::set($field_name, $field_value, $use_default);
93
+		}
94
+	}
95
+
96
+
97
+	/**
98
+	 * Set Status ID
99
+	 * updates the registration status and ALSO...
100
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
101
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
102
+	 *
103
+	 * @param string  $new_STS_ID
104
+	 * @param boolean $use_default
105
+	 * @return bool
106
+	 * @throws \RuntimeException
107
+	 * @throws \EE_Error
108
+	 */
109
+	public function set_status($new_STS_ID = null, $use_default = false)
110
+	{
111
+		// get current REG_Status
112
+		$old_STS_ID = $this->status_ID();
113
+		// if status has changed
114
+		if (
115
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
116
+			&& ! empty($old_STS_ID) // and that old status is actually set
117
+			&& ! empty($new_STS_ID) // as well as the new status
118
+			&& $this->ID() // ensure registration is in the db
119
+		) {
120
+			// TO approved
121
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
122
+				// reserve a space by incrementing ticket and datetime sold values
123
+				$this->_reserve_registration_space();
124
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID);
125
+				// OR FROM  approved
126
+			} else if ($old_STS_ID === EEM_Registration::status_id_approved) {
127
+				// release a space by decrementing ticket and datetime sold values
128
+				$this->_release_registration_space();
129
+				do_action('AHEE__EE_Registration__set_status__from_approved', $this, $old_STS_ID, $new_STS_ID);
130
+			}
131
+			// update status
132
+			parent::set('STS_ID', $new_STS_ID, $use_default);
133
+			$this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID);
134
+			/** @type EE_Transaction_Payments $transaction_payments */
135
+			$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
136
+			$transaction_payments->recalculate_transaction_total($this->transaction(), false);
137
+			$this->transaction()->update_status_based_on_total_paid(true);
138
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID);
139
+			return true;
140
+		}
141
+		//even though the old value matches the new value, it's still good to
142
+		//allow the parent set method to have a say
143
+		parent::set('STS_ID', $new_STS_ID, $use_default);
144
+		return true;
145
+	}
146
+
147
+
148
+	/**
149
+	 * update REGs and TXN when cancelled or declined registrations involved
150
+	 *
151
+	 * @param string $new_STS_ID
152
+	 * @param string $old_STS_ID
153
+	 * @throws \EE_Error
154
+	 */
155
+	private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID)
156
+	{
157
+		// these reg statuses should not be considered in any calculations involving monies owing
158
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
159
+		// true if registration has been cancelled or declined
160
+		if (
161
+			in_array($new_STS_ID, $closed_reg_statuses, true)
162
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
163
+		) {
164
+			/** @type EE_Registration_Processor $registration_processor */
165
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
166
+			/** @type EE_Transaction_Processor $transaction_processor */
167
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
168
+			// cancelled or declined registration
169
+			$registration_processor->update_registration_after_being_canceled_or_declined(
170
+				$this,
171
+				$closed_reg_statuses
172
+			);
173
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
174
+				$this,
175
+				$closed_reg_statuses,
176
+				false
177
+			);
178
+			do_action('AHEE__EE_Registration__set_status__canceled_or_declined', $this, $old_STS_ID, $new_STS_ID);
179
+			return;
180
+		}
181
+		// true if reinstating cancelled or declined registration
182
+		if (
183
+			in_array($old_STS_ID, $closed_reg_statuses, true)
184
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
185
+		) {
186
+			/** @type EE_Registration_Processor $registration_processor */
187
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
188
+			/** @type EE_Transaction_Processor $transaction_processor */
189
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
190
+			// reinstating cancelled or declined registration
191
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
192
+				$this,
193
+				$closed_reg_statuses
194
+			);
195
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
196
+				$this,
197
+				$closed_reg_statuses,
198
+				false
199
+			);
200
+			do_action('AHEE__EE_Registration__set_status__after_reinstated', $this, $old_STS_ID, $new_STS_ID);
201
+		}
202
+	}
203
+
204
+
205
+	/**
206
+	 *        get Status ID
207
+	 */
208
+	public function status_ID()
209
+	{
210
+		return $this->get('STS_ID');
211
+	}
212
+
213
+
214
+	/**
215
+	 * increments this registration's related ticket sold and corresponding datetime sold values
216
+	 *
217
+	 * @return void
218
+	 * @throws \EE_Error
219
+	 */
220
+	private function _reserve_registration_space()
221
+	{
222
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
223
+		// so stop tracking that this reg has a ticket reserved
224
+		$this->release_reserved_ticket();
225
+		$ticket = $this->ticket();
226
+		$ticket->increase_sold();
227
+		$ticket->save();
228
+		// possibly set event status to sold out
229
+		$this->event()->perform_sold_out_status_check();
230
+	}
231
+
232
+
233
+	/**
234
+	 * Gets the ticket this registration is for
235
+	 *
236
+	 * @param boolean $include_archived whether to include archived tickets or not.
237
+	 * @return EE_Ticket|EE_Base_Class
238
+	 * @throws \EE_Error
239
+	 */
240
+	public function ticket($include_archived = true)
241
+	{
242
+		$query_params = array();
243
+		if ($include_archived) {
244
+			$query_params['default_where_conditions'] = 'none';
245
+		}
246
+		return $this->get_first_related('Ticket', $query_params);
247
+	}
248
+
249
+
250
+	/**
251
+	 * Gets the event this registration is for
252
+	 *
253
+	 * @return EE_Event
254
+	 */
255
+	public function event()
256
+	{
257
+		$event = $this->get_first_related('Event');
258
+		if (! $event instanceof \EE_Event) {
259
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
260
+		}
261
+		return $event;
262
+	}
263
+
264
+
265
+	/**
266
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
267
+	 * with the author of the event this registration is for.
268
+	 *
269
+	 * @since 4.5.0
270
+	 * @return int
271
+	 */
272
+	public function wp_user()
273
+	{
274
+		$event = $this->event();
275
+		if ($event instanceof EE_Event) {
276
+			return $event->wp_user();
277
+		}
278
+		return 0;
279
+	}
280
+
281
+
282
+	/**
283
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
284
+	 *
285
+	 * @return void
286
+	 * @throws \EE_Error
287
+	 */
288
+	private function _release_registration_space()
289
+	{
290
+		$ticket = $this->ticket();
291
+		$ticket->decrease_sold();
292
+		$ticket->save();
293
+	}
294
+
295
+
296
+	/**
297
+	 * tracks this registration's ticket reservation in extra meta
298
+	 * and can increment related ticket reserved and corresponding datetime reserved values
299
+	 *
300
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
301
+	 * @return void
302
+	 * @throws \EE_Error
303
+	 */
304
+	public function reserve_ticket($update_ticket = false)
305
+	{
306
+		if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) === false) {
307
+			// PLZ NOTE: although checking $update_ticket first would be more efficient,
308
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
309
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) && $update_ticket) {
310
+				$ticket = $this->ticket();
311
+				$ticket->increase_reserved();
312
+				$ticket->save();
313
+			}
314
+		}
315
+	}
316
+
317
+
318
+	/**
319
+	 * stops tracking this registration's ticket reservation in extra meta
320
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
321
+	 *
322
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
323
+	 * @return void
324
+	 * @throws \EE_Error
325
+	 */
326
+	public function release_reserved_ticket($update_ticket = false)
327
+	{
328
+		if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) !== false) {
329
+			// PLZ NOTE: although checking $update_ticket first would be more efficient,
330
+			// we NEED to ALWAYS call delete_extra_meta(), which is why that is done first
331
+			if ($this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY) && $update_ticket) {
332
+				$ticket = $this->ticket();
333
+				$ticket->decrease_reserved();
334
+				$ticket->save();
335
+			}
336
+		}
337
+	}
338
+
339
+
340
+	/**
341
+	 * Set Attendee ID
342
+	 *
343
+	 * @param        int $ATT_ID Attendee ID
344
+	 */
345
+	public function set_attendee_id($ATT_ID = 0)
346
+	{
347
+		$this->set('ATT_ID', $ATT_ID);
348
+	}
349
+
350
+
351
+	/**
352
+	 *        Set Transaction ID
353
+	 *
354
+	 * @param        int $TXN_ID Transaction ID
355
+	 */
356
+	public function set_transaction_id($TXN_ID = 0)
357
+	{
358
+		$this->set('TXN_ID', $TXN_ID);
359
+	}
360
+
361
+
362
+	/**
363
+	 *        Set Session
364
+	 *
365
+	 * @param    string $REG_session PHP Session ID
366
+	 */
367
+	public function set_session($REG_session = '')
368
+	{
369
+		$this->set('REG_session', $REG_session);
370
+	}
371
+
372
+
373
+	/**
374
+	 *        Set Registration URL Link
375
+	 *
376
+	 * @param    string $REG_url_link Registration URL Link
377
+	 */
378
+	public function set_reg_url_link($REG_url_link = '')
379
+	{
380
+		$this->set('REG_url_link', $REG_url_link);
381
+	}
382
+
383
+
384
+	/**
385
+	 *        Set Attendee Counter
386
+	 *
387
+	 * @param        int $REG_count Primary Attendee
388
+	 */
389
+	public function set_count($REG_count = 1)
390
+	{
391
+		$this->set('REG_count', $REG_count);
392
+	}
393
+
394
+
395
+	/**
396
+	 *        Set Group Size
397
+	 *
398
+	 * @param        boolean $REG_group_size Group Registration
399
+	 */
400
+	public function set_group_size($REG_group_size = false)
401
+	{
402
+		$this->set('REG_group_size', $REG_group_size);
403
+	}
404
+
405
+
406
+	/**
407
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
408
+	 *    EEM_Registration::status_id_not_approved
409
+	 *
410
+	 * @return        boolean
411
+	 */
412
+	public function is_not_approved()
413
+	{
414
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
415
+	}
416
+
417
+
418
+	/**
419
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
420
+	 *    EEM_Registration::status_id_pending_payment
421
+	 *
422
+	 * @return        boolean
423
+	 */
424
+	public function is_pending_payment()
425
+	{
426
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
427
+	}
428
+
429
+
430
+	/**
431
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
432
+	 *
433
+	 * @return        boolean
434
+	 */
435
+	public function is_approved()
436
+	{
437
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
438
+	}
439
+
440
+
441
+	/**
442
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
443
+	 *
444
+	 * @return        boolean
445
+	 */
446
+	public function is_cancelled()
447
+	{
448
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
449
+	}
450
+
451
+
452
+	/**
453
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
454
+	 *
455
+	 * @return        boolean
456
+	 */
457
+	public function is_declined()
458
+	{
459
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
460
+	}
461
+
462
+
463
+	/**
464
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
465
+	 *    EEM_Registration::status_id_incomplete
466
+	 *
467
+	 * @return        boolean
468
+	 */
469
+	public function is_incomplete()
470
+	{
471
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
472
+	}
473
+
474
+
475
+	/**
476
+	 *        Set Registration Date
477
+	 *
478
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
479
+	 *                       Date
480
+	 */
481
+	public function set_reg_date($REG_date = false)
482
+	{
483
+		$this->set('REG_date', $REG_date);
484
+	}
485
+
486
+
487
+	/**
488
+	 *    Set final price owing for this registration after all ticket/price modifications
489
+	 *
490
+	 * @access    public
491
+	 * @param    float $REG_final_price
492
+	 */
493
+	public function set_final_price($REG_final_price = 0.00)
494
+	{
495
+		$this->set('REG_final_price', $REG_final_price);
496
+	}
497
+
498
+
499
+	/**
500
+	 *    Set amount paid towards this registration's final price
501
+	 *
502
+	 * @access    public
503
+	 * @param    float $REG_paid
504
+	 */
505
+	public function set_paid($REG_paid = 0.00)
506
+	{
507
+		$this->set('REG_paid', $REG_paid);
508
+	}
509
+
510
+
511
+	/**
512
+	 *        Attendee Is Going
513
+	 *
514
+	 * @param        boolean $REG_att_is_going Attendee Is Going
515
+	 */
516
+	public function set_att_is_going($REG_att_is_going = false)
517
+	{
518
+		$this->set('REG_att_is_going', $REG_att_is_going);
519
+	}
520
+
521
+
522
+	/**
523
+	 * Gets the related attendee
524
+	 *
525
+	 * @return EE_Attendee
526
+	 */
527
+	public function attendee()
528
+	{
529
+		return $this->get_first_related('Attendee');
530
+	}
531
+
532
+
533
+	/**
534
+	 *        get Event ID
535
+	 */
536
+	public function event_ID()
537
+	{
538
+		return $this->get('EVT_ID');
539
+	}
540
+
541
+
542
+	/**
543
+	 *        get Event ID
544
+	 */
545
+	public function event_name()
546
+	{
547
+		$event = $this->event_obj();
548
+		if ($event) {
549
+			return $event->name();
550
+		} else {
551
+			return null;
552
+		}
553
+	}
554
+
555
+
556
+	/**
557
+	 * Fetches the event this registration is for
558
+	 *
559
+	 * @return EE_Event
560
+	 */
561
+	public function event_obj()
562
+	{
563
+		return $this->get_first_related('Event');
564
+	}
565
+
566
+
567
+	/**
568
+	 *        get Attendee ID
569
+	 */
570
+	public function attendee_ID()
571
+	{
572
+		return $this->get('ATT_ID');
573
+	}
574
+
575
+
576
+	/**
577
+	 *        get PHP Session ID
578
+	 */
579
+	public function session_ID()
580
+	{
581
+		return $this->get('REG_session');
582
+	}
583
+
584
+
585
+	/**
586
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
587
+	 *
588
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
589
+	 * @return string
590
+	 */
591
+	public function receipt_url($messenger = 'html')
592
+	{
593
+
594
+		/**
595
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template already in use on old system.  If there is then we just return the standard url for it.
596
+		 *
597
+		 * @since 4.5.0
598
+		 */
599
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
600
+		$has_custom             = EEH_Template::locate_template($template_relative_path, array(), true, true, true);
601
+
602
+		if ($has_custom) {
603
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
604
+		}
605
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
606
+	}
607
+
608
+
609
+	/**
610
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
611
+	 *
612
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
613
+	 * @return string
614
+	 */
615
+	public function invoice_url($messenger = 'html')
616
+	{
617
+		/**
618
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template already in use on old system.  If there is then we just return the standard url for it.
619
+		 *
620
+		 * @since 4.5.0
621
+		 */
622
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
623
+		$has_custom             = EEH_Template::locate_template($template_relative_path, array(), true, true, true);
624
+
625
+		if ($has_custom) {
626
+			if ($messenger == 'html') {
627
+				return $this->invoice_url('launch');
628
+			}
629
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
630
+
631
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
632
+			if ($messenger == 'html') {
633
+				$query_args['html'] = true;
634
+			}
635
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
636
+		}
637
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
638
+	}
639
+
640
+
641
+	/**
642
+	 * get Registration URL Link
643
+	 *
644
+	 * @access public
645
+	 * @return string
646
+	 * @throws \EE_Error
647
+	 */
648
+	public function reg_url_link()
649
+	{
650
+		return (string)$this->get('REG_url_link');
651
+	}
652
+
653
+
654
+	/**
655
+	 * Echoes out invoice_url()
656
+	 *
657
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
658
+	 * @return void
659
+	 */
660
+	public function e_invoice_url($type = 'launch')
661
+	{
662
+		echo $this->invoice_url($type);
663
+	}
664
+
665
+
666
+	/**
667
+	 * Echoes out payment_overview_url
668
+	 */
669
+	public function e_payment_overview_url()
670
+	{
671
+		echo $this->payment_overview_url();
672
+	}
673
+
674
+
675
+	/**
676
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
677
+	 * a query parameter
678
+	 *
679
+	 * @return string
680
+	 */
681
+	public function payment_overview_url()
682
+	{
683
+		return add_query_arg(array(
684
+			'e_reg_url_link' => $this->reg_url_link(),
685
+			'step'           => 'payment_options',
686
+			'revisit'        => true,
687
+		), EE_Registry::instance()->CFG->core->reg_page_url());
688
+	}
689
+
690
+
691
+	/**
692
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
693
+	 * a query parameter
694
+	 *
695
+	 * @return string
696
+	 */
697
+	public function edit_attendee_information_url()
698
+	{
699
+		return add_query_arg(array(
700
+			'e_reg_url_link' => $this->reg_url_link(),
701
+			'step'           => 'attendee_information',
702
+			'revisit'        => true,
703
+		), EE_Registry::instance()->CFG->core->reg_page_url());
704
+	}
705
+
706
+
707
+	/**
708
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
709
+	 *
710
+	 * @return string
711
+	 */
712
+	public function get_admin_edit_url()
713
+	{
714
+		return EEH_URL::add_query_args_and_nonce(array(
715
+			'page'    => 'espresso_registrations',
716
+			'action'  => 'view_registration',
717
+			'_REG_ID' => $this->ID(),
718
+		), admin_url('admin.php'));
719
+	}
720
+
721
+
722
+	/**
723
+	 *    is_primary_registrant?
724
+	 */
725
+	public function is_primary_registrant()
726
+	{
727
+		return $this->get('REG_count') == 1 ? true : false;
728
+	}
729
+
730
+
731
+	/**
732
+	 * This returns the primary registration object for this registration group (which may be this object).
733
+	 *
734
+	 * @return EE_Registration
735
+	 */
736
+	public function get_primary_registration()
737
+	{
738
+		if ($this->is_primary_registrant()) {
739
+			return $this;
740
+		}
741
+
742
+		//k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
743
+		$primary_registrant = EEM_Registration::instance()->get_one(array(
744
+			array(
745
+				'TXN_ID'    => $this->transaction_ID(),
746
+				'REG_count' => 1,
747
+			),
748
+		));
749
+		return $primary_registrant;
750
+	}
751
+
752
+
753
+	/**
754
+	 *        get  Attendee Number
755
+	 *
756
+	 * @access        public
757
+	 */
758
+	public function count()
759
+	{
760
+		return $this->get('REG_count');
761
+	}
762
+
763
+
764
+	/**
765
+	 *        get Group Size
766
+	 */
767
+	public function group_size()
768
+	{
769
+		return $this->get('REG_group_size');
770
+	}
771
+
772
+
773
+	/**
774
+	 *        get Registration Date
775
+	 */
776
+	public function date()
777
+	{
778
+		return $this->get('REG_date');
779
+	}
780
+
781
+
782
+	/**
783
+	 * gets a pretty date
784
+	 *
785
+	 * @param string $date_format
786
+	 * @param string $time_format
787
+	 * @return string
788
+	 */
789
+	public function pretty_date($date_format = null, $time_format = null)
790
+	{
791
+		return $this->get_datetime('REG_date', $date_format, $time_format);
792
+	}
793
+
794
+
795
+	/**
796
+	 * final_price
797
+	 * the registration's share of the transaction total, so that the
798
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
799
+	 *
800
+	 * @return    float
801
+	 */
802
+	public function final_price()
803
+	{
804
+		return $this->get('REG_final_price');
805
+	}
806
+
807
+
808
+	/**
809
+	 * pretty_final_price
810
+	 *  final price as formatted string, with correct decimal places and currency symbol
811
+	 *
812
+	 * @return string
813
+	 */
814
+	public function pretty_final_price()
815
+	{
816
+		return $this->get_pretty('REG_final_price');
817
+	}
818
+
819
+
820
+	/**
821
+	 * get paid (yeah)
822
+	 *
823
+	 * @return    float
824
+	 */
825
+	public function paid()
826
+	{
827
+		return $this->get('REG_paid');
828
+	}
829
+
830
+
831
+	/**
832
+	 * pretty_paid
833
+	 *
834
+	 * @return    float
835
+	 */
836
+	public function pretty_paid()
837
+	{
838
+		return $this->get_pretty('REG_paid');
839
+	}
840
+
841
+
842
+	/**
843
+	 * owes_monies_and_can_pay
844
+	 * whether or not this registration has monies owing and it's' status allows payment
845
+	 *
846
+	 * @param array $requires_payment
847
+	 * @return bool
848
+	 */
849
+	public function owes_monies_and_can_pay($requires_payment = array())
850
+	{
851
+		// these reg statuses require payment (if event is not free)
852
+		$requires_payment = ! empty($requires_payment) ? $requires_payment : EEM_Registration::reg_statuses_that_allow_payment();
853
+		if (
854
+			in_array($this->status_ID(), $requires_payment) &&
855
+			$this->final_price() != 0 &&
856
+			$this->final_price() != $this->paid()
857
+		) {
858
+			return true;
859
+		} else {
860
+			return false;
861
+		}
862
+	}
863
+
864
+
865
+	/**
866
+	 * Prints out the return value of $this->pretty_status()
867
+	 *
868
+	 * @param bool $show_icons
869
+	 * @return void
870
+	 */
871
+	public function e_pretty_status($show_icons = false)
872
+	{
873
+		echo $this->pretty_status($show_icons);
874
+	}
875
+
876
+
877
+	/**
878
+	 * Returns a nice version of the status for displaying to customers
879
+	 *
880
+	 * @param bool $show_icons
881
+	 * @return string
882
+	 */
883
+	public function pretty_status($show_icons = false)
884
+	{
885
+		$status = EEM_Status::instance()->localized_status(array($this->status_ID() => __('unknown', 'event_espresso')),
886
+			false, 'sentence');
887
+		$icon   = '';
888
+		switch ($this->status_ID()) {
889
+			case EEM_Registration::status_id_approved:
890
+				$icon = $show_icons ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>' : '';
891
+				break;
892
+			case EEM_Registration::status_id_pending_payment:
893
+				$icon = $show_icons ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>' : '';
894
+				break;
895
+			case EEM_Registration::status_id_not_approved:
896
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>' : '';
897
+				break;
898
+			case EEM_Registration::status_id_cancelled:
899
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>' : '';
900
+				break;
901
+			case EEM_Registration::status_id_incomplete:
902
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>' : '';
903
+				break;
904
+			case EEM_Registration::status_id_declined:
905
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
906
+				break;
907
+			case EEM_Registration::status_id_wait_list:
908
+				$icon = $show_icons ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>' : '';
909
+				break;
910
+		}
911
+		return $icon . $status[$this->status_ID()];
912
+	}
913
+
914
+
915
+	/**
916
+	 *        get Attendee Is Going
917
+	 */
918
+	public function att_is_going()
919
+	{
920
+		return $this->get('REG_att_is_going');
921
+	}
922
+
923
+
924
+	/**
925
+	 * Gets related answers
926
+	 *
927
+	 * @param array $query_params like EEM_Base::get_all
928
+	 * @return EE_Answer[]
929
+	 */
930
+	public function answers($query_params = null)
931
+	{
932
+		return $this->get_many_related('Answer', $query_params);
933
+	}
934
+
935
+
936
+	/**
937
+	 * Gets the registration's answer value to the specified question
938
+	 * (either the question's ID or a question object)
939
+	 *
940
+	 * @param EE_Question|int $question
941
+	 * @param bool            $pretty_value
942
+	 * @return array|string if pretty_value= true, the result will always be a string
943
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
944
+	 * will convert it into some kind of string)
945
+	 */
946
+	public function answer_value_to_question($question, $pretty_value = true)
947
+	{
948
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
949
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
950
+	}
951
+
952
+
953
+	/**
954
+	 * question_groups
955
+	 * returns an array of EE_Question_Group objects for this registration
956
+	 *
957
+	 * @return EE_Question_Group[]
958
+	 */
959
+	public function question_groups()
960
+	{
961
+		$question_groups = array();
962
+		if ($this->event() instanceof EE_Event) {
963
+			$question_groups = $this->event()->question_groups(
964
+				array(
965
+					array(
966
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
967
+					),
968
+					'order_by' => array('QSG_order' => 'ASC'),
969
+				)
970
+			);
971
+		}
972
+		return $question_groups;
973
+	}
974
+
975
+
976
+	/**
977
+	 * count_question_groups
978
+	 * returns a count of the number of EE_Question_Group objects for this registration
979
+	 *
980
+	 * @return int
981
+	 */
982
+	public function count_question_groups()
983
+	{
984
+		$qg_count = 0;
985
+		if ($this->event() instanceof EE_Event) {
986
+			$qg_count = $this->event()->count_related(
987
+				'Question_Group',
988
+				array(
989
+					array(
990
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
991
+					),
992
+				)
993
+			);
994
+		}
995
+		return $qg_count;
996
+	}
997
+
998
+
999
+	/**
1000
+	 * Returns the registration date in the 'standard' string format
1001
+	 * (function may be improved in the future to allow for different formats and timezones)
1002
+	 *
1003
+	 * @return string
1004
+	 */
1005
+	public function reg_date()
1006
+	{
1007
+		return $this->get_datetime('REG_date');
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1013
+	 * the ticket this registration purchased, or the datetime they have registered
1014
+	 * to attend)
1015
+	 *
1016
+	 * @return EE_Datetime_Ticket
1017
+	 */
1018
+	public function datetime_ticket()
1019
+	{
1020
+		return $this->get_first_related('Datetime_Ticket');
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * Sets the registration's datetime_ticket.
1026
+	 *
1027
+	 * @param EE_Datetime_Ticket $datetime_ticket
1028
+	 * @return EE_Datetime_Ticket
1029
+	 */
1030
+	public function set_datetime_ticket($datetime_ticket)
1031
+	{
1032
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1033
+	}
1034
+
1035
+	/**
1036
+	 * Gets deleted
1037
+	 *
1038
+	 * @return boolean
1039
+	 */
1040
+	public function deleted()
1041
+	{
1042
+		return $this->get('REG_deleted');
1043
+	}
1044
+
1045
+	/**
1046
+	 * Sets deleted
1047
+	 *
1048
+	 * @param boolean $deleted
1049
+	 * @return boolean
1050
+	 */
1051
+	public function set_deleted($deleted)
1052
+	{
1053
+		if ($deleted) {
1054
+			$this->delete();
1055
+		} else {
1056
+			$this->restore();
1057
+		}
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * Get the status object of this object
1063
+	 *
1064
+	 * @return EE_Status
1065
+	 */
1066
+	public function status_obj()
1067
+	{
1068
+		return $this->get_first_related('Status');
1069
+	}
1070
+
1071
+
1072
+	/**
1073
+	 * Returns the number of times this registration has checked into any of the datetimes
1074
+	 * its available for
1075
+	 *
1076
+	 * @return int
1077
+	 */
1078
+	public function count_checkins()
1079
+	{
1080
+		return $this->get_model()->count_related($this, 'Checkin');
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1086
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1087
+	 *
1088
+	 * @return int
1089
+	 */
1090
+	public function count_checkins_not_checkedout()
1091
+	{
1092
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1098
+	 *
1099
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1100
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1101
+	 *                                          consider registration status as well as datetime access.
1102
+	 * @return bool
1103
+	 */
1104
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1105
+	{
1106
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1107
+
1108
+		//first check registration status
1109
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1110
+			return false;
1111
+		}
1112
+		//is there a datetime ticket that matches this dtt_ID?
1113
+		if (! (EEM_Datetime_Ticket::instance()->exists(array(
1114
+			array(
1115
+				'TKT_ID' => $this->get('TKT_ID'),
1116
+				'DTT_ID' => $DTT_ID,
1117
+			),
1118
+		)))
1119
+		) {
1120
+			return false;
1121
+		}
1122
+
1123
+		//final check is against TKT_uses
1124
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1130
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1131
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1132
+	 * then return false.  Otherwise return true.
1133
+	 *
1134
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1135
+	 * @return bool   true means can checkin.  false means cannot checkin.
1136
+	 */
1137
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1138
+	{
1139
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1140
+
1141
+		if (! $DTT_ID) {
1142
+			return false;
1143
+		}
1144
+
1145
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1146
+
1147
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can check-in
1148
+		// or not.
1149
+		if (! $max_uses || $max_uses === EE_INF) {
1150
+			return true;
1151
+		}
1152
+
1153
+		//does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1154
+		//go ahead and toggle.
1155
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1156
+			return true;
1157
+		}
1158
+
1159
+		//made it here so the last check is whether the number of checkins per unique datetime on this registration
1160
+		//disallows further check-ins.
1161
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1162
+			array(
1163
+				'REG_ID' => $this->ID(),
1164
+				'CHK_in' => true,
1165
+			),
1166
+		), 'DTT_ID', true);
1167
+		// checkins have already reached their max number of uses
1168
+		// so registrant can NOT checkin
1169
+		if ($count_unique_dtt_checkins >= $max_uses) {
1170
+			EE_Error::add_error(__('Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1171
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1172
+			return false;
1173
+		}
1174
+		return true;
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * toggle Check-in status for this registration
1180
+	 * Check-ins are toggled in the following order:
1181
+	 * never checked in -> checked in
1182
+	 * checked in -> checked out
1183
+	 * checked out -> checked in
1184
+	 *
1185
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1186
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1187
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1188
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1189
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1193
+	{
1194
+		if (empty($DTT_ID)) {
1195
+			$datetime = $this->get_latest_related_datetime();
1196
+			$DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1197
+			// verify the registration can checkin for the given DTT_ID
1198
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1199
+			EE_Error::add_error(
1200
+				sprintf(
1201
+					__('The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1202
+						'event_espresso'),
1203
+					$this->ID(),
1204
+					$DTT_ID
1205
+				),
1206
+				__FILE__, __FUNCTION__, __LINE__
1207
+			);
1208
+			return false;
1209
+		}
1210
+		$status_paths = array(
1211
+			EE_Registration::checkin_status_never => EE_Registration::checkin_status_in,
1212
+			EE_Registration::checkin_status_in    => EE_Registration::checkin_status_out,
1213
+			EE_Registration::checkin_status_out   => EE_Registration::checkin_status_in,
1214
+		);
1215
+		//start by getting the current status so we know what status we'll be changing to.
1216
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1217
+		$status_to  = $status_paths[$cur_status];
1218
+		// database only records true for checked IN or false for checked OUT
1219
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1220
+		$new_status = $status_to === EE_Registration::checkin_status_in ? true : false;
1221
+		// add relation - note Check-ins are always creating new rows
1222
+		// because we are keeping track of Check-ins over time.
1223
+		// Eventually we'll probably want to show a list table
1224
+		// for the individual Check-ins so that they can be managed.
1225
+		$checkin = EE_Checkin::new_instance(array(
1226
+			'REG_ID' => $this->ID(),
1227
+			'DTT_ID' => $DTT_ID,
1228
+			'CHK_in' => $new_status,
1229
+		));
1230
+		// if the record could not be saved then return false
1231
+		if ($checkin->save() === 0) {
1232
+			if (WP_DEBUG) {
1233
+				global $wpdb;
1234
+				$error = sprintf(
1235
+					__('Registration check in update failed because of the following database error: %1$s%2$s',
1236
+						'event_espresso'),
1237
+					'<br />',
1238
+					$wpdb->last_error
1239
+				);
1240
+			} else {
1241
+				$error = __('Registration check in update failed because of an unknown database error',
1242
+					'event_espresso');
1243
+			}
1244
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1245
+			return false;
1246
+		}
1247
+		return $status_to;
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1253
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1254
+	 *
1255
+	 * @return EE_Datetime|null
1256
+	 * @throws \EE_Error
1257
+	 */
1258
+	public function get_latest_related_datetime()
1259
+	{
1260
+		return EEM_Datetime::instance()->get_one(
1261
+			array(
1262
+				array(
1263
+					'Ticket.Registration.REG_ID' => $this->ID(),
1264
+				),
1265
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1266
+			)
1267
+		);
1268
+	}
1269
+
1270
+
1271
+	/**
1272
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1273
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1274
+	 *
1275
+	 * @throws \EE_Error
1276
+	 */
1277
+	public function get_earliest_related_datetime()
1278
+	{
1279
+		return EEM_Datetime::instance()->get_one(
1280
+			array(
1281
+				array(
1282
+					'Ticket.Registration.REG_ID' => $this->ID(),
1283
+				),
1284
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1285
+			)
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * This method simply returns the check-in status for this registration and the given datetime.
1292
+	 * If neither the datetime nor the checkin values are provided as arguments,
1293
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1294
+	 *
1295
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1296
+	 *                            (if empty we'll get the primary datetime for
1297
+	 *                            this registration (via event) and use it's ID);
1298
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1299
+	 * @return int                Integer representing Check-in status.
1300
+	 * @throws \EE_Error
1301
+	 */
1302
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1303
+	{
1304
+		$checkin_query_params = array(
1305
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1306
+		);
1307
+
1308
+		if ($DTT_ID > 0) {
1309
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1310
+		}
1311
+
1312
+		//get checkin object (if exists)
1313
+		$checkin = $checkin instanceof EE_Checkin
1314
+			? $checkin
1315
+			: $this->get_first_related('Checkin', $checkin_query_params);
1316
+		if ($checkin instanceof EE_Checkin) {
1317
+			if ($checkin->get('CHK_in')) {
1318
+				return EE_Registration::checkin_status_in; //checked in
1319
+			}
1320
+			return EE_Registration::checkin_status_out; //had checked in but is now checked out.
1321
+		}
1322
+		return EE_Registration::checkin_status_never; //never been checked in
1323
+	}
1324
+
1325
+
1326
+	/**
1327
+	 * This method returns a localized message for the toggled Check-in message.
1328
+	 *
1329
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1330
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1331
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1332
+	 *                     message can be customized with the attendee name.
1333
+	 * @return string         internationalized message
1334
+	 */
1335
+	public function get_checkin_msg($DTT_ID, $error = false)
1336
+	{
1337
+		//let's get the attendee first so we can include the name of the attendee
1338
+		$attendee = $this->get_first_related('Attendee');
1339
+		if ($attendee instanceof EE_Attendee) {
1340
+			if ($error) {
1341
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1342
+			}
1343
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1344
+			//what is the status message going to be?
1345
+			switch ($cur_status) {
1346
+				case EE_Registration::checkin_status_never :
1347
+					return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1348
+						$attendee->full_name());
1349
+					break;
1350
+				case EE_Registration::checkin_status_in :
1351
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1352
+					break;
1353
+				case EE_Registration::checkin_status_out :
1354
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1355
+					break;
1356
+			}
1357
+		}
1358
+		return __("The check-in status could not be determined.", "event_espresso");
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * Returns the related EE_Transaction to this registration
1364
+	 *
1365
+	 * @return EE_Transaction
1366
+	 */
1367
+	public function transaction()
1368
+	{
1369
+		$transaction = $this->get_first_related('Transaction');
1370
+		if (! $transaction instanceof \EE_Transaction) {
1371
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1372
+		}
1373
+		return $transaction;
1374
+	}
1375
+
1376
+
1377
+	/**
1378
+	 *        get Registration Code
1379
+	 */
1380
+	public function reg_code()
1381
+	{
1382
+		return $this->get('REG_code');
1383
+	}
1384
+
1385
+
1386
+	/**
1387
+	 *        get Transaction ID
1388
+	 */
1389
+	public function transaction_ID()
1390
+	{
1391
+		return $this->get('TXN_ID');
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * @return int
1397
+	 */
1398
+	public function ticket_ID()
1399
+	{
1400
+		return $this->get('TKT_ID');
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 *        Set Registration Code
1406
+	 *
1407
+	 * @access    public
1408
+	 * @param    string  $REG_code Registration Code
1409
+	 * @param    boolean $use_default
1410
+	 */
1411
+	public function set_reg_code($REG_code, $use_default = false)
1412
+	{
1413
+		if (empty($REG_code)) {
1414
+			EE_Error::add_error(__('REG_code can not be empty.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1415
+			return;
1416
+		}
1417
+		if (! $this->reg_code()) {
1418
+			parent::set('REG_code', $REG_code, $use_default);
1419
+		} else {
1420
+			EE_Error::doing_it_wrong(
1421
+				__CLASS__ . '::' . __FUNCTION__,
1422
+				__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1423
+				'4.6.0'
1424
+			);
1425
+		}
1426
+	}
1427
+
1428
+
1429
+	/**
1430
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1431
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1432
+	 *    $registration->transaction()->registrations();
1433
+	 *
1434
+	 * @since 4.5.0
1435
+	 * @return EE_Registration[]  or empty array if this isn't a group registration.
1436
+	 */
1437
+	public function get_all_other_registrations_in_group()
1438
+	{
1439
+		if ($this->group_size() < 2) {
1440
+			return array();
1441
+		}
1442
+
1443
+		$query[0] = array(
1444
+			'TXN_ID' => $this->transaction_ID(),
1445
+			'REG_ID' => array('!=', $this->ID()),
1446
+			'TKT_ID' => $this->ticket_ID(),
1447
+		);
1448
+
1449
+		$registrations = $this->get_model()->get_all($query);
1450
+		return $registrations;
1451
+	}
1452
+
1453
+	/**
1454
+	 * Return the link to the admin details for the object.
1455
+	 *
1456
+	 * @return string
1457
+	 */
1458
+	public function get_admin_details_link()
1459
+	{
1460
+		EE_Registry::instance()->load_helper('URL');
1461
+		return EEH_URL::add_query_args_and_nonce(
1462
+			array(
1463
+				'page'    => 'espresso_registrations',
1464
+				'action'  => 'view_registration',
1465
+				'_REG_ID' => $this->ID(),
1466
+			),
1467
+			admin_url('admin.php')
1468
+		);
1469
+	}
1470
+
1471
+	/**
1472
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1473
+	 *
1474
+	 * @return string
1475
+	 */
1476
+	public function get_admin_edit_link()
1477
+	{
1478
+		return $this->get_admin_details_link();
1479
+	}
1480
+
1481
+	/**
1482
+	 * Returns the link to a settings page for the object.
1483
+	 *
1484
+	 * @return string
1485
+	 */
1486
+	public function get_admin_settings_link()
1487
+	{
1488
+		return $this->get_admin_details_link();
1489
+	}
1490
+
1491
+	/**
1492
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1493
+	 *
1494
+	 * @return string
1495
+	 */
1496
+	public function get_admin_overview_link()
1497
+	{
1498
+		EE_Registry::instance()->load_helper('URL');
1499
+		return EEH_URL::add_query_args_and_nonce(
1500
+			array(
1501
+				'page' => 'espresso_registrations',
1502
+			),
1503
+			admin_url('admin.php')
1504
+		);
1505
+	}
1506
+
1507
+
1508
+	/**
1509
+	 * @param array $query_params
1510
+	 * @return \EE_Registration[]
1511
+	 * @throws \EE_Error
1512
+	 */
1513
+	public function payments($query_params = array())
1514
+	{
1515
+		return $this->get_many_related('Payment', $query_params);
1516
+	}
1517
+
1518
+
1519
+	/**
1520
+	 * @param array $query_params
1521
+	 * @return \EE_Registration_Payment[]
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function registration_payments($query_params = array())
1525
+	{
1526
+		return $this->get_many_related('Registration_Payment', $query_params);
1527
+	}
1528
+
1529
+
1530
+	/**
1531
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1532
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1533
+	 *
1534
+	 * @return EE_Payment_Method|null
1535
+	 */
1536
+	public function payment_method()
1537
+	{
1538
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1539
+	}
1540
+
1541
+
1542
+	/**
1543
+	 * @return \EE_Line_Item
1544
+	 * @throws EntityNotFoundException
1545
+	 * @throws \EE_Error
1546
+	 */
1547
+	public function ticket_line_item()
1548
+	{
1549
+		$ticket            = $this->ticket();
1550
+		$transaction       = $this->transaction();
1551
+		$line_item         = null;
1552
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1553
+			$transaction->total_line_item(),
1554
+			'Ticket',
1555
+			array($ticket->ID())
1556
+		);
1557
+		foreach ($ticket_line_items as $ticket_line_item) {
1558
+			if (
1559
+				$ticket_line_item instanceof \EE_Line_Item
1560
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1561
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1562
+			) {
1563
+				$line_item = $ticket_line_item;
1564
+				break;
1565
+			}
1566
+		}
1567
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1568
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1569
+		}
1570
+		return $line_item;
1571
+	}
1572
+
1573
+
1574
+	/**
1575
+	 * Soft Deletes this model object.
1576
+	 *
1577
+	 * @return boolean | int
1578
+	 * @throws \RuntimeException
1579
+	 * @throws \EE_Error
1580
+	 */
1581
+	public function delete()
1582
+	{
1583
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1584
+			$this->set_status(EEM_Registration::status_id_cancelled);
1585
+		}
1586
+		return parent::delete();
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1592
+	 *
1593
+	 * @throws \EE_Error
1594
+	 * @throws \RuntimeException
1595
+	 */
1596
+	public function restore()
1597
+	{
1598
+		$previous_status = $this->get_extra_meta(
1599
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1600
+			true,
1601
+			EEM_Registration::status_id_cancelled
1602
+		);
1603
+		if ($previous_status) {
1604
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1605
+			$this->set_status($previous_status);
1606
+		}
1607
+		return parent::restore();
1608
+	}
1609
+
1610
+
1611
+
1612
+	/*************************** DEPRECATED ***************************/
1613
+
1614
+
1615
+	/**
1616
+	 * @deprecated
1617
+	 * @since     4.7.0
1618
+	 * @access    public
1619
+	 */
1620
+	public function price_paid()
1621
+	{
1622
+		EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1623
+			__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1624
+			'4.7.0');
1625
+		return $this->final_price();
1626
+	}
1627
+
1628
+
1629
+	/**
1630
+	 * @deprecated
1631
+	 * @since     4.7.0
1632
+	 * @access    public
1633
+	 * @param    float $REG_final_price
1634
+	 */
1635
+	public function set_price_paid($REG_final_price = 0.00)
1636
+	{
1637
+		EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
1638
+			__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
1639
+			'4.7.0');
1640
+		$this->set_final_price($REG_final_price);
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * @deprecated
1646
+	 * @since 4.7.0
1647
+	 * @return string
1648
+	 */
1649
+	public function pretty_price_paid()
1650
+	{
1651
+		EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
1652
+			__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
1653
+				'event_espresso'), '4.7.0');
1654
+		return $this->pretty_final_price();
1655
+	}
1656
+
1657
+
1658
+	/**
1659
+	 * Gets the primary datetime related to this registration via the related Event to this registration
1660
+	 *
1661
+	 * @deprecated 4.9.17
1662
+	 * @return EE_Datetime
1663
+	 */
1664
+	public function get_related_primary_datetime()
1665
+	{
1666
+		EE_Error::doing_it_wrong(
1667
+			__METHOD__,
1668
+			esc_html__(
1669
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
1670
+				'event_espresso'
1671
+			),
1672
+			'4.9.17',
1673
+			'5.0.0'
1674
+		);
1675
+		return $this->event()->primary_datetime();
1676
+	}
1677 1677
 
1678 1678
 
1679 1679
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 1 patch
Indentation   +571 added lines, -571 removed lines patch added patch discarded remove patch
@@ -70,13 +70,13 @@  discard block
 block discarded – undo
70 70
 
71 71
 
72 72
 
73
-    /**
74
-     * return if a ticket has quantities available for purchase
75
-     *
76
-     * @param  int $DTT_ID the primary key for a particular datetime
77
-     * @return boolean
78
-     * @throws \EE_Error
79
-     */
73
+	/**
74
+	 * return if a ticket has quantities available for purchase
75
+	 *
76
+	 * @param  int $DTT_ID the primary key for a particular datetime
77
+	 * @return boolean
78
+	 * @throws \EE_Error
79
+	 */
80 80
 	public function available( $DTT_ID = 0 ) {
81 81
 		// are we checking availability for a particular datetime ?
82 82
 		if ( $DTT_ID ) {
@@ -93,14 +93,14 @@  discard block
 block discarded – undo
93 93
 
94 94
 
95 95
 
96
-    /**
97
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
98
-     *
99
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the relevant status const
100
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save further processing
101
-     * @return mixed status int if the display string isn't requested
102
-     * @throws \EE_Error
103
-     */
96
+	/**
97
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
98
+	 *
99
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the relevant status const
100
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save further processing
101
+	 * @return mixed status int if the display string isn't requested
102
+	 * @throws \EE_Error
103
+	 */
104 104
 	public function ticket_status( $display = FALSE, $remaining = null ) {
105 105
 		$remaining = is_bool( $remaining ) ? $remaining : $this->is_remaining();
106 106
 		if ( ! $remaining ) {
@@ -123,14 +123,14 @@  discard block
 block discarded – undo
123 123
 
124 124
 
125 125
 
126
-    /**
127
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale considering ALL the factors used for figuring that out.
128
-     *
129
-     * @access public
130
-     * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
131
-     * @return boolean         true = tickets remaining, false not.
132
-     * @throws \EE_Error
133
-     */
126
+	/**
127
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale considering ALL the factors used for figuring that out.
128
+	 *
129
+	 * @access public
130
+	 * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
131
+	 * @return boolean         true = tickets remaining, false not.
132
+	 * @throws \EE_Error
133
+	 */
134 134
 	public function is_remaining( $DTT_ID = 0 ) {
135 135
 		$num_remaining = $this->remaining( $DTT_ID );
136 136
 		if ( $num_remaining === 0 ) {
@@ -144,76 +144,76 @@  discard block
 block discarded – undo
144 144
 
145 145
 
146 146
 
147
-    /**
148
-     * return the total number of tickets available for purchase
149
-     *
150
-     * @param  int $DTT_ID the primary key for a particular datetime.
151
-     *                     set to 0 for all related datetimes
152
-     * @return int
153
-     * @throws \EE_Error
154
-     */
147
+	/**
148
+	 * return the total number of tickets available for purchase
149
+	 *
150
+	 * @param  int $DTT_ID the primary key for a particular datetime.
151
+	 *                     set to 0 for all related datetimes
152
+	 * @return int
153
+	 * @throws \EE_Error
154
+	 */
155 155
 	public function remaining( $DTT_ID = 0 ) {
156 156
 		return $this->real_quantity_on_ticket('saleable', $DTT_ID );
157 157
 	}
158 158
 
159 159
 
160 160
 
161
-    /**
162
-     * Gets min
163
-     *
164
-     * @return int
165
-     * @throws \EE_Error
166
-     */
161
+	/**
162
+	 * Gets min
163
+	 *
164
+	 * @return int
165
+	 * @throws \EE_Error
166
+	 */
167 167
 	public function min() {
168 168
 		return $this->get( 'TKT_min' );
169 169
 	}
170 170
 
171 171
 
172 172
 
173
-    /**
174
-     * return if a ticket is no longer available cause its available dates have expired.
175
-     *
176
-     * @return boolean
177
-     * @throws \EE_Error
178
-     */
173
+	/**
174
+	 * return if a ticket is no longer available cause its available dates have expired.
175
+	 *
176
+	 * @return boolean
177
+	 * @throws \EE_Error
178
+	 */
179 179
 	public function is_expired() {
180 180
 		return ( $this->get_raw( 'TKT_end_date' ) < time() );
181 181
 	}
182 182
 
183 183
 
184 184
 
185
-    /**
186
-     * Return if a ticket is yet to go on sale or not
187
-     *
188
-     * @return boolean
189
-     * @throws \EE_Error
190
-     */
185
+	/**
186
+	 * Return if a ticket is yet to go on sale or not
187
+	 *
188
+	 * @return boolean
189
+	 * @throws \EE_Error
190
+	 */
191 191
 	public function is_pending() {
192 192
 		return ( $this->get_raw( 'TKT_start_date' ) > time() );
193 193
 	}
194 194
 
195 195
 
196 196
 
197
-    /**
198
-     * Return if a ticket is on sale or not
199
-     *
200
-     * @return boolean
201
-     * @throws \EE_Error
202
-     */
197
+	/**
198
+	 * Return if a ticket is on sale or not
199
+	 *
200
+	 * @return boolean
201
+	 * @throws \EE_Error
202
+	 */
203 203
 	public function is_on_sale() {
204 204
 		return ( $this->get_raw( 'TKT_start_date' ) < time() && $this->get_raw( 'TKT_end_date' ) > time() );
205 205
 	}
206 206
 
207 207
 
208 208
 
209
-    /**
210
-     * This returns the chronologically last datetime that this ticket is associated with
211
-     *
212
-     * @param string $dt_frmt
213
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with the end date ie: Jan 01 "to" Dec 31
214
-     * @return string
215
-     * @throws \EE_Error
216
-     */
209
+	/**
210
+	 * This returns the chronologically last datetime that this ticket is associated with
211
+	 *
212
+	 * @param string $dt_frmt
213
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with the end date ie: Jan 01 "to" Dec 31
214
+	 * @return string
215
+	 * @throws \EE_Error
216
+	 */
217 217
 	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
218 218
 		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date( $dt_frmt ) : '';
219 219
 		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date( $dt_frmt ) : '';
@@ -223,12 +223,12 @@  discard block
 block discarded – undo
223 223
 
224 224
 
225 225
 
226
-    /**
227
-     * This returns the chronologically first datetime that this ticket is associated with
228
-     *
229
-     * @return EE_Datetime
230
-     * @throws \EE_Error
231
-     */
226
+	/**
227
+	 * This returns the chronologically first datetime that this ticket is associated with
228
+	 *
229
+	 * @return EE_Datetime
230
+	 * @throws \EE_Error
231
+	 */
232 232
 	public function first_datetime() {
233 233
 		$datetimes = $this->datetimes( array( 'limit' => 1 ) );
234 234
 		return reset( $datetimes );
@@ -236,14 +236,14 @@  discard block
 block discarded – undo
236 236
 
237 237
 
238 238
 
239
-    /**
240
-     * Gets all the datetimes this ticket can be used for attending.
241
-     * Unless otherwise specified, orders datetimes by start date.
242
-     *
243
-     * @param array $query_params see EEM_Base::get_all()
244
-     * @return EE_Datetime[]|EE_Base_Class[]
245
-     * @throws \EE_Error
246
-     */
239
+	/**
240
+	 * Gets all the datetimes this ticket can be used for attending.
241
+	 * Unless otherwise specified, orders datetimes by start date.
242
+	 *
243
+	 * @param array $query_params see EEM_Base::get_all()
244
+	 * @return EE_Datetime[]|EE_Base_Class[]
245
+	 * @throws \EE_Error
246
+	 */
247 247
 	public function datetimes( $query_params = array() ) {
248 248
 		if ( ! isset( $query_params[ 'order_by' ] ) ) {
249 249
 			$query_params[ 'order_by' ][ 'DTT_order' ] = 'ASC';
@@ -253,12 +253,12 @@  discard block
 block discarded – undo
253 253
 
254 254
 
255 255
 
256
-    /**
257
-     * This returns the chronologically last datetime that this ticket is associated with
258
-     *
259
-     * @return EE_Datetime
260
-     * @throws \EE_Error
261
-     */
256
+	/**
257
+	 * This returns the chronologically last datetime that this ticket is associated with
258
+	 *
259
+	 * @return EE_Datetime
260
+	 * @throws \EE_Error
261
+	 */
262 262
 	public function last_datetime() {
263 263
 		$datetimes = $this->datetimes( array( 'limit' => 1, 'order_by' => array( 'DTT_EVT_start' => 'DESC' ) ) );
264 264
 		return end( $datetimes );
@@ -266,19 +266,19 @@  discard block
 block discarded – undo
266 266
 
267 267
 
268 268
 
269
-    /**
270
-     * This returns the total tickets sold depending on the given parameters.
271
-     *
272
-     * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
273
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
274
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
275
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
276
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
277
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
278
-     * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
279
-     * @return mixed (array|int)          how many tickets have sold
280
-     * @throws \EE_Error
281
-     */
269
+	/**
270
+	 * This returns the total tickets sold depending on the given parameters.
271
+	 *
272
+	 * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
273
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
274
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
275
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
276
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
277
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
278
+	 * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
279
+	 * @return mixed (array|int)          how many tickets have sold
280
+	 * @throws \EE_Error
281
+	 */
282 282
 	public function tickets_sold( $what = 'ticket', $dtt_id = NULL ) {
283 283
 		$total = 0;
284 284
 		$tickets_sold = $this->_all_tickets_sold();
@@ -303,12 +303,12 @@  discard block
 block discarded – undo
303 303
 
304 304
 
305 305
 
306
-    /**
307
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
308
-     *
309
-     * @return EE_Ticket[]
310
-     * @throws \EE_Error
311
-     */
306
+	/**
307
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
308
+	 *
309
+	 * @return EE_Ticket[]
310
+	 * @throws \EE_Error
311
+	 */
312 312
 	protected function _all_tickets_sold() {
313 313
 		$datetimes = $this->get_many_related( 'Datetime' );
314 314
 		$tickets_sold = array();
@@ -324,29 +324,29 @@  discard block
 block discarded – undo
324 324
 
325 325
 
326 326
 
327
-    /**
328
-     * This returns the base price object for the ticket.
329
-     *
330
-     * @param  bool $return_array whether to return as an array indexed by price id or just the object.
331
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
332
-     * @throws \EE_Error
333
-     */
327
+	/**
328
+	 * This returns the base price object for the ticket.
329
+	 *
330
+	 * @param  bool $return_array whether to return as an array indexed by price id or just the object.
331
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
332
+	 * @throws \EE_Error
333
+	 */
334 334
 	public function base_price( $return_array = FALSE ) {
335 335
 		$_where = array( 'Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price );
336 336
 		return $return_array
337
-            ? $this->get_many_related( 'Price', array( $_where ) )
338
-            : $this->get_first_related( 'Price', array( $_where ) );
337
+			? $this->get_many_related( 'Price', array( $_where ) )
338
+			: $this->get_first_related( 'Price', array( $_where ) );
339 339
 	}
340 340
 
341 341
 
342 342
 
343
-    /**
344
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
345
-     *
346
-     * @access public
347
-     * @return EE_Price[]
348
-     * @throws \EE_Error
349
-     */
343
+	/**
344
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
345
+	 *
346
+	 * @access public
347
+	 * @return EE_Price[]
348
+	 * @throws \EE_Error
349
+	 */
350 350
 	public function price_modifiers() {
351 351
 		$query_params = array( 0 => array( 'Price_Type.PBT_ID' => array( 'NOT IN', array( EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax ) ) ) );
352 352
 		return $this->prices( $query_params );
@@ -354,132 +354,132 @@  discard block
 block discarded – undo
354 354
 
355 355
 
356 356
 
357
-    /**
358
-     * Gets all the prices that combine to form the final price of this ticket
359
-     *
360
-     * @param array $query_params like EEM_Base::get_all
361
-     * @return EE_Price[]|EE_Base_Class[]
362
-     * @throws \EE_Error
363
-     */
357
+	/**
358
+	 * Gets all the prices that combine to form the final price of this ticket
359
+	 *
360
+	 * @param array $query_params like EEM_Base::get_all
361
+	 * @return EE_Price[]|EE_Base_Class[]
362
+	 * @throws \EE_Error
363
+	 */
364 364
 	public function prices( $query_params = array() ) {
365 365
 		return $this->get_many_related( 'Price', $query_params );
366 366
 	}
367 367
 
368 368
 
369 369
 
370
-    /**
371
-     * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
372
-     *
373
-     * @param array $query_params see EEM_Base::get_all()
374
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
375
-     * @throws \EE_Error
376
-     */
370
+	/**
371
+	 * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
372
+	 *
373
+	 * @param array $query_params see EEM_Base::get_all()
374
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
375
+	 * @throws \EE_Error
376
+	 */
377 377
 	public function datetime_tickets( $query_params = array() ) {
378 378
 		return $this->get_many_related( 'Datetime_Ticket', $query_params );
379 379
 	}
380 380
 
381 381
 
382 382
 
383
-    /**
384
-     * Gets all the datetimes from the db ordered by DTT_order
385
-     *
386
-     * @param boolean $show_expired
387
-     * @param boolean $show_deleted
388
-     * @return EE_Datetime[]
389
-     * @throws \EE_Error
390
-     */
383
+	/**
384
+	 * Gets all the datetimes from the db ordered by DTT_order
385
+	 *
386
+	 * @param boolean $show_expired
387
+	 * @param boolean $show_deleted
388
+	 * @return EE_Datetime[]
389
+	 * @throws \EE_Error
390
+	 */
391 391
 	public function datetimes_ordered( $show_expired = TRUE, $show_deleted = FALSE ) {
392 392
 		return EEM_Datetime::instance( $this->_timezone )->get_datetimes_for_ticket_ordered_by_DTT_order( $this->ID(), $show_expired, $show_deleted );
393 393
 	}
394 394
 
395 395
 
396 396
 
397
-    /**
398
-     * Gets ID
399
-     *
400
-     * @return string
401
-     * @throws \EE_Error
402
-     */
397
+	/**
398
+	 * Gets ID
399
+	 *
400
+	 * @return string
401
+	 * @throws \EE_Error
402
+	 */
403 403
 	public function ID() {
404 404
 		return $this->get( 'TKT_ID' );
405 405
 	}
406 406
 
407 407
 
408 408
 
409
-    /**
410
-     * get the author of the ticket.
411
-     *
412
-     * @since 4.5.0
413
-     * @return int
414
-     * @throws \EE_Error
415
-     */
409
+	/**
410
+	 * get the author of the ticket.
411
+	 *
412
+	 * @since 4.5.0
413
+	 * @return int
414
+	 * @throws \EE_Error
415
+	 */
416 416
 	public function wp_user() {
417 417
 		return $this->get('TKT_wp_user');
418 418
 	}
419 419
 
420 420
 
421 421
 
422
-    /**
423
-     * Gets the template for the ticket
424
-     *
425
-     * @return EE_Ticket_Template|EE_Base_Class
426
-     * @throws \EE_Error
427
-     */
422
+	/**
423
+	 * Gets the template for the ticket
424
+	 *
425
+	 * @return EE_Ticket_Template|EE_Base_Class
426
+	 * @throws \EE_Error
427
+	 */
428 428
 	public function template() {
429 429
 		return $this->get_first_related( 'Ticket_Template' );
430 430
 	}
431 431
 
432 432
 
433 433
 
434
-    /**
435
-     * Simply returns an array of EE_Price objects that are taxes.
436
-     *
437
-     * @return EE_Price[]
438
-     * @throws \EE_Error
439
-     */
434
+	/**
435
+	 * Simply returns an array of EE_Price objects that are taxes.
436
+	 *
437
+	 * @return EE_Price[]
438
+	 * @throws \EE_Error
439
+	 */
440 440
 	public function get_ticket_taxes_for_admin() {
441 441
 		return EE_Taxes::get_taxes_for_admin();
442 442
 	}
443 443
 
444 444
 
445 445
 
446
-    /**
447
-     * @return float
448
-     * @throws \EE_Error
449
-     */
446
+	/**
447
+	 * @return float
448
+	 * @throws \EE_Error
449
+	 */
450 450
 	public function ticket_price() {
451 451
 		return $this->get( 'TKT_price' );
452 452
 	}
453 453
 
454 454
 
455 455
 
456
-    /**
457
-     * @return mixed
458
-     * @throws \EE_Error
459
-     */
456
+	/**
457
+	 * @return mixed
458
+	 * @throws \EE_Error
459
+	 */
460 460
 	public function pretty_price() {
461 461
 		return $this->get_pretty( 'TKT_price' );
462 462
 	}
463 463
 
464 464
 
465 465
 
466
-    /**
467
-     * @return bool
468
-     * @throws \EE_Error
469
-     */
466
+	/**
467
+	 * @return bool
468
+	 * @throws \EE_Error
469
+	 */
470 470
 	public function is_free() {
471 471
 		return $this->get_ticket_total_with_taxes() === (float) 0;
472 472
 	}
473 473
 
474 474
 
475 475
 
476
-    /**
477
-     * get_ticket_total_with_taxes
478
-     *
479
-     * @param bool $no_cache
480
-     * @return float
481
-     * @throws \EE_Error
482
-     */
476
+	/**
477
+	 * get_ticket_total_with_taxes
478
+	 *
479
+	 * @param bool $no_cache
480
+	 * @return float
481
+	 * @throws \EE_Error
482
+	 */
483 483
 	public function get_ticket_total_with_taxes( $no_cache = FALSE ) {
484 484
 		if ($this->_ticket_total_with_taxes === null || $no_cache ) {
485 485
 			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
@@ -496,201 +496,201 @@  discard block
 block discarded – undo
496 496
 
497 497
 
498 498
 
499
-    /**
500
-     * @return float
501
-     * @throws \EE_Error
502
-     */
499
+	/**
500
+	 * @return float
501
+	 * @throws \EE_Error
502
+	 */
503 503
 	public function get_ticket_subtotal() {
504 504
 		return EE_Taxes::get_subtotal_for_admin( $this );
505 505
 	}
506 506
 
507 507
 
508 508
 
509
-    /**
510
-     * Returns the total taxes applied to this ticket
511
-     *
512
-     * @return float
513
-     * @throws \EE_Error
514
-     */
509
+	/**
510
+	 * Returns the total taxes applied to this ticket
511
+	 *
512
+	 * @return float
513
+	 * @throws \EE_Error
514
+	 */
515 515
 	public function get_ticket_taxes_total_for_admin() {
516 516
 		return EE_Taxes::get_total_taxes_for_admin( $this );
517 517
 	}
518 518
 
519 519
 
520 520
 
521
-    /**
522
-     * Sets name
523
-     *
524
-     * @param string $name
525
-     * @throws \EE_Error
526
-     */
521
+	/**
522
+	 * Sets name
523
+	 *
524
+	 * @param string $name
525
+	 * @throws \EE_Error
526
+	 */
527 527
 	public function set_name( $name ) {
528 528
 		$this->set( 'TKT_name', $name );
529 529
 	}
530 530
 
531 531
 
532 532
 
533
-    /**
534
-     * Gets description
535
-     *
536
-     * @return string
537
-     * @throws \EE_Error
538
-     */
533
+	/**
534
+	 * Gets description
535
+	 *
536
+	 * @return string
537
+	 * @throws \EE_Error
538
+	 */
539 539
 	public function description() {
540 540
 		return $this->get( 'TKT_description' );
541 541
 	}
542 542
 
543 543
 
544 544
 
545
-    /**
546
-     * Sets description
547
-     *
548
-     * @param string $description
549
-     * @throws \EE_Error
550
-     */
545
+	/**
546
+	 * Sets description
547
+	 *
548
+	 * @param string $description
549
+	 * @throws \EE_Error
550
+	 */
551 551
 	public function set_description( $description ) {
552 552
 		$this->set( 'TKT_description', $description );
553 553
 	}
554 554
 
555 555
 
556 556
 
557
-    /**
558
-     * Gets start_date
559
-     *
560
-     * @param string $dt_frmt
561
-     * @param string $tm_frmt
562
-     * @return string
563
-     * @throws \EE_Error
564
-     */
557
+	/**
558
+	 * Gets start_date
559
+	 *
560
+	 * @param string $dt_frmt
561
+	 * @param string $tm_frmt
562
+	 * @return string
563
+	 * @throws \EE_Error
564
+	 */
565 565
 	public function start_date( $dt_frmt = '', $tm_frmt = '' ) {
566 566
 		return $this->_get_datetime( 'TKT_start_date', $dt_frmt, $tm_frmt );
567 567
 	}
568 568
 
569 569
 
570 570
 
571
-    /**
572
-     * Sets start_date
573
-     *
574
-     * @param string $start_date
575
-     * @return void
576
-     * @throws \EE_Error
577
-     */
571
+	/**
572
+	 * Sets start_date
573
+	 *
574
+	 * @param string $start_date
575
+	 * @return void
576
+	 * @throws \EE_Error
577
+	 */
578 578
 	public function set_start_date( $start_date ) {
579 579
 		$this->_set_date_time( 'B', $start_date, 'TKT_start_date' );
580 580
 	}
581 581
 
582 582
 
583 583
 
584
-    /**
585
-     * Gets end_date
586
-     *
587
-     * @param string $dt_frmt
588
-     * @param string $tm_frmt
589
-     * @return string
590
-     * @throws \EE_Error
591
-     */
584
+	/**
585
+	 * Gets end_date
586
+	 *
587
+	 * @param string $dt_frmt
588
+	 * @param string $tm_frmt
589
+	 * @return string
590
+	 * @throws \EE_Error
591
+	 */
592 592
 	public function end_date( $dt_frmt = '', $tm_frmt = '' ) {
593 593
 		return $this->_get_datetime( 'TKT_end_date', $dt_frmt, $tm_frmt );
594 594
 	}
595 595
 
596 596
 
597 597
 
598
-    /**
599
-     * Sets end_date
600
-     *
601
-     * @param string $end_date
602
-     * @return void
603
-     * @throws \EE_Error
604
-     */
598
+	/**
599
+	 * Sets end_date
600
+	 *
601
+	 * @param string $end_date
602
+	 * @return void
603
+	 * @throws \EE_Error
604
+	 */
605 605
 	public function set_end_date( $end_date ) {
606 606
 		$this->_set_date_time( 'B', $end_date, 'TKT_end_date' );
607 607
 	}
608 608
 
609 609
 
610 610
 
611
-    /**
612
-     * Sets sell until time
613
-     *
614
-     * @since 4.5.0
615
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
616
-     * @throws \EE_Error
617
-     */
611
+	/**
612
+	 * Sets sell until time
613
+	 *
614
+	 * @since 4.5.0
615
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
616
+	 * @throws \EE_Error
617
+	 */
618 618
 	public function set_end_time( $time ) {
619 619
 		$this->_set_time_for( $time, 'TKT_end_date' );
620 620
 	}
621 621
 
622 622
 
623 623
 
624
-    /**
625
-     * Sets min
626
-     *
627
-     * @param int $min
628
-     * @return void
629
-     * @throws \EE_Error
630
-     */
624
+	/**
625
+	 * Sets min
626
+	 *
627
+	 * @param int $min
628
+	 * @return void
629
+	 * @throws \EE_Error
630
+	 */
631 631
 	public function set_min( $min ) {
632 632
 		$this->set( 'TKT_min', $min );
633 633
 	}
634 634
 
635 635
 
636 636
 
637
-    /**
638
-     * Gets max
639
-     *
640
-     * @return int
641
-     * @throws \EE_Error
642
-     */
637
+	/**
638
+	 * Gets max
639
+	 *
640
+	 * @return int
641
+	 * @throws \EE_Error
642
+	 */
643 643
 	public function max() {
644 644
 		return $this->get( 'TKT_max' );
645 645
 	}
646 646
 
647 647
 
648 648
 
649
-    /**
650
-     * Sets max
651
-     *
652
-     * @param int $max
653
-     * @return void
654
-     * @throws \EE_Error
655
-     */
649
+	/**
650
+	 * Sets max
651
+	 *
652
+	 * @param int $max
653
+	 * @return void
654
+	 * @throws \EE_Error
655
+	 */
656 656
 	public function set_max( $max ) {
657 657
 		$this->set( 'TKT_max', $max );
658 658
 	}
659 659
 
660 660
 
661 661
 
662
-    /**
663
-     * Sets price
664
-     *
665
-     * @param float $price
666
-     * @return void
667
-     * @throws \EE_Error
668
-     */
662
+	/**
663
+	 * Sets price
664
+	 *
665
+	 * @param float $price
666
+	 * @return void
667
+	 * @throws \EE_Error
668
+	 */
669 669
 	public function set_price( $price ) {
670 670
 		$this->set( 'TKT_price', $price );
671 671
 	}
672 672
 
673 673
 
674 674
 
675
-    /**
676
-     * Gets sold
677
-     *
678
-     * @return int
679
-     * @throws \EE_Error
680
-     */
675
+	/**
676
+	 * Gets sold
677
+	 *
678
+	 * @return int
679
+	 * @throws \EE_Error
680
+	 */
681 681
 	public function sold() {
682 682
 		return $this->get_raw( 'TKT_sold' );
683 683
 	}
684 684
 
685 685
 
686 686
 
687
-    /**
688
-     * Sets sold
689
-     *
690
-     * @param int $sold
691
-     * @return void
692
-     * @throws \EE_Error
693
-     */
687
+	/**
688
+	 * Sets sold
689
+	 *
690
+	 * @param int $sold
691
+	 * @return void
692
+	 * @throws \EE_Error
693
+	 */
694 694
 	public function set_sold( $sold ) {
695 695
 		// sold can not go below zero
696 696
 		$sold = max( 0, $sold );
@@ -699,13 +699,13 @@  discard block
 block discarded – undo
699 699
 
700 700
 
701 701
 
702
-    /**
703
-     * increments sold by amount passed by $qty
704
-     *
705
-     * @param int $qty
706
-     * @return void
707
-     * @throws \EE_Error
708
-     */
702
+	/**
703
+	 * increments sold by amount passed by $qty
704
+	 *
705
+	 * @param int $qty
706
+	 * @return void
707
+	 * @throws \EE_Error
708
+	 */
709 709
 	public function increase_sold( $qty = 1 ) {
710 710
 		$sold = $this->sold() + $qty;
711 711
 		// remove ticket reservation, but don't adjust datetime reservations,  because that will happen
@@ -717,13 +717,13 @@  discard block
 block discarded – undo
717 717
 
718 718
 
719 719
 
720
-    /**
721
-     * Increases sold on related datetimes
722
-     *
723
-     * @param int $qty
724
-     * @return void
725
-     * @throws \EE_Error
726
-     */
720
+	/**
721
+	 * Increases sold on related datetimes
722
+	 *
723
+	 * @param int $qty
724
+	 * @return void
725
+	 * @throws \EE_Error
726
+	 */
727 727
 	protected function _increase_sold_for_datetimes( $qty = 1 ) {
728 728
 		$datetimes = $this->datetimes();
729 729
 		if ( is_array( $datetimes ) ) {
@@ -738,13 +738,13 @@  discard block
 block discarded – undo
738 738
 
739 739
 
740 740
 
741
-    /**
742
-     * decrements (subtracts) sold by amount passed by $qty
743
-     *
744
-     * @param int $qty
745
-     * @return void
746
-     * @throws \EE_Error
747
-     */
741
+	/**
742
+	 * decrements (subtracts) sold by amount passed by $qty
743
+	 *
744
+	 * @param int $qty
745
+	 * @return void
746
+	 * @throws \EE_Error
747
+	 */
748 748
 	public function decrease_sold( $qty = 1 ) {
749 749
 		$sold = $this->sold() - $qty;
750 750
 		$this->_decrease_sold_for_datetimes( $qty );
@@ -753,13 +753,13 @@  discard block
 block discarded – undo
753 753
 
754 754
 
755 755
 
756
-    /**
757
-     * Decreases sold on related datetimes
758
-     *
759
-     * @param int $qty
760
-     * @return void
761
-     * @throws \EE_Error
762
-     */
756
+	/**
757
+	 * Decreases sold on related datetimes
758
+	 *
759
+	 * @param int $qty
760
+	 * @return void
761
+	 * @throws \EE_Error
762
+	 */
763 763
 	protected function _decrease_sold_for_datetimes( $qty = 1 ) {
764 764
 		$datetimes = $this->datetimes();
765 765
 		if ( is_array( $datetimes ) ) {
@@ -774,25 +774,25 @@  discard block
 block discarded – undo
774 774
 
775 775
 
776 776
 
777
-    /**
778
-     * Gets qty of reserved tickets
779
-     *
780
-     * @return int
781
-     * @throws \EE_Error
782
-     */
777
+	/**
778
+	 * Gets qty of reserved tickets
779
+	 *
780
+	 * @return int
781
+	 * @throws \EE_Error
782
+	 */
783 783
 	public function reserved() {
784 784
 		return $this->get_raw( 'TKT_reserved' );
785 785
 	}
786 786
 
787 787
 
788 788
 
789
-    /**
790
-     * Sets reserved
791
-     *
792
-     * @param int $reserved
793
-     * @return void
794
-     * @throws \EE_Error
795
-     */
789
+	/**
790
+	 * Sets reserved
791
+	 *
792
+	 * @param int $reserved
793
+	 * @return void
794
+	 * @throws \EE_Error
795
+	 */
796 796
 	public function set_reserved( $reserved ) {
797 797
 		// reserved can not go below zero
798 798
 		$reserved = max( 0, (int) $reserved );
@@ -801,13 +801,13 @@  discard block
 block discarded – undo
801 801
 
802 802
 
803 803
 
804
-    /**
805
-     * increments reserved by amount passed by $qty
806
-     *
807
-     * @param int $qty
808
-     * @return void
809
-     * @throws \EE_Error
810
-     */
804
+	/**
805
+	 * increments reserved by amount passed by $qty
806
+	 *
807
+	 * @param int $qty
808
+	 * @return void
809
+	 * @throws \EE_Error
810
+	 */
811 811
 	public function increase_reserved( $qty = 1 ) {
812 812
 		$qty = absint( $qty );
813 813
 		$reserved = $this->reserved() + $qty;
@@ -817,13 +817,13 @@  discard block
 block discarded – undo
817 817
 
818 818
 
819 819
 
820
-    /**
821
-     * Increases sold on related datetimes
822
-     *
823
-     * @param int $qty
824
-     * @return void
825
-     * @throws \EE_Error
826
-     */
820
+	/**
821
+	 * Increases sold on related datetimes
822
+	 *
823
+	 * @param int $qty
824
+	 * @return void
825
+	 * @throws \EE_Error
826
+	 */
827 827
 	protected function _increase_reserved_for_datetimes( $qty = 1 ) {
828 828
 		$datetimes = $this->datetimes();
829 829
 		if ( is_array( $datetimes ) ) {
@@ -838,14 +838,14 @@  discard block
 block discarded – undo
838 838
 
839 839
 
840 840
 
841
-    /**
842
-     * decrements (subtracts) reserved by amount passed by $qty
843
-     *
844
-     * @param int  $qty
845
-     * @param bool $adjust_datetimes
846
-     * @return void
847
-     * @throws \EE_Error
848
-     */
841
+	/**
842
+	 * decrements (subtracts) reserved by amount passed by $qty
843
+	 *
844
+	 * @param int  $qty
845
+	 * @param bool $adjust_datetimes
846
+	 * @return void
847
+	 * @throws \EE_Error
848
+	 */
849 849
 	public function decrease_reserved( $qty = 1, $adjust_datetimes = true ) {
850 850
 		$reserved = $this->reserved() - absint( $qty );
851 851
 		if ( $adjust_datetimes ) {
@@ -856,13 +856,13 @@  discard block
 block discarded – undo
856 856
 
857 857
 
858 858
 
859
-    /**
860
-     * Increases sold on related datetimes
861
-     *
862
-     * @param int $qty
863
-     * @return void
864
-     * @throws \EE_Error
865
-     */
859
+	/**
860
+	 * Increases sold on related datetimes
861
+	 *
862
+	 * @param int $qty
863
+	 * @return void
864
+	 * @throws \EE_Error
865
+	 */
866 866
 	protected function _decrease_reserved_for_datetimes( $qty = 1 ) {
867 867
 		$datetimes = $this->datetimes();
868 868
 		if ( is_array( $datetimes ) ) {
@@ -877,18 +877,18 @@  discard block
 block discarded – undo
877 877
 
878 878
 
879 879
 
880
-    /**
881
-     * Gets ticket quantity
882
-     *
883
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
884
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
885
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
886
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
887
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
888
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
889
-     * @return int
890
-     * @throws \EE_Error
891
-     */
880
+	/**
881
+	 * Gets ticket quantity
882
+	 *
883
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
884
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
885
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
886
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
887
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
888
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
889
+	 * @return int
890
+	 * @throws \EE_Error
891
+	 */
892 892
 	public function qty( $context = '' ) {
893 893
 		switch ( $context ) {
894 894
 			case 'reg_limit' :
@@ -902,19 +902,19 @@  discard block
 block discarded – undo
902 902
 
903 903
 
904 904
 
905
-    /**
906
-     * Gets ticket quantity
907
-     *
908
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
909
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
910
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
911
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
912
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
913
-     * @param  int   $DTT_ID      the primary key for a particular datetime.
914
-     *                            set to 0 for all related datetimes
915
-     * @return int
916
-     * @throws \EE_Error
917
-     */
905
+	/**
906
+	 * Gets ticket quantity
907
+	 *
908
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
909
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
910
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
911
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
912
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
913
+	 * @param  int   $DTT_ID      the primary key for a particular datetime.
914
+	 *                            set to 0 for all related datetimes
915
+	 * @return int
916
+	 * @throws \EE_Error
917
+	 */
918 918
 	public function real_quantity_on_ticket( $context = 'reg_limit', $DTT_ID = 0 ) {
919 919
 		$raw = $this->get_raw( 'TKT_qty' );
920 920
 		// return immediately if it's zero
@@ -997,212 +997,212 @@  discard block
 block discarded – undo
997 997
 
998 998
 
999 999
 
1000
-    /**
1001
-     * Gets uses
1002
-     *
1003
-     * @return int
1004
-     * @throws \EE_Error
1005
-     */
1000
+	/**
1001
+	 * Gets uses
1002
+	 *
1003
+	 * @return int
1004
+	 * @throws \EE_Error
1005
+	 */
1006 1006
 	public function uses() {
1007 1007
 		return $this->get( 'TKT_uses' );
1008 1008
 	}
1009 1009
 
1010 1010
 
1011 1011
 
1012
-    /**
1013
-     * Sets uses
1014
-     *
1015
-     * @param int $uses
1016
-     * @return void
1017
-     * @throws \EE_Error
1018
-     */
1012
+	/**
1013
+	 * Sets uses
1014
+	 *
1015
+	 * @param int $uses
1016
+	 * @return void
1017
+	 * @throws \EE_Error
1018
+	 */
1019 1019
 	public function set_uses( $uses ) {
1020 1020
 		$this->set( 'TKT_uses', $uses );
1021 1021
 	}
1022 1022
 
1023 1023
 
1024 1024
 
1025
-    /**
1026
-     * returns whether ticket is required or not.
1027
-     *
1028
-     * @return boolean
1029
-     * @throws \EE_Error
1030
-     */
1025
+	/**
1026
+	 * returns whether ticket is required or not.
1027
+	 *
1028
+	 * @return boolean
1029
+	 * @throws \EE_Error
1030
+	 */
1031 1031
 	public function required() {
1032 1032
 		return $this->get( 'TKT_required' );
1033 1033
 	}
1034 1034
 
1035 1035
 
1036 1036
 
1037
-    /**
1038
-     * sets the TKT_required property
1039
-     *
1040
-     * @param boolean $required
1041
-     * @return void
1042
-     * @throws \EE_Error
1043
-     */
1037
+	/**
1038
+	 * sets the TKT_required property
1039
+	 *
1040
+	 * @param boolean $required
1041
+	 * @return void
1042
+	 * @throws \EE_Error
1043
+	 */
1044 1044
 	public function set_required( $required ) {
1045 1045
 		$this->set( 'TKT_required', $required );
1046 1046
 	}
1047 1047
 
1048 1048
 
1049 1049
 
1050
-    /**
1051
-     * Gets taxable
1052
-     *
1053
-     * @return boolean
1054
-     * @throws \EE_Error
1055
-     */
1050
+	/**
1051
+	 * Gets taxable
1052
+	 *
1053
+	 * @return boolean
1054
+	 * @throws \EE_Error
1055
+	 */
1056 1056
 	public function taxable() {
1057 1057
 		return $this->get( 'TKT_taxable' );
1058 1058
 	}
1059 1059
 
1060 1060
 
1061 1061
 
1062
-    /**
1063
-     * Sets taxable
1064
-     *
1065
-     * @param boolean $taxable
1066
-     * @return void
1067
-     * @throws \EE_Error
1068
-     */
1062
+	/**
1063
+	 * Sets taxable
1064
+	 *
1065
+	 * @param boolean $taxable
1066
+	 * @return void
1067
+	 * @throws \EE_Error
1068
+	 */
1069 1069
 	public function set_taxable( $taxable ) {
1070 1070
 		$this->set( 'TKT_taxable', $taxable );
1071 1071
 	}
1072 1072
 
1073 1073
 
1074 1074
 
1075
-    /**
1076
-     * Gets is_default
1077
-     *
1078
-     * @return boolean
1079
-     * @throws \EE_Error
1080
-     */
1075
+	/**
1076
+	 * Gets is_default
1077
+	 *
1078
+	 * @return boolean
1079
+	 * @throws \EE_Error
1080
+	 */
1081 1081
 	public function is_default() {
1082 1082
 		return $this->get( 'TKT_is_default' );
1083 1083
 	}
1084 1084
 
1085 1085
 
1086 1086
 
1087
-    /**
1088
-     * Sets is_default
1089
-     *
1090
-     * @param boolean $is_default
1091
-     * @return void
1092
-     * @throws \EE_Error
1093
-     */
1087
+	/**
1088
+	 * Sets is_default
1089
+	 *
1090
+	 * @param boolean $is_default
1091
+	 * @return void
1092
+	 * @throws \EE_Error
1093
+	 */
1094 1094
 	public function set_is_default( $is_default ) {
1095 1095
 		$this->set( 'TKT_is_default', $is_default );
1096 1096
 	}
1097 1097
 
1098 1098
 
1099 1099
 
1100
-    /**
1101
-     * Gets order
1102
-     *
1103
-     * @return int
1104
-     * @throws \EE_Error
1105
-     */
1100
+	/**
1101
+	 * Gets order
1102
+	 *
1103
+	 * @return int
1104
+	 * @throws \EE_Error
1105
+	 */
1106 1106
 	public function order() {
1107 1107
 		return $this->get( 'TKT_order' );
1108 1108
 	}
1109 1109
 
1110 1110
 
1111 1111
 
1112
-    /**
1113
-     * Sets order
1114
-     *
1115
-     * @param int $order
1116
-     * @return void
1117
-     * @throws \EE_Error
1118
-     */
1112
+	/**
1113
+	 * Sets order
1114
+	 *
1115
+	 * @param int $order
1116
+	 * @return void
1117
+	 * @throws \EE_Error
1118
+	 */
1119 1119
 	public function set_order( $order ) {
1120 1120
 		$this->set( 'TKT_order', $order );
1121 1121
 	}
1122 1122
 
1123 1123
 
1124 1124
 
1125
-    /**
1126
-     * Gets row
1127
-     *
1128
-     * @return int
1129
-     * @throws \EE_Error
1130
-     */
1125
+	/**
1126
+	 * Gets row
1127
+	 *
1128
+	 * @return int
1129
+	 * @throws \EE_Error
1130
+	 */
1131 1131
 	public function row() {
1132 1132
 		return $this->get( 'TKT_row' );
1133 1133
 	}
1134 1134
 
1135 1135
 
1136 1136
 
1137
-    /**
1138
-     * Sets row
1139
-     *
1140
-     * @param int $row
1141
-     * @return void
1142
-     * @throws \EE_Error
1143
-     */
1137
+	/**
1138
+	 * Sets row
1139
+	 *
1140
+	 * @param int $row
1141
+	 * @return void
1142
+	 * @throws \EE_Error
1143
+	 */
1144 1144
 	public function set_row( $row ) {
1145 1145
 		$this->set( 'TKT_row', $row );
1146 1146
 	}
1147 1147
 
1148 1148
 
1149 1149
 
1150
-    /**
1151
-     * Gets deleted
1152
-     *
1153
-     * @return boolean
1154
-     * @throws \EE_Error
1155
-     */
1150
+	/**
1151
+	 * Gets deleted
1152
+	 *
1153
+	 * @return boolean
1154
+	 * @throws \EE_Error
1155
+	 */
1156 1156
 	public function deleted() {
1157 1157
 		return $this->get( 'TKT_deleted' );
1158 1158
 	}
1159 1159
 
1160 1160
 
1161 1161
 
1162
-    /**
1163
-     * Sets deleted
1164
-     *
1165
-     * @param boolean $deleted
1166
-     * @return void
1167
-     * @throws \EE_Error
1168
-     */
1162
+	/**
1163
+	 * Sets deleted
1164
+	 *
1165
+	 * @param boolean $deleted
1166
+	 * @return void
1167
+	 * @throws \EE_Error
1168
+	 */
1169 1169
 	public function set_deleted( $deleted ) {
1170 1170
 		$this->set( 'TKT_deleted', $deleted );
1171 1171
 	}
1172 1172
 
1173 1173
 
1174 1174
 
1175
-    /**
1176
-     * Gets parent
1177
-     *
1178
-     * @return int
1179
-     * @throws \EE_Error
1180
-     */
1175
+	/**
1176
+	 * Gets parent
1177
+	 *
1178
+	 * @return int
1179
+	 * @throws \EE_Error
1180
+	 */
1181 1181
 	public function parent_ID() {
1182 1182
 		return $this->get( 'TKT_parent' );
1183 1183
 	}
1184 1184
 
1185 1185
 
1186 1186
 
1187
-    /**
1188
-     * Sets parent
1189
-     *
1190
-     * @param int $parent
1191
-     * @return void
1192
-     * @throws \EE_Error
1193
-     */
1187
+	/**
1188
+	 * Sets parent
1189
+	 *
1190
+	 * @param int $parent
1191
+	 * @return void
1192
+	 * @throws \EE_Error
1193
+	 */
1194 1194
 	public function set_parent_ID( $parent ) {
1195 1195
 		$this->set( 'TKT_parent', $parent );
1196 1196
 	}
1197 1197
 
1198 1198
 
1199 1199
 
1200
-    /**
1201
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1202
-     *
1203
-     * @return string
1204
-     * @throws \EE_Error
1205
-     */
1200
+	/**
1201
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1202
+	 *
1203
+	 * @return string
1204
+	 * @throws \EE_Error
1205
+	 */
1206 1206
 	public function name_and_info() {
1207 1207
 		$times = array();
1208 1208
 		foreach ( $this->datetimes() as $datetime ) {
@@ -1213,67 +1213,67 @@  discard block
 block discarded – undo
1213 1213
 
1214 1214
 
1215 1215
 
1216
-    /**
1217
-     * Gets name
1218
-     *
1219
-     * @return string
1220
-     * @throws \EE_Error
1221
-     */
1216
+	/**
1217
+	 * Gets name
1218
+	 *
1219
+	 * @return string
1220
+	 * @throws \EE_Error
1221
+	 */
1222 1222
 	public function name() {
1223 1223
 		return $this->get( 'TKT_name' );
1224 1224
 	}
1225 1225
 
1226 1226
 
1227 1227
 
1228
-    /**
1229
-     * Gets price
1230
-     *
1231
-     * @return float
1232
-     * @throws \EE_Error
1233
-     */
1228
+	/**
1229
+	 * Gets price
1230
+	 *
1231
+	 * @return float
1232
+	 * @throws \EE_Error
1233
+	 */
1234 1234
 	public function price() {
1235 1235
 		return $this->get( 'TKT_price' );
1236 1236
 	}
1237 1237
 
1238 1238
 
1239 1239
 
1240
-    /**
1241
-     * Gets all the registrations for this ticket
1242
-     *
1243
-     * @param array $query_params like EEM_Base::get_all's
1244
-     * @return EE_Registration[]|EE_Base_Class[]
1245
-     * @throws \EE_Error
1246
-     */
1240
+	/**
1241
+	 * Gets all the registrations for this ticket
1242
+	 *
1243
+	 * @param array $query_params like EEM_Base::get_all's
1244
+	 * @return EE_Registration[]|EE_Base_Class[]
1245
+	 * @throws \EE_Error
1246
+	 */
1247 1247
 	public function registrations( $query_params = array() ) {
1248 1248
 		return $this->get_many_related( 'Registration', $query_params );
1249 1249
 	}
1250 1250
 
1251 1251
 
1252 1252
 
1253
-    /**
1254
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1255
-     * into account
1256
-     *
1257
-     * @return int
1258
-     * @throws \EE_Error
1259
-     */
1253
+	/**
1254
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1255
+	 * into account
1256
+	 *
1257
+	 * @return int
1258
+	 * @throws \EE_Error
1259
+	 */
1260 1260
 	public function update_tickets_sold() {
1261
-        $count_regs_for_this_ticket = $this->count_registrations(
1262
-            array(
1263
-                array(
1264
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1265
-                    'REG_deleted' => 0,
1266
-                ),
1267
-            )
1268
-        );
1269
-        $sold = $this->sold();
1270
-        if ($count_regs_for_this_ticket > $sold) {
1271
-            $this->increase_sold($count_regs_for_this_ticket - $sold);
1272
-            $this->save();
1273
-        } else if ($count_regs_for_this_ticket < $sold) {
1274
-            $this->decrease_sold($count_regs_for_this_ticket - $sold);
1275
-            $this->save();
1276
-        }
1261
+		$count_regs_for_this_ticket = $this->count_registrations(
1262
+			array(
1263
+				array(
1264
+					'STS_ID'      => EEM_Registration::status_id_approved,
1265
+					'REG_deleted' => 0,
1266
+				),
1267
+			)
1268
+		);
1269
+		$sold = $this->sold();
1270
+		if ($count_regs_for_this_ticket > $sold) {
1271
+			$this->increase_sold($count_regs_for_this_ticket - $sold);
1272
+			$this->save();
1273
+		} else if ($count_regs_for_this_ticket < $sold) {
1274
+			$this->decrease_sold($count_regs_for_this_ticket - $sold);
1275
+			$this->save();
1276
+		}
1277 1277
 		return $count_regs_for_this_ticket;
1278 1278
 	}
1279 1279
 
@@ -1301,21 +1301,21 @@  discard block
 block discarded – undo
1301 1301
 
1302 1302
 
1303 1303
 
1304
-    /**
1305
-     * Implementation of the EEI_Event_Relation interface method
1306
-     *
1307
-     * @see EEI_Event_Relation for comments
1308
-     * @return EE_Event
1309
-     * @throws \EE_Error
1310
-     * @throws UnexpectedEntityException
1311
-     */
1304
+	/**
1305
+	 * Implementation of the EEI_Event_Relation interface method
1306
+	 *
1307
+	 * @see EEI_Event_Relation for comments
1308
+	 * @return EE_Event
1309
+	 * @throws \EE_Error
1310
+	 * @throws UnexpectedEntityException
1311
+	 */
1312 1312
 	public function get_related_event() {
1313 1313
 		//get one datetime to use for getting the event
1314 1314
 		$datetime = $this->first_datetime();
1315 1315
 		if ( ! $datetime instanceof \EE_Datetime ) {
1316 1316
 			throw new UnexpectedEntityException(
1317 1317
 				$datetime,
1318
-                'EE_Datetime',
1318
+				'EE_Datetime',
1319 1319
 				sprintf(
1320 1320
 					__( 'The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1321 1321
 					$this->name()
@@ -1326,7 +1326,7 @@  discard block
 block discarded – undo
1326 1326
 		if ( ! $event instanceof \EE_Event ) {
1327 1327
 			throw new UnexpectedEntityException(
1328 1328
 				$event,
1329
-                'EE_Event',
1329
+				'EE_Event',
1330 1330
 				sprintf(
1331 1331
 					__( 'The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1332 1332
 					$this->name()
@@ -1338,14 +1338,14 @@  discard block
 block discarded – undo
1338 1338
 
1339 1339
 
1340 1340
 
1341
-    /**
1342
-     * Implementation of the EEI_Event_Relation interface method
1343
-     *
1344
-     * @see EEI_Event_Relation for comments
1345
-     * @return string
1346
-     * @throws UnexpectedEntityException
1347
-     * @throws \EE_Error
1348
-     */
1341
+	/**
1342
+	 * Implementation of the EEI_Event_Relation interface method
1343
+	 *
1344
+	 * @see EEI_Event_Relation for comments
1345
+	 * @return string
1346
+	 * @throws UnexpectedEntityException
1347
+	 * @throws \EE_Error
1348
+	 */
1349 1349
 	public function get_event_name() {
1350 1350
 		$event = $this->get_related_event();
1351 1351
 		return $event instanceof EE_Event ? $event->name() : '';
@@ -1353,28 +1353,28 @@  discard block
 block discarded – undo
1353 1353
 
1354 1354
 
1355 1355
 
1356
-    /**
1357
-     * Implementation of the EEI_Event_Relation interface method
1358
-     *
1359
-     * @see EEI_Event_Relation for comments
1360
-     * @return int
1361
-     * @throws UnexpectedEntityException
1362
-     * @throws \EE_Error
1363
-     */
1356
+	/**
1357
+	 * Implementation of the EEI_Event_Relation interface method
1358
+	 *
1359
+	 * @see EEI_Event_Relation for comments
1360
+	 * @return int
1361
+	 * @throws UnexpectedEntityException
1362
+	 * @throws \EE_Error
1363
+	 */
1364 1364
 	public function get_event_ID() {
1365 1365
 		$event = $this->get_related_event();
1366 1366
 		return $event instanceof EE_Event ? $event->ID() : 0;
1367 1367
 	}
1368 1368
 
1369 1369
 
1370
-    /**
1371
-     * This simply returns whether a ticket can be permanently deleted or not.
1372
-     * The criteria for determining this is whether the ticket has any related registrations.
1373
-     * If there are none then it can be permanently deleted.
1374
-     *
1375
-     * @return bool
1376
-     */
1370
+	/**
1371
+	 * This simply returns whether a ticket can be permanently deleted or not.
1372
+	 * The criteria for determining this is whether the ticket has any related registrations.
1373
+	 * If there are none then it can be permanently deleted.
1374
+	 *
1375
+	 * @return bool
1376
+	 */
1377 1377
 	public function is_permanently_deleteable() {
1378
-	    return $this->count_registrations() === 0;
1379
-    }
1378
+		return $this->count_registrations() === 0;
1379
+	}
1380 1380
 } //end EE_Ticket class
Please login to merge, or discard this patch.