Completed
Branch decaf-fixes/sanitize-all-reque... (b7fe86)
by
unknown
06:39 queued 04:47
created
core/services/privacy/policy/PrivacyPolicyManager.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -26,71 +26,71 @@
 block discarded – undo
26 26
 class PrivacyPolicyManager
27 27
 {
28 28
 
29
-    public function __construct()
30
-    {
31
-        add_action('current_screen', array($this, 'addPrivacyPolicy'), 9);
32
-    }
29
+	public function __construct()
30
+	{
31
+		add_action('current_screen', array($this, 'addPrivacyPolicy'), 9);
32
+	}
33 33
 
34 34
 
35
-    /**
36
-     * For all the registered `PrivacyPolicyInterface`s, add their privacy policy content
37
-     *
38
-     * @param WP_Screen $screen
39
-     * @throws InvalidClassException
40
-     * @throws InvalidDataTypeException
41
-     * @throws InvalidEntityException
42
-     * @throws InvalidFilePathException
43
-     * @throws InvalidIdentifierException
44
-     * @throws InvalidInterfaceException
45
-     */
46
-    public function addPrivacyPolicy(WP_Screen $screen)
47
-    {
48
-        /** @var RequestInterface $request */
49
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
35
+	/**
36
+	 * For all the registered `PrivacyPolicyInterface`s, add their privacy policy content
37
+	 *
38
+	 * @param WP_Screen $screen
39
+	 * @throws InvalidClassException
40
+	 * @throws InvalidDataTypeException
41
+	 * @throws InvalidEntityException
42
+	 * @throws InvalidFilePathException
43
+	 * @throws InvalidIdentifierException
44
+	 * @throws InvalidInterfaceException
45
+	 */
46
+	public function addPrivacyPolicy(WP_Screen $screen)
47
+	{
48
+		/** @var RequestInterface $request */
49
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
50 50
 
51
-        if ($screen->id === 'tools' && $request->requestParamIsSet('wp-privacy-policy-guide')) {
52
-            // load all the privacy policy stuff
53
-            // add post policy text
54
-            foreach ($this->loadPrivacyPolicyCollection() as $privacy_policy) {
55
-                wp_add_privacy_policy_content($privacy_policy->getName(), $privacy_policy->getContent());
56
-            }
57
-        }
58
-    }
51
+		if ($screen->id === 'tools' && $request->requestParamIsSet('wp-privacy-policy-guide')) {
52
+			// load all the privacy policy stuff
53
+			// add post policy text
54
+			foreach ($this->loadPrivacyPolicyCollection() as $privacy_policy) {
55
+				wp_add_privacy_policy_content($privacy_policy->getName(), $privacy_policy->getContent());
56
+			}
57
+		}
58
+	}
59 59
 
60 60
 
61
-    /**
62
-     * @return CollectionInterface|PrivacyPolicyInterface[]
63
-     * @throws InvalidIdentifierException
64
-     * @throws InvalidInterfaceException
65
-     * @throws InvalidFilePathException
66
-     * @throws InvalidEntityException
67
-     * @throws InvalidDataTypeException
68
-     * @throws InvalidClassException
69
-     */
70
-    protected function loadPrivacyPolicyCollection()
71
-    {
72
-        $loader = new CollectionLoader(
73
-            new CollectionDetails(
74
-                // collection name
75
-                'privacy_policies',
76
-                // collection interface
77
-                'EventEspresso\core\services\privacy\policy\PrivacyPolicyInterface',
78
-                // FQCNs for classes to add (all classes within that namespace will be loaded)
79
-                apply_filters(
80
-                    'FHEE__EventEspresso_core_services_privacy_policy_PrivacyPolicyManager__privacy_policies',
81
-                    array('EventEspresso\core\domain\services\admin\privacy\policy\PrivacyPolicy')
82
-                ),
83
-                // filepaths to classes to add
84
-                array(),
85
-                // file mask to use if parsing folder for files to add
86
-                '',
87
-                // what to use as identifier for collection entities
88
-                // using CLASS NAME prevents duplicates (works like a singleton)
89
-                CollectionDetails::ID_CLASS_NAME
90
-            )
91
-        );
92
-        return $loader->getCollection();
93
-    }
61
+	/**
62
+	 * @return CollectionInterface|PrivacyPolicyInterface[]
63
+	 * @throws InvalidIdentifierException
64
+	 * @throws InvalidInterfaceException
65
+	 * @throws InvalidFilePathException
66
+	 * @throws InvalidEntityException
67
+	 * @throws InvalidDataTypeException
68
+	 * @throws InvalidClassException
69
+	 */
70
+	protected function loadPrivacyPolicyCollection()
71
+	{
72
+		$loader = new CollectionLoader(
73
+			new CollectionDetails(
74
+				// collection name
75
+				'privacy_policies',
76
+				// collection interface
77
+				'EventEspresso\core\services\privacy\policy\PrivacyPolicyInterface',
78
+				// FQCNs for classes to add (all classes within that namespace will be loaded)
79
+				apply_filters(
80
+					'FHEE__EventEspresso_core_services_privacy_policy_PrivacyPolicyManager__privacy_policies',
81
+					array('EventEspresso\core\domain\services\admin\privacy\policy\PrivacyPolicy')
82
+				),
83
+				// filepaths to classes to add
84
+				array(),
85
+				// file mask to use if parsing folder for files to add
86
+				'',
87
+				// what to use as identifier for collection entities
88
+				// using CLASS NAME prevents duplicates (works like a singleton)
89
+				CollectionDetails::ID_CLASS_NAME
90
+			)
91
+		);
92
+		return $loader->getCollection();
93
+	}
94 94
 }
95 95
 // End of file PrivacyPolicyManager.php
96 96
 // Location: EventEspresso\core\domain\services\admin/PrivacyPolicyManager.php
Please login to merge, or discard this patch.
core/services/bootstrap/BootstrapRequestResponseObjects.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -29,84 +29,84 @@
 block discarded – undo
29 29
 class BootstrapRequestResponseObjects
30 30
 {
31 31
 
32
-    /**
33
-     * @type LegacyRequestInterface $legacy_request
34
-     */
35
-    protected $legacy_request;
32
+	/**
33
+	 * @type LegacyRequestInterface $legacy_request
34
+	 */
35
+	protected $legacy_request;
36 36
 
37
-    /**
38
-     * @type LoaderInterface $loader
39
-     */
40
-    protected $loader;
37
+	/**
38
+	 * @type LoaderInterface $loader
39
+	 */
40
+	protected $loader;
41 41
 
42
-    /**
43
-     * @var RequestInterface $request
44
-     */
45
-    protected $request;
42
+	/**
43
+	 * @var RequestInterface $request
44
+	 */
45
+	protected $request;
46 46
 
47
-    /**
48
-     * @var ResponseInterface $response
49
-     */
50
-    protected $response;
47
+	/**
48
+	 * @var ResponseInterface $response
49
+	 */
50
+	protected $response;
51 51
 
52 52
 
53
-    /**
54
-     * BootstrapRequestResponseObjects constructor.
55
-     *
56
-     * @param LoaderInterface $loader
57
-     */
58
-    public function __construct(LoaderInterface $loader)
59
-    {
60
-        $this->loader = $loader;
61
-    }
53
+	/**
54
+	 * BootstrapRequestResponseObjects constructor.
55
+	 *
56
+	 * @param LoaderInterface $loader
57
+	 */
58
+	public function __construct(LoaderInterface $loader)
59
+	{
60
+		$this->loader = $loader;
61
+	}
62 62
 
63 63
 
64
-    /**
65
-     * @return void
66
-     */
67
-    public function buildRequestResponse()
68
-    {
69
-        $request_params = new RequestParams(new RequestSanitizer());
70
-        $server_params = new ServerParams(new ServerSanitizer());
71
-        // load our Request and Response objects
72
-        $this->request = new Request($request_params, $server_params);
73
-        $this->response = new Response();
74
-        $this->loader->share(RequestParams::class, $request_params);
75
-        $this->loader->share(ServerParams::class, $server_params);
76
-    }
64
+	/**
65
+	 * @return void
66
+	 */
67
+	public function buildRequestResponse()
68
+	{
69
+		$request_params = new RequestParams(new RequestSanitizer());
70
+		$server_params = new ServerParams(new ServerSanitizer());
71
+		// load our Request and Response objects
72
+		$this->request = new Request($request_params, $server_params);
73
+		$this->response = new Response();
74
+		$this->loader->share(RequestParams::class, $request_params);
75
+		$this->loader->share(ServerParams::class, $server_params);
76
+	}
77 77
 
78 78
 
79
-    /**
80
-     * @return void
81
-     * @throws InvalidArgumentException
82
-     */
83
-    public function shareRequestResponse()
84
-    {
85
-        $this->loader->share('EventEspresso\core\services\request\Request', $this->request);
86
-        $this->loader->share('EventEspresso\core\services\request\Response', $this->response);
87
-        EE_Dependency_Map::instance()->setRequest($this->request);
88
-        EE_Dependency_Map::instance()->setResponse($this->response);
89
-    }
79
+	/**
80
+	 * @return void
81
+	 * @throws InvalidArgumentException
82
+	 */
83
+	public function shareRequestResponse()
84
+	{
85
+		$this->loader->share('EventEspresso\core\services\request\Request', $this->request);
86
+		$this->loader->share('EventEspresso\core\services\request\Response', $this->response);
87
+		EE_Dependency_Map::instance()->setRequest($this->request);
88
+		EE_Dependency_Map::instance()->setResponse($this->response);
89
+	}
90 90
 
91 91
 
92
-    /**
93
-     * @return void
94
-     * @throws InvalidArgumentException
95
-     * @throws EE_Error
96
-     */
97
-    public function setupLegacyRequest()
98
-    {
99
-        espresso_load_required(
100
-            'EE_Request',
101
-            EE_CORE . 'request_stack/EE_Request.core.php'
102
-        );
103
-        $this->legacy_request = new EE_Request($_GET, $_POST, $_COOKIE, $_SERVER);
104
-        $this->legacy_request->setRequest($this->request);
105
-        $this->legacy_request->admin = $this->request->isAdmin();
106
-        $this->legacy_request->ajax = $this->request->isAjax();
107
-        $this->legacy_request->front_ajax = $this->request->isFrontAjax();
108
-        EE_Dependency_Map::instance()->setLegacyRequest($this->legacy_request);
109
-        $this->loader->share('EE_Request', $this->legacy_request);
110
-        $this->loader->share('EventEspresso\core\services\request\LegacyRequestInterface', $this->legacy_request);
111
-    }
92
+	/**
93
+	 * @return void
94
+	 * @throws InvalidArgumentException
95
+	 * @throws EE_Error
96
+	 */
97
+	public function setupLegacyRequest()
98
+	{
99
+		espresso_load_required(
100
+			'EE_Request',
101
+			EE_CORE . 'request_stack/EE_Request.core.php'
102
+		);
103
+		$this->legacy_request = new EE_Request($_GET, $_POST, $_COOKIE, $_SERVER);
104
+		$this->legacy_request->setRequest($this->request);
105
+		$this->legacy_request->admin = $this->request->isAdmin();
106
+		$this->legacy_request->ajax = $this->request->isAjax();
107
+		$this->legacy_request->front_ajax = $this->request->isFrontAjax();
108
+		EE_Dependency_Map::instance()->setLegacyRequest($this->legacy_request);
109
+		$this->loader->share('EE_Request', $this->legacy_request);
110
+		$this->loader->share('EventEspresso\core\services\request\LegacyRequestInterface', $this->legacy_request);
111
+	}
112 112
 }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Addon.lib.php 2 patches
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -23,1240 +23,1240 @@
 block discarded – undo
23 23
 class EE_Register_Addon implements EEI_Plugin_API
24 24
 {
25 25
 
26
-    /**
27
-     * possibly truncated version of the EE core version string
28
-     *
29
-     * @var string
30
-     */
31
-    protected static $_core_version = '';
32
-
33
-    /**
34
-     * Holds values for registered addons
35
-     *
36
-     * @var array
37
-     */
38
-    protected static $_settings = array();
39
-
40
-    /**
41
-     * @var  array $_incompatible_addons keys are addon SLUGS
42
-     * (first argument passed to EE_Register_Addon::register()), keys are
43
-     * their MINIMUM VERSION (with all 5 parts. Eg 1.2.3.rc.004).
44
-     * Generally this should be used sparingly, as we don't want to muddle up
45
-     * EE core with knowledge of ALL the addons out there.
46
-     * If you want NO versions of an addon to run with a certain version of core,
47
-     * it's usually best to define the addon's "min_core_version" as part of its call
48
-     * to EE_Register_Addon::register(), rather than using this array with a super high value for its
49
-     * minimum plugin version.
50
-     * @access    protected
51
-     */
52
-    protected static $_incompatible_addons = array(
53
-        'Multi_Event_Registration' => '2.0.11.rc.002',
54
-        'Promotions'               => '1.0.0.rc.084',
55
-    );
56
-
57
-
58
-    /**
59
-     * We should always be comparing core to a version like '4.3.0.rc.000',
60
-     * not just '4.3.0'.
61
-     * So if the addon developer doesn't provide that full version string,
62
-     * fill in the blanks for them
63
-     *
64
-     * @param string $min_core_version
65
-     * @return string always like '4.3.0.rc.000'
66
-     */
67
-    protected static function _effective_version($min_core_version)
68
-    {
69
-        // versions: 4 . 3 . 1 . p . 123
70
-        // offsets:    0 . 1 . 2 . 3 . 4
71
-        $version_parts = explode('.', $min_core_version);
72
-        // check they specified the micro version (after 2nd period)
73
-        if (! isset($version_parts[2])) {
74
-            $version_parts[2] = '0';
75
-        }
76
-        // if they didn't specify the 'p', or 'rc' part. Just assume the lowest possible
77
-        // soon we can assume that's 'rc', but this current version is 'alpha'
78
-        if (! isset($version_parts[3])) {
79
-            $version_parts[3] = 'dev';
80
-        }
81
-        if (! isset($version_parts[4])) {
82
-            $version_parts[4] = '000';
83
-        }
84
-        return implode('.', $version_parts);
85
-    }
86
-
87
-
88
-    /**
89
-     * Returns whether or not the min core version requirement of the addon is met
90
-     *
91
-     * @param string $min_core_version    the minimum core version required by the addon
92
-     * @param string $actual_core_version the actual core version, optional
93
-     * @return boolean
94
-     */
95
-    public static function _meets_min_core_version_requirement(
96
-        $min_core_version,
97
-        $actual_core_version = EVENT_ESPRESSO_VERSION
98
-    ) {
99
-        return version_compare(
100
-            self::_effective_version($actual_core_version),
101
-            self::_effective_version($min_core_version),
102
-            '>='
103
-        );
104
-    }
105
-
106
-
107
-    /**
108
-     * Method for registering new EE_Addons.
109
-     * Should be called AFTER AHEE__EE_System__load_espresso_addons but BEFORE
110
-     * AHEE__EE_System___detect_if_activation_or_upgrade__begin in order to register all its components. However, it
111
-     * may also be called after the 'activate_plugin' action (when an addon is activated), because an activating addon
112
-     * won't be loaded by WP until after AHEE__EE_System__load_espresso_addons has fired. If its called after
113
-     * 'activate_plugin', it registers the addon still, but its components are not registered
114
-     * (they shouldn't be needed anyways, because it's just an activation request and they won't have a chance to do
115
-     * anything anyways). Instead, it just sets the newly-activated addon's activation indicator wp option and returns
116
-     * (so that we can detect that the addon has activated on the subsequent request)
117
-     *
118
-     * @since    4.3.0
119
-     * @param string                  $addon_name                       [Required] the EE_Addon's name.
120
-     * @param  array                  $setup_args                       {
121
-     *                                                                  An array of arguments provided for registering
122
-     *                                                                  the message type.
123
-     * @type  string                  $class_name                       the addon's main file name.
124
-     *                                                                  If left blank, generated from the addon name,
125
-     *                                                                  changes something like "calendar" to
126
-     *                                                                  "EE_Calendar"
127
-     * @type string                   $min_core_version                 the minimum version of EE Core that the
128
-     *                                                                  addon will work with. eg "4.8.1.rc.084"
129
-     * @type string                   $version                          the "software" version for the addon. eg
130
-     *                                                                  "1.0.0.p" for a first stable release, or
131
-     *                                                                  "1.0.0.rc.043" for a version in progress
132
-     * @type string                   $main_file_path                   the full server path to the main file
133
-     *                                                                  loaded directly by WP
134
-     * @type DomainInterface $domain                                    child class of
135
-     *                                                                  EventEspresso\core\domain\DomainBase
136
-     * @type string                   $domain_fqcn                      Fully Qualified Class Name
137
-     *                                                                  for the addon's Domain class
138
-     *                                                                  (see EventEspresso\core\domain\Domain)
139
-     * @type string                   $admin_path                       full server path to the folder where the
140
-     *                                                                  addon\'s admin files reside
141
-     * @type string                   $admin_callback                   a method to be called when the EE Admin is
142
-     *                                                                  first invoked, can be used for hooking into
143
-     *                                                                  any admin page
144
-     * @type string                   $config_section                   the section name for this addon's
145
-     *                                                                  configuration settings section
146
-     *                                                                  (defaults to "addons")
147
-     * @type string                   $config_class                     the class name for this addon's
148
-     *                                                                  configuration settings object
149
-     * @type string                   $config_name                      the class name for this addon's
150
-     *                                                                  configuration settings object
151
-     * @type string                   $autoloader_paths                 [Required] an array of class names and the full
152
-     *                                                                  server paths to those files.
153
-     * @type string                   $autoloader_folders               an array of  "full server paths" for any
154
-     *                                                                  folders containing classes that might be
155
-     *                                                                  invoked by the addon
156
-     * @type string                   $dms_paths                        [Required] an array of full server paths to
157
-     *                                                                  folders that contain data migration scripts.
158
-     *                                                                  The key should be the EE_Addon class name that
159
-     *                                                                  this set of data migration scripts belongs to.
160
-     *                                                                  If the EE_Addon class is namespaced, then this
161
-     *                                                                  needs to be the Fully Qualified Class Name
162
-     * @type string                   $module_paths                     an array of full server paths to any
163
-     *                                                                  EED_Modules used by the addon
164
-     * @type string                   $shortcode_paths                  an array of full server paths to folders
165
-     *                                                                  that contain EES_Shortcodes
166
-     * @type string                   $widget_paths                     an array of full server paths to folders
167
-     *                                                                  that contain WP_Widgets
168
-     * @type string                   $pue_options
169
-     * @type array                    $capabilities                     an array indexed by role name
170
-     *                                                                  (i.e administrator,author ) and the values
171
-     *                                                                  are an array of caps to add to the role.
172
-     *                                                                  'administrator' => array(
173
-     *                                                                  'read_addon',
174
-     *                                                                  'edit_addon',
175
-     *                                                                  etc.
176
-     *                                                                  ).
177
-     * @type EE_Meta_Capability_Map[] $capability_maps                  an array of EE_Meta_Capability_Map object
178
-     *                                                                  for any addons that need to register any
179
-     *                                                                  special meta mapped capabilities.  Should
180
-     *                                                                  be indexed where the key is the
181
-     *                                                                  EE_Meta_Capability_Map class name and the
182
-     *                                                                  values are the arguments sent to the class.
183
-     * @type array                    $model_paths                      array of folders containing DB models
184
-     * @see      EE_Register_Model
185
-     * @type array                    $class_paths                      array of folders containing DB classes
186
-     * @see      EE_Register_Model
187
-     * @type array                    $model_extension_paths            array of folders containing DB model
188
-     *                                                                  extensions
189
-     * @see      EE_Register_Model_Extension
190
-     * @type array                    $class_extension_paths            array of folders containing DB class
191
-     *                                                                  extensions
192
-     * @see      EE_Register_Model_Extension
193
-     * @type array message_types {
194
-     *                                                                  An array of message types with the key as
195
-     *                                                                  the message type name and the values as
196
-     *                                                                  below:
197
-     * @type string                   $mtfilename                       [Required] The filename of the message type
198
-     *                                                                  being registered. This will be the main
199
-     *                                                                  EE_{Message Type Name}_message_type class.
200
-     *                                                                  for example:
201
-     *                                                                  EE_Declined_Registration_message_type.class.php
202
-     * @type array                    $autoloadpaths                    [Required] An array of paths to add to the
203
-     *                                                                  messages autoloader for the new message type.
204
-     * @type array                    $messengers_to_activate_with      An array of messengers that this message
205
-     *                                                                  type should activate with. Each value in
206
-     *                                                                  the
207
-     *                                                                  array
208
-     *                                                                  should match the name property of a
209
-     *                                                                  EE_messenger. Optional.
210
-     * @type array                    $messengers_to_validate_with      An array of messengers that this message
211
-     *                                                                  type should validate with. Each value in
212
-     *                                                                  the
213
-     *                                                                  array
214
-     *                                                                  should match the name property of an
215
-     *                                                                  EE_messenger.
216
-     *                                                                  Optional.
217
-     *                                                                  }
218
-     * @type array                    $custom_post_types
219
-     * @type array                    $custom_taxonomies
220
-     * @type array                    $payment_method_paths             each element is the folder containing the
221
-     *                                                                  EE_PMT_Base child class
222
-     *                                                                  (eg,
223
-     *                                                                  '/wp-content/plugins/my_plugin/Payomatic/'
224
-     *                                                                  which contains the files
225
-     *                                                                  EE_PMT_Payomatic.pm.php)
226
-     * @type array                    $default_terms
227
-     * @type array                    $namespace                        {
228
-     *                                                                  An array with two items for registering the
229
-     *                                                                  addon's namespace. (If, for some reason, you
230
-     *                                                                  require additional namespaces,
231
-     *                                                                  use
232
-     *                                                                  EventEspresso\core\Psr4Autoloader::addNamespace()
233
-     *                                                                  directly)
234
-     * @see      EventEspresso\core\Psr4Autoloader::addNamespace()
235
-     * @type string                   $FQNS                             the namespace prefix
236
-     * @type string                   $DIR                              a base directory for class files in the
237
-     *                                                                  namespace.
238
-     *                                                                  }
239
-     *                                                                  }
240
-     * @type string                   $privacy_policies                 FQNSs (namespaces, each of which contains only
241
-     *                                                                  privacy policy classes) or FQCNs (specific
242
-     *                                                                  classnames of privacy policy classes)
243
-     * @type string                   $personal_data_exporters          FQNSs (namespaces, each of which contains only
244
-     *                                                                  privacy policy classes) or FQCNs (specific
245
-     *                                                                  classnames of privacy policy classes)
246
-     * @type string                   $personal_data_erasers            FQNSs (namespaces, each of which contains only
247
-     *                                                                  privacy policy classes) or FQCNs (specific
248
-     *                                                                  classnames of privacy policy classes)
249
-     * @return void
250
-     * @throws DomainException
251
-     * @throws EE_Error
252
-     * @throws InvalidArgumentException
253
-     * @throws InvalidDataTypeException
254
-     * @throws InvalidInterfaceException
255
-     */
256
-    public static function register($addon_name = '', array $setup_args = array())
257
-    {
258
-        // required fields MUST be present, so let's make sure they are.
259
-        EE_Register_Addon::_verify_parameters($addon_name, $setup_args);
260
-        // get class name for addon
261
-        $class_name = EE_Register_Addon::_parse_class_name($addon_name, $setup_args);
262
-        // setup $_settings array from incoming values.
263
-        $addon_settings = EE_Register_Addon::_get_addon_settings($class_name, $setup_args);
264
-        // setup PUE
265
-        EE_Register_Addon::_parse_pue_options($addon_name, $class_name, $setup_args);
266
-        // does this addon work with this version of core or WordPress ?
267
-        // does this addon work with this version of core or WordPress ?
268
-        if (! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
269
-            return;
270
-        }
271
-        // register namespaces
272
-        EE_Register_Addon::_setup_namespaces($addon_settings);
273
-        // check if this is an activation request
274
-        if (EE_Register_Addon::_addon_activation($addon_name, $addon_settings)) {
275
-            // dont bother setting up the rest of the addon atm
276
-            return;
277
-        }
278
-        // we need cars
279
-        EE_Register_Addon::_setup_autoloaders($addon_name);
280
-        // register new models and extensions
281
-        EE_Register_Addon::_register_models_and_extensions($addon_name);
282
-        // setup DMS
283
-        EE_Register_Addon::_register_data_migration_scripts($addon_name);
284
-        // if config_class is present let's register config.
285
-        EE_Register_Addon::_register_config($addon_name);
286
-        // register admin pages
287
-        EE_Register_Addon::_register_admin_pages($addon_name);
288
-        // add to list of modules to be registered
289
-        EE_Register_Addon::_register_modules($addon_name);
290
-        // add to list of shortcodes to be registered
291
-        EE_Register_Addon::_register_shortcodes($addon_name);
292
-        // add to list of widgets to be registered
293
-        EE_Register_Addon::_register_widgets($addon_name);
294
-        // register capability related stuff.
295
-        EE_Register_Addon::_register_capabilities($addon_name);
296
-        // any message type to register?
297
-        EE_Register_Addon::_register_message_types($addon_name);
298
-        // any custom post type/ custom capabilities or default terms to register
299
-        EE_Register_Addon::_register_custom_post_types($addon_name);
300
-        // and any payment methods
301
-        EE_Register_Addon::_register_payment_methods($addon_name);
302
-        // and privacy policy generators
303
-        EE_Register_Addon::registerPrivacyPolicies($addon_name);
304
-        // and privacy policy generators
305
-        EE_Register_Addon::registerPersonalDataExporters($addon_name);
306
-        // and privacy policy generators
307
-        EE_Register_Addon::registerPersonalDataErasers($addon_name);
308
-        // load and instantiate main addon class
309
-        $addon = EE_Register_Addon::_load_and_init_addon_class($addon_name);
310
-        // delay calling after_registration hook on each addon until after all add-ons have been registered.
311
-        add_action('AHEE__EE_System__load_espresso_addons__complete', array($addon, 'after_registration'), 999);
312
-    }
313
-
314
-
315
-    /**
316
-     * @param string $addon_name
317
-     * @param array  $setup_args
318
-     * @return void
319
-     * @throws EE_Error
320
-     */
321
-    private static function _verify_parameters($addon_name, array $setup_args)
322
-    {
323
-        // required fields MUST be present, so let's make sure they are.
324
-        if (empty($addon_name) || ! is_array($setup_args)) {
325
-            throw new EE_Error(
326
-                __(
327
-                    'In order to register an EE_Addon with EE_Register_Addon::register(), you must include the "addon_name" (the name of the addon), and an array of arguments.',
328
-                    'event_espresso'
329
-                )
330
-            );
331
-        }
332
-        if (! isset($setup_args['main_file_path']) || empty($setup_args['main_file_path'])) {
333
-            throw new EE_Error(
334
-                sprintf(
335
-                    __(
336
-                        'When registering an addon, you didn\'t provide the "main_file_path", which is the full path to the main file loaded directly by Wordpress. You only provided %s',
337
-                        'event_espresso'
338
-                    ),
339
-                    implode(',', array_keys($setup_args))
340
-                )
341
-            );
342
-        }
343
-        // check that addon has not already been registered with that name
344
-        if (isset(self::$_settings[ $addon_name ]) && ! did_action('activate_plugin')) {
345
-            throw new EE_Error(
346
-                sprintf(
347
-                    __(
348
-                        'An EE_Addon with the name "%s" has already been registered and each EE_Addon requires a unique name.',
349
-                        'event_espresso'
350
-                    ),
351
-                    $addon_name
352
-                )
353
-            );
354
-        }
355
-    }
356
-
357
-
358
-    /**
359
-     * @param string $addon_name
360
-     * @param array  $setup_args
361
-     * @return string
362
-     */
363
-    private static function _parse_class_name($addon_name, array $setup_args)
364
-    {
365
-        if (empty($setup_args['class_name'])) {
366
-            // generate one by first separating name with spaces
367
-            $class_name = str_replace(array('-', '_'), ' ', trim($addon_name));
368
-            // capitalize, then replace spaces with underscores
369
-            $class_name = str_replace(' ', '_', ucwords($class_name));
370
-        } else {
371
-            $class_name = $setup_args['class_name'];
372
-        }
373
-        // check if classname is fully  qualified or is a legacy classname already prefixed with 'EE_'
374
-        return strpos($class_name, '\\') || strpos($class_name, 'EE_') === 0
375
-            ? $class_name
376
-            : 'EE_' . $class_name;
377
-    }
378
-
379
-
380
-    /**
381
-     * @param string $class_name
382
-     * @param array  $setup_args
383
-     * @return array
384
-     */
385
-    private static function _get_addon_settings($class_name, array $setup_args)
386
-    {
387
-        // setup $_settings array from incoming values.
388
-        $addon_settings = array(
389
-            // generated from the addon name, changes something like "calendar" to "EE_Calendar"
390
-            'class_name'            => $class_name,
391
-            // the addon slug for use in URLs, etc
392
-            'plugin_slug'           => isset($setup_args['plugin_slug'])
393
-                ? (string) $setup_args['plugin_slug']
394
-                : '',
395
-            // page slug to be used when generating the "Settings" link on the WP plugin page
396
-            'plugin_action_slug'    => isset($setup_args['plugin_action_slug'])
397
-                ? (string) $setup_args['plugin_action_slug']
398
-                : '',
399
-            // the "software" version for the addon
400
-            'version'               => isset($setup_args['version'])
401
-                ? (string) $setup_args['version']
402
-                : '',
403
-            // the minimum version of EE Core that the addon will work with
404
-            'min_core_version'      => isset($setup_args['min_core_version'])
405
-                ? (string) $setup_args['min_core_version']
406
-                : '',
407
-            // the minimum version of WordPress that the addon will work with
408
-            'min_wp_version'        => isset($setup_args['min_wp_version'])
409
-                ? (string) $setup_args['min_wp_version']
410
-                : EE_MIN_WP_VER_REQUIRED,
411
-            // full server path to main file (file loaded directly by WP)
412
-            'main_file_path'        => isset($setup_args['main_file_path'])
413
-                ? (string) $setup_args['main_file_path']
414
-                : '',
415
-            // instance of \EventEspresso\core\domain\DomainInterface
416
-            'domain'                => isset($setup_args['domain']) && $setup_args['domain'] instanceof DomainInterface
417
-                ? $setup_args['domain']
418
-                : null,
419
-            // Fully Qualified Class Name for the addon's Domain class
420
-            'domain_fqcn'           => isset($setup_args['domain_fqcn'])
421
-                ? (string) $setup_args['domain_fqcn']
422
-                : '',
423
-            // path to folder containing files for integrating with the EE core admin and/or setting up EE admin pages
424
-            'admin_path'            => isset($setup_args['admin_path'])
425
-                ? (string) $setup_args['admin_path'] : '',
426
-            // a method to be called when the EE Admin is first invoked, can be used for hooking into any admin page
427
-            'admin_callback'        => isset($setup_args['admin_callback'])
428
-                ? (string) $setup_args['admin_callback']
429
-                : '',
430
-            // the section name for this addon's configuration settings section (defaults to "addons")
431
-            'config_section'        => isset($setup_args['config_section'])
432
-                ? (string) $setup_args['config_section']
433
-                : 'addons',
434
-            // the class name for this addon's configuration settings object
435
-            'config_class'          => isset($setup_args['config_class'])
436
-                ? (string) $setup_args['config_class'] : '',
437
-            // the name given to the config for this addons' configuration settings object (optional)
438
-            'config_name'           => isset($setup_args['config_name'])
439
-                ? (string) $setup_args['config_name'] : '',
440
-            // an array of "class names" => "full server paths" for any classes that might be invoked by the addon
441
-            'autoloader_paths'      => isset($setup_args['autoloader_paths'])
442
-                ? (array) $setup_args['autoloader_paths']
443
-                : array(),
444
-            // an array of  "full server paths" for any folders containing classes that might be invoked by the addon
445
-            'autoloader_folders'    => isset($setup_args['autoloader_folders'])
446
-                ? (array) $setup_args['autoloader_folders']
447
-                : array(),
448
-            // array of full server paths to any EE_DMS data migration scripts used by the addon.
449
-            // The key should be the EE_Addon class name that this set of data migration scripts belongs to.
450
-            // If the EE_Addon class is namespaced, then this needs to be the Fully Qualified Class Name
451
-            'dms_paths'             => isset($setup_args['dms_paths'])
452
-                ? (array) $setup_args['dms_paths']
453
-                : array(),
454
-            // array of full server paths to any EED_Modules used by the addon
455
-            'module_paths'          => isset($setup_args['module_paths'])
456
-                ? (array) $setup_args['module_paths']
457
-                : array(),
458
-            // array of full server paths to any EES_Shortcodes used by the addon
459
-            'shortcode_paths'       => isset($setup_args['shortcode_paths'])
460
-                ? (array) $setup_args['shortcode_paths']
461
-                : array(),
462
-            'shortcode_fqcns'       => isset($setup_args['shortcode_fqcns'])
463
-                ? (array) $setup_args['shortcode_fqcns']
464
-                : array(),
465
-            // array of full server paths to any WP_Widgets used by the addon
466
-            'widget_paths'          => isset($setup_args['widget_paths'])
467
-                ? (array) $setup_args['widget_paths']
468
-                : array(),
469
-            // array of PUE options used by the addon
470
-            'pue_options'           => isset($setup_args['pue_options'])
471
-                ? (array) $setup_args['pue_options']
472
-                : array(),
473
-            'message_types'         => isset($setup_args['message_types'])
474
-                ? (array) $setup_args['message_types']
475
-                : array(),
476
-            'capabilities'          => isset($setup_args['capabilities'])
477
-                ? (array) $setup_args['capabilities']
478
-                : array(),
479
-            'capability_maps'       => isset($setup_args['capability_maps'])
480
-                ? (array) $setup_args['capability_maps']
481
-                : array(),
482
-            'model_paths'           => isset($setup_args['model_paths'])
483
-                ? (array) $setup_args['model_paths']
484
-                : array(),
485
-            'class_paths'           => isset($setup_args['class_paths'])
486
-                ? (array) $setup_args['class_paths']
487
-                : array(),
488
-            'model_extension_paths' => isset($setup_args['model_extension_paths'])
489
-                ? (array) $setup_args['model_extension_paths']
490
-                : array(),
491
-            'class_extension_paths' => isset($setup_args['class_extension_paths'])
492
-                ? (array) $setup_args['class_extension_paths']
493
-                : array(),
494
-            'custom_post_types'     => isset($setup_args['custom_post_types'])
495
-                ? (array) $setup_args['custom_post_types']
496
-                : array(),
497
-            'custom_taxonomies'     => isset($setup_args['custom_taxonomies'])
498
-                ? (array) $setup_args['custom_taxonomies']
499
-                : array(),
500
-            'payment_method_paths'  => isset($setup_args['payment_method_paths'])
501
-                ? (array) $setup_args['payment_method_paths']
502
-                : array(),
503
-            'default_terms'         => isset($setup_args['default_terms'])
504
-                ? (array) $setup_args['default_terms']
505
-                : array(),
506
-            // if not empty, inserts a new table row after this plugin's row on the WP Plugins page
507
-            // that can be used for adding upgrading/marketing info
508
-            'plugins_page_row'      => isset($setup_args['plugins_page_row']) ? $setup_args['plugins_page_row'] : '',
509
-            'namespace'             => isset(
510
-                $setup_args['namespace']['FQNS'],
511
-                $setup_args['namespace']['DIR']
512
-            )
513
-                ? (array) $setup_args['namespace']
514
-                : array(),
515
-            'privacy_policies'      => isset($setup_args['privacy_policies'])
516
-                ? (array) $setup_args['privacy_policies']
517
-                : '',
518
-        );
519
-        // if plugin_action_slug is NOT set, but an admin page path IS set,
520
-        // then let's just use the plugin_slug since that will be used for linking to the admin page
521
-        $addon_settings['plugin_action_slug'] = empty($addon_settings['plugin_action_slug'])
522
-                                                && ! empty($addon_settings['admin_path'])
523
-            ? $addon_settings['plugin_slug']
524
-            : $addon_settings['plugin_action_slug'];
525
-        // full server path to main file (file loaded directly by WP)
526
-        $addon_settings['plugin_basename'] = plugin_basename($addon_settings['main_file_path']);
527
-        return $addon_settings;
528
-    }
529
-
530
-
531
-    /**
532
-     * @param string $addon_name
533
-     * @param array  $addon_settings
534
-     * @return boolean
535
-     */
536
-    private static function _addon_is_compatible($addon_name, array $addon_settings)
537
-    {
538
-        global $wp_version;
539
-        $incompatibility_message = '';
540
-        // check whether this addon version is compatible with EE core
541
-        if (isset(EE_Register_Addon::$_incompatible_addons[ $addon_name ])
542
-            && ! self::_meets_min_core_version_requirement(
543
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
544
-                $addon_settings['version']
545
-            )
546
-        ) {
547
-            $incompatibility_message = sprintf(
548
-                __(
549
-                    '%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon is not compatible with this version of Event Espresso.%2$sPlease upgrade your "%1$s" addon to version %3$s or newer to resolve this issue.',
550
-                    'event_espresso'
551
-                ),
552
-                $addon_name,
553
-                '<br />',
554
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
555
-                '<span style="font-weight: bold; color: #D54E21;">',
556
-                '</span><br />'
557
-            );
558
-        } elseif (! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
559
-        ) {
560
-            $incompatibility_message = sprintf(
561
-                __(
562
-                    '%5$sIMPORTANT!%6$sThe Event Espresso "%1$s" addon requires Event Espresso Core version "%2$s" or higher in order to run.%4$sYour version of Event Espresso Core is currently at "%3$s". Please upgrade Event Espresso Core first and then re-activate "%1$s".',
563
-                    'event_espresso'
564
-                ),
565
-                $addon_name,
566
-                self::_effective_version($addon_settings['min_core_version']),
567
-                self::_effective_version(espresso_version()),
568
-                '<br />',
569
-                '<span style="font-weight: bold; color: #D54E21;">',
570
-                '</span><br />'
571
-            );
572
-        } elseif (version_compare($wp_version, $addon_settings['min_wp_version'], '<')) {
573
-            $incompatibility_message = sprintf(
574
-                __(
575
-                    '%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon requires WordPress version "%2$s" or greater.%3$sPlease update your version of WordPress to use the "%1$s" addon and to keep your site secure.',
576
-                    'event_espresso'
577
-                ),
578
-                $addon_name,
579
-                $addon_settings['min_wp_version'],
580
-                '<br />',
581
-                '<span style="font-weight: bold; color: #D54E21;">',
582
-                '</span><br />'
583
-            );
584
-        }
585
-        if (! empty($incompatibility_message)) {
586
-            // remove 'activate' from the REQUEST
587
-            // so WP doesn't erroneously tell the user the plugin activated fine when it didn't
588
-            /** @var RequestInterface $request */
589
-            $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
590
-            $request->unSetRequestParam('activate', true);
591
-            if (current_user_can('activate_plugins')) {
592
-                // show an error message indicating the plugin didn't activate properly
593
-                EE_Error::add_error($incompatibility_message, __FILE__, __FUNCTION__, __LINE__);
594
-            }
595
-            // BAIL FROM THE ADDON REGISTRATION PROCESS
596
-            return false;
597
-        }
598
-        // addon IS compatible
599
-        return true;
600
-    }
601
-
602
-
603
-    /**
604
-     * if plugin update engine is being used for auto-updates,
605
-     * then let's set that up now before going any further so that ALL addons can be updated
606
-     * (not needed if PUE is not being used)
607
-     *
608
-     * @param string $addon_name
609
-     * @param string $class_name
610
-     * @param array  $setup_args
611
-     * @return void
612
-     */
613
-    private static function _parse_pue_options($addon_name, $class_name, array $setup_args)
614
-    {
615
-        if (! empty($setup_args['pue_options'])) {
616
-            self::$_settings[ $addon_name ]['pue_options'] = array(
617
-                'pue_plugin_slug' => isset($setup_args['pue_options']['pue_plugin_slug'])
618
-                    ? (string) $setup_args['pue_options']['pue_plugin_slug']
619
-                    : 'espresso_' . strtolower($class_name),
620
-                'plugin_basename' => isset($setup_args['pue_options']['plugin_basename'])
621
-                    ? (string) $setup_args['pue_options']['plugin_basename']
622
-                    : plugin_basename($setup_args['main_file_path']),
623
-                'checkPeriod'     => isset($setup_args['pue_options']['checkPeriod'])
624
-                    ? (string) $setup_args['pue_options']['checkPeriod']
625
-                    : '24',
626
-                'use_wp_update'   => isset($setup_args['pue_options']['use_wp_update'])
627
-                    ? (string) $setup_args['pue_options']['use_wp_update']
628
-                    : false,
629
-            );
630
-            add_action(
631
-                'AHEE__EE_System__brew_espresso__after_pue_init',
632
-                array('EE_Register_Addon', 'load_pue_update')
633
-            );
634
-        }
635
-    }
636
-
637
-
638
-    /**
639
-     * register namespaces right away before any other files or classes get loaded, but AFTER the version checks
640
-     *
641
-     * @param array $addon_settings
642
-     * @return void
643
-     */
644
-    private static function _setup_namespaces(array $addon_settings)
645
-    {
646
-        //
647
-        if (isset(
648
-            $addon_settings['namespace']['FQNS'],
649
-            $addon_settings['namespace']['DIR']
650
-        )) {
651
-            EE_Psr4AutoloaderInit::psr4_loader()->addNamespace(
652
-                $addon_settings['namespace']['FQNS'],
653
-                $addon_settings['namespace']['DIR']
654
-            );
655
-        }
656
-    }
657
-
658
-
659
-    /**
660
-     * @param string $addon_name
661
-     * @param array  $addon_settings
662
-     * @return bool
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidDataTypeException
665
-     * @throws InvalidInterfaceException
666
-     */
667
-    private static function _addon_activation($addon_name, array $addon_settings)
668
-    {
669
-        // this is an activation request
670
-        if (did_action('activate_plugin')) {
671
-            // to find if THIS is the addon that was activated, just check if we have already registered it or not
672
-            // (as the newly-activated addon wasn't around the first time addons were registered).
673
-            // Note: the presence of pue_options in the addon registration options will initialize the $_settings
674
-            // property for the add-on, but the add-on is only partially initialized.  Hence, the additional check.
675
-            if (! isset(self::$_settings[ $addon_name ])
676
-                || (isset(self::$_settings[ $addon_name ])
677
-                    && ! isset(self::$_settings[ $addon_name ]['class_name'])
678
-                )
679
-            ) {
680
-                self::$_settings[ $addon_name ] = $addon_settings;
681
-                $addon = self::_load_and_init_addon_class($addon_name);
682
-                $addon->set_activation_indicator_option();
683
-                // dont bother setting up the rest of the addon.
684
-                // we know it was just activated and the request will end soon
685
-            }
686
-            return true;
687
-        }
688
-        // make sure this was called in the right place!
689
-        if (! did_action('AHEE__EE_System__load_espresso_addons')
690
-            || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')
691
-        ) {
692
-            EE_Error::doing_it_wrong(
693
-                __METHOD__,
694
-                sprintf(
695
-                    __(
696
-                        'An attempt to register an EE_Addon named "%s" has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__load_espresso_addons" hook to register addons.',
697
-                        'event_espresso'
698
-                    ),
699
-                    $addon_name
700
-                ),
701
-                '4.3.0'
702
-            );
703
-        }
704
-        // make sure addon settings are set correctly without overwriting anything existing
705
-        if (isset(self::$_settings[ $addon_name ])) {
706
-            self::$_settings[ $addon_name ] += $addon_settings;
707
-        } else {
708
-            self::$_settings[ $addon_name ] = $addon_settings;
709
-        }
710
-        return false;
711
-    }
712
-
713
-
714
-    /**
715
-     * @param string $addon_name
716
-     * @return void
717
-     * @throws EE_Error
718
-     */
719
-    private static function _setup_autoloaders($addon_name)
720
-    {
721
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_paths'])) {
722
-            // setup autoloader for single file
723
-            EEH_Autoloader::instance()->register_autoloader(self::$_settings[ $addon_name ]['autoloader_paths']);
724
-        }
725
-        // setup autoloaders for folders
726
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_folders'])) {
727
-            foreach ((array) self::$_settings[ $addon_name ]['autoloader_folders'] as $autoloader_folder) {
728
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($autoloader_folder);
729
-            }
730
-        }
731
-    }
732
-
733
-
734
-    /**
735
-     * register new models and extensions
736
-     *
737
-     * @param string $addon_name
738
-     * @return void
739
-     * @throws EE_Error
740
-     */
741
-    private static function _register_models_and_extensions($addon_name)
742
-    {
743
-        // register new models
744
-        if (! empty(self::$_settings[ $addon_name ]['model_paths'])
745
-            || ! empty(self::$_settings[ $addon_name ]['class_paths'])
746
-        ) {
747
-            EE_Register_Model::register(
748
-                $addon_name,
749
-                array(
750
-                    'model_paths' => self::$_settings[ $addon_name ]['model_paths'],
751
-                    'class_paths' => self::$_settings[ $addon_name ]['class_paths'],
752
-                )
753
-            );
754
-        }
755
-        // register model extensions
756
-        if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
757
-            || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
758
-        ) {
759
-            EE_Register_Model_Extensions::register(
760
-                $addon_name,
761
-                array(
762
-                    'model_extension_paths' => self::$_settings[ $addon_name ]['model_extension_paths'],
763
-                    'class_extension_paths' => self::$_settings[ $addon_name ]['class_extension_paths'],
764
-                )
765
-            );
766
-        }
767
-    }
768
-
769
-
770
-    /**
771
-     * @param string $addon_name
772
-     * @return void
773
-     * @throws EE_Error
774
-     */
775
-    private static function _register_data_migration_scripts($addon_name)
776
-    {
777
-        // setup DMS
778
-        if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
779
-            EE_Register_Data_Migration_Scripts::register(
780
-                $addon_name,
781
-                array('dms_paths' => self::$_settings[ $addon_name ]['dms_paths'])
782
-            );
783
-        }
784
-    }
785
-
786
-
787
-    /**
788
-     * @param string $addon_name
789
-     * @return void
790
-     * @throws EE_Error
791
-     */
792
-    private static function _register_config($addon_name)
793
-    {
794
-        // if config_class is present let's register config.
795
-        if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
796
-            EE_Register_Config::register(
797
-                self::$_settings[ $addon_name ]['config_class'],
798
-                array(
799
-                    'config_section' => self::$_settings[ $addon_name ]['config_section'],
800
-                    'config_name'    => self::$_settings[ $addon_name ]['config_name'],
801
-                )
802
-            );
803
-        }
804
-    }
805
-
806
-
807
-    /**
808
-     * @param string $addon_name
809
-     * @return void
810
-     * @throws EE_Error
811
-     */
812
-    private static function _register_admin_pages($addon_name)
813
-    {
814
-        if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
815
-            EE_Register_Admin_Page::register(
816
-                $addon_name,
817
-                array('page_path' => self::$_settings[ $addon_name ]['admin_path'])
818
-            );
819
-        }
820
-    }
821
-
822
-
823
-    /**
824
-     * @param string $addon_name
825
-     * @return void
826
-     * @throws EE_Error
827
-     */
828
-    private static function _register_modules($addon_name)
829
-    {
830
-        if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
831
-            EE_Register_Module::register(
832
-                $addon_name,
833
-                array('module_paths' => self::$_settings[ $addon_name ]['module_paths'])
834
-            );
835
-        }
836
-    }
837
-
838
-
839
-    /**
840
-     * @param string $addon_name
841
-     * @return void
842
-     * @throws EE_Error
843
-     */
844
-    private static function _register_shortcodes($addon_name)
845
-    {
846
-        if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
847
-            || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
848
-        ) {
849
-            EE_Register_Shortcode::register(
850
-                $addon_name,
851
-                array(
852
-                    'shortcode_paths' => isset(self::$_settings[ $addon_name ]['shortcode_paths'])
853
-                        ? self::$_settings[ $addon_name ]['shortcode_paths'] : array(),
854
-                    'shortcode_fqcns' => isset(self::$_settings[ $addon_name ]['shortcode_fqcns'])
855
-                        ? self::$_settings[ $addon_name ]['shortcode_fqcns'] : array(),
856
-                )
857
-            );
858
-        }
859
-    }
860
-
861
-
862
-    /**
863
-     * @param string $addon_name
864
-     * @return void
865
-     * @throws EE_Error
866
-     */
867
-    private static function _register_widgets($addon_name)
868
-    {
869
-        if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
870
-            EE_Register_Widget::register(
871
-                $addon_name,
872
-                array('widget_paths' => self::$_settings[ $addon_name ]['widget_paths'])
873
-            );
874
-        }
875
-    }
876
-
877
-
878
-    /**
879
-     * @param string $addon_name
880
-     * @return void
881
-     * @throws EE_Error
882
-     */
883
-    private static function _register_capabilities($addon_name)
884
-    {
885
-        if (! empty(self::$_settings[ $addon_name ]['capabilities'])) {
886
-            EE_Register_Capabilities::register(
887
-                $addon_name,
888
-                array(
889
-                    'capabilities'    => self::$_settings[ $addon_name ]['capabilities'],
890
-                    'capability_maps' => self::$_settings[ $addon_name ]['capability_maps'],
891
-                )
892
-            );
893
-        }
894
-    }
895
-
896
-
897
-    /**
898
-     * @param string $addon_name
899
-     * @return void
900
-     */
901
-    private static function _register_message_types($addon_name)
902
-    {
903
-        if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
904
-            add_action(
905
-                'EE_Brewing_Regular___messages_caf',
906
-                array('EE_Register_Addon', 'register_message_types')
907
-            );
908
-        }
909
-    }
910
-
911
-
912
-    /**
913
-     * @param string $addon_name
914
-     * @return void
915
-     * @throws EE_Error
916
-     */
917
-    private static function _register_custom_post_types($addon_name)
918
-    {
919
-        if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])
920
-            || ! empty(self::$_settings[ $addon_name ]['custom_taxonomies'])
921
-        ) {
922
-            EE_Register_CPT::register(
923
-                $addon_name,
924
-                array(
925
-                    'cpts'          => self::$_settings[ $addon_name ]['custom_post_types'],
926
-                    'cts'           => self::$_settings[ $addon_name ]['custom_taxonomies'],
927
-                    'default_terms' => self::$_settings[ $addon_name ]['default_terms'],
928
-                )
929
-            );
930
-        }
931
-    }
932
-
933
-
934
-    /**
935
-     * @param string $addon_name
936
-     * @return void
937
-     * @throws InvalidArgumentException
938
-     * @throws InvalidInterfaceException
939
-     * @throws InvalidDataTypeException
940
-     * @throws DomainException
941
-     * @throws EE_Error
942
-     */
943
-    private static function _register_payment_methods($addon_name)
944
-    {
945
-        if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
946
-            EE_Register_Payment_Method::register(
947
-                $addon_name,
948
-                array('payment_method_paths' => self::$_settings[ $addon_name ]['payment_method_paths'])
949
-            );
950
-        }
951
-    }
952
-
953
-
954
-    /**
955
-     * @param string $addon_name
956
-     * @return void
957
-     * @throws InvalidArgumentException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidDataTypeException
960
-     * @throws DomainException
961
-     */
962
-    private static function registerPrivacyPolicies($addon_name)
963
-    {
964
-        if (! empty(self::$_settings[ $addon_name ]['privacy_policies'])) {
965
-            EE_Register_Privacy_Policy::register(
966
-                $addon_name,
967
-                self::$_settings[ $addon_name ]['privacy_policies']
968
-            );
969
-        }
970
-    }
971
-
972
-
973
-    /**
974
-     * @param string $addon_name
975
-     * @return void
976
-     */
977
-    private static function registerPersonalDataExporters($addon_name)
978
-    {
979
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_exporters'])) {
980
-            EE_Register_Personal_Data_Eraser::register(
981
-                $addon_name,
982
-                self::$_settings[ $addon_name ]['personal_data_exporters']
983
-            );
984
-        }
985
-    }
986
-
987
-
988
-    /**
989
-     * @param string $addon_name
990
-     * @return void
991
-     */
992
-    private static function registerPersonalDataErasers($addon_name)
993
-    {
994
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_erasers'])) {
995
-            EE_Register_Personal_Data_Eraser::register(
996
-                $addon_name,
997
-                self::$_settings[ $addon_name ]['personal_data_erasers']
998
-            );
999
-        }
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Loads and instantiates the EE_Addon class and adds it onto the registry
1005
-     *
1006
-     * @param string $addon_name
1007
-     * @return EE_Addon
1008
-     * @throws InvalidArgumentException
1009
-     * @throws InvalidInterfaceException
1010
-     * @throws InvalidDataTypeException
1011
-     */
1012
-    private static function _load_and_init_addon_class($addon_name)
1013
-    {
1014
-        $addon = LoaderFactory::getLoader()->getShared(
1015
-            self::$_settings[ $addon_name ]['class_name'],
1016
-            array('EE_Registry::create(addon)' => true)
1017
-        );
1018
-        if (! $addon instanceof EE_Addon) {
1019
-            throw new DomainException(
1020
-                sprintf(
1021
-                    esc_html__(
1022
-                        'Failed to instantiate the %1$s class. PLease check that the class exists.',
1023
-                        'event_espresso'
1024
-                    ),
1025
-                    $addon_name
1026
-                )
1027
-            );
1028
-        }
1029
-        // setter inject dep map if required
1030
-        if ($addon->dependencyMap() === null) {
1031
-            $addon->setDependencyMap(LoaderFactory::getLoader()->getShared('EE_Dependency_Map'));
1032
-        }
1033
-        // setter inject domain if required
1034
-        EE_Register_Addon::injectAddonDomain($addon_name, $addon);
1035
-
1036
-        $addon->set_name($addon_name);
1037
-        $addon->set_plugin_slug(self::$_settings[ $addon_name ]['plugin_slug']);
1038
-        $addon->set_plugin_basename(self::$_settings[ $addon_name ]['plugin_basename']);
1039
-        $addon->set_main_plugin_file(self::$_settings[ $addon_name ]['main_file_path']);
1040
-        $addon->set_plugin_action_slug(self::$_settings[ $addon_name ]['plugin_action_slug']);
1041
-        $addon->set_plugins_page_row(self::$_settings[ $addon_name ]['plugins_page_row']);
1042
-        $addon->set_version(self::$_settings[ $addon_name ]['version']);
1043
-        $addon->set_min_core_version(self::_effective_version(self::$_settings[ $addon_name ]['min_core_version']));
1044
-        $addon->set_config_section(self::$_settings[ $addon_name ]['config_section']);
1045
-        $addon->set_config_class(self::$_settings[ $addon_name ]['config_class']);
1046
-        $addon->set_config_name(self::$_settings[ $addon_name ]['config_name']);
1047
-        // setup the add-on's pue_slug if we have one.
1048
-        if (! empty(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug'])) {
1049
-            $addon->setPueSlug(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug']);
1050
-        }
1051
-        // unfortunately this can't be hooked in upon construction,
1052
-        // because we don't have the plugin's mainfile path upon construction.
1053
-        register_deactivation_hook($addon->get_main_plugin_file(), array($addon, 'deactivation'));
1054
-        // call any additional admin_callback functions during load_admin_controller hook
1055
-        if (! empty(self::$_settings[ $addon_name ]['admin_callback'])) {
1056
-            add_action(
1057
-                'AHEE__EE_System__load_controllers__load_admin_controllers',
1058
-                array($addon, self::$_settings[ $addon_name ]['admin_callback'])
1059
-            );
1060
-        }
1061
-        return $addon;
1062
-    }
1063
-
1064
-
1065
-    /**
1066
-     * @param string   $addon_name
1067
-     * @param EE_Addon $addon
1068
-     * @since   4.10.13.p
1069
-     */
1070
-    private static function injectAddonDomain($addon_name, EE_Addon $addon)
1071
-    {
1072
-        if ($addon instanceof RequiresDomainInterface && $addon->domain() === null) {
1073
-            // using supplied Domain object
1074
-            $domain = self::$_settings[ $addon_name ]['domain'] instanceof DomainInterface
1075
-                ? self::$_settings[ $addon_name ]['domain']
1076
-                : null;
1077
-            // or construct one using Domain FQCN
1078
-            if ($domain === null && self::$_settings[ $addon_name ]['domain_fqcn'] !== '') {
1079
-                $domain = LoaderFactory::getLoader()->getShared(
1080
-                    self::$_settings[ $addon_name ]['domain_fqcn'],
1081
-                    [
1082
-                        new EventEspresso\core\domain\values\FilePath(
1083
-                            self::$_settings[ $addon_name ]['main_file_path']
1084
-                        ),
1085
-                        EventEspresso\core\domain\values\Version::fromString(
1086
-                            self::$_settings[ $addon_name ]['version']
1087
-                        ),
1088
-                    ]
1089
-                );
1090
-            }
1091
-            if ($domain instanceof DomainInterface) {
1092
-                $addon->setDomain($domain);
1093
-            }
1094
-        }
1095
-    }
1096
-
1097
-
1098
-    /**
1099
-     *    load_pue_update - Update notifications
1100
-     *
1101
-     * @return void
1102
-     * @throws InvalidArgumentException
1103
-     * @throws InvalidDataTypeException
1104
-     * @throws InvalidInterfaceException
1105
-     */
1106
-    public static function load_pue_update()
1107
-    {
1108
-        // load PUE client
1109
-        require_once EE_THIRD_PARTY . 'pue/pue-client.php';
1110
-        $license_server = defined('PUE_UPDATES_ENDPOINT') ? PUE_UPDATES_ENDPOINT : 'https://eventespresso.com';
1111
-        // cycle thru settings
1112
-        foreach (self::$_settings as $settings) {
1113
-            if (! empty($settings['pue_options'])) {
1114
-                // initiate the class and start the plugin update engine!
1115
-                new PluginUpdateEngineChecker(
1116
-                    // host file URL
1117
-                    $license_server,
1118
-                    // plugin slug(s)
1119
-                    array(
1120
-                        'premium'    => array('p' => $settings['pue_options']['pue_plugin_slug']),
1121
-                        'prerelease' => array('beta' => $settings['pue_options']['pue_plugin_slug'] . '-pr'),
1122
-                    ),
1123
-                    // options
1124
-                    array(
1125
-                        'apikey'            => EE_Registry::instance()->NET_CFG->core->site_license_key,
1126
-                        'lang_domain'       => 'event_espresso',
1127
-                        'checkPeriod'       => $settings['pue_options']['checkPeriod'],
1128
-                        'option_key'        => 'ee_site_license_key',
1129
-                        'options_page_slug' => 'event_espresso',
1130
-                        'plugin_basename'   => $settings['pue_options']['plugin_basename'],
1131
-                        // if use_wp_update is TRUE it means you want FREE versions of the plugin to be updated from WP
1132
-                        'use_wp_update'     => $settings['pue_options']['use_wp_update'],
1133
-                    )
1134
-                );
1135
-            }
1136
-        }
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * Callback for EE_Brewing_Regular__messages_caf hook used to register message types.
1142
-     *
1143
-     * @since 4.4.0
1144
-     * @return void
1145
-     * @throws EE_Error
1146
-     */
1147
-    public static function register_message_types()
1148
-    {
1149
-        foreach (self::$_settings as $settings) {
1150
-            if (! empty($settings['message_types'])) {
1151
-                foreach ((array) $settings['message_types'] as $message_type => $message_type_settings) {
1152
-                    EE_Register_Message_Type::register($message_type, $message_type_settings);
1153
-                }
1154
-            }
1155
-        }
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * This deregisters an addon that was previously registered with a specific addon_name.
1161
-     *
1162
-     * @param string $addon_name the name for the addon that was previously registered
1163
-     * @throws DomainException
1164
-     * @throws InvalidArgumentException
1165
-     * @throws InvalidDataTypeException
1166
-     * @throws InvalidInterfaceException
1167
-     *@since    4.3.0
1168
-     */
1169
-    public static function deregister($addon_name = '')
1170
-    {
1171
-        if (isset(self::$_settings[ $addon_name ]['class_name'])) {
1172
-            try {
1173
-                do_action('AHEE__EE_Register_Addon__deregister__before', $addon_name);
1174
-                $class_name = self::$_settings[ $addon_name ]['class_name'];
1175
-                if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
1176
-                    // setup DMS
1177
-                    EE_Register_Data_Migration_Scripts::deregister($addon_name);
1178
-                }
1179
-                if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
1180
-                    // register admin page
1181
-                    EE_Register_Admin_Page::deregister($addon_name);
1182
-                }
1183
-                if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
1184
-                    // add to list of modules to be registered
1185
-                    EE_Register_Module::deregister($addon_name);
1186
-                }
1187
-                if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
1188
-                    || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
1189
-                ) {
1190
-                    // add to list of shortcodes to be registered
1191
-                    EE_Register_Shortcode::deregister($addon_name);
1192
-                }
1193
-                if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
1194
-                    // if config_class present let's register config.
1195
-                    EE_Register_Config::deregister(self::$_settings[ $addon_name ]['config_class']);
1196
-                }
1197
-                if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
1198
-                    // add to list of widgets to be registered
1199
-                    EE_Register_Widget::deregister($addon_name);
1200
-                }
1201
-                if (! empty(self::$_settings[ $addon_name ]['model_paths'])
1202
-                    || ! empty(self::$_settings[ $addon_name ]['class_paths'])
1203
-                ) {
1204
-                    // add to list of shortcodes to be registered
1205
-                    EE_Register_Model::deregister($addon_name);
1206
-                }
1207
-                if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
1208
-                    || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
1209
-                ) {
1210
-                    // add to list of shortcodes to be registered
1211
-                    EE_Register_Model_Extensions::deregister($addon_name);
1212
-                }
1213
-                if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
1214
-                    foreach ((array) self::$_settings[ $addon_name ]['message_types'] as $message_type => $message_type_settings) {
1215
-                        EE_Register_Message_Type::deregister($message_type);
1216
-                    }
1217
-                }
1218
-                // deregister capabilities for addon
1219
-                if (! empty(self::$_settings[ $addon_name ]['capabilities'])
1220
-                    || ! empty(self::$_settings[ $addon_name ]['capability_maps'])
1221
-                ) {
1222
-                    EE_Register_Capabilities::deregister($addon_name);
1223
-                }
1224
-                // deregister custom_post_types for addon
1225
-                if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])) {
1226
-                    EE_Register_CPT::deregister($addon_name);
1227
-                }
1228
-                if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
1229
-                    EE_Register_Payment_Method::deregister($addon_name);
1230
-                }
1231
-                $addon = EE_Registry::instance()->getAddon($class_name);
1232
-                if ($addon instanceof EE_Addon) {
1233
-                    remove_action(
1234
-                        'deactivate_' . $addon->get_main_plugin_file_basename(),
1235
-                        array($addon, 'deactivation')
1236
-                    );
1237
-                    remove_action(
1238
-                        'AHEE__EE_System__perform_activations_upgrades_and_migrations',
1239
-                        array($addon, 'initialize_db_if_no_migrations_required')
1240
-                    );
1241
-                    // remove `after_registration` call
1242
-                    remove_action(
1243
-                        'AHEE__EE_System__load_espresso_addons__complete',
1244
-                        array($addon, 'after_registration'),
1245
-                        999
1246
-                    );
1247
-                }
1248
-                EE_Registry::instance()->removeAddon($class_name);
1249
-                LoaderFactory::getLoader()->remove($class_name);
1250
-            } catch (OutOfBoundsException $addon_not_yet_registered_exception) {
1251
-                // the add-on was not yet registered in the registry,
1252
-                // so RegistryContainer::__get() throws this exception.
1253
-                // also no need to worry about this or log it,
1254
-                // it's ok to deregister an add-on before its registered in the registry
1255
-            } catch (Exception $e) {
1256
-                new ExceptionLogger($e);
1257
-            }
1258
-            unset(self::$_settings[ $addon_name ]);
1259
-            do_action('AHEE__EE_Register_Addon__deregister__after', $addon_name);
1260
-        }
1261
-    }
26
+	/**
27
+	 * possibly truncated version of the EE core version string
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected static $_core_version = '';
32
+
33
+	/**
34
+	 * Holds values for registered addons
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected static $_settings = array();
39
+
40
+	/**
41
+	 * @var  array $_incompatible_addons keys are addon SLUGS
42
+	 * (first argument passed to EE_Register_Addon::register()), keys are
43
+	 * their MINIMUM VERSION (with all 5 parts. Eg 1.2.3.rc.004).
44
+	 * Generally this should be used sparingly, as we don't want to muddle up
45
+	 * EE core with knowledge of ALL the addons out there.
46
+	 * If you want NO versions of an addon to run with a certain version of core,
47
+	 * it's usually best to define the addon's "min_core_version" as part of its call
48
+	 * to EE_Register_Addon::register(), rather than using this array with a super high value for its
49
+	 * minimum plugin version.
50
+	 * @access    protected
51
+	 */
52
+	protected static $_incompatible_addons = array(
53
+		'Multi_Event_Registration' => '2.0.11.rc.002',
54
+		'Promotions'               => '1.0.0.rc.084',
55
+	);
56
+
57
+
58
+	/**
59
+	 * We should always be comparing core to a version like '4.3.0.rc.000',
60
+	 * not just '4.3.0'.
61
+	 * So if the addon developer doesn't provide that full version string,
62
+	 * fill in the blanks for them
63
+	 *
64
+	 * @param string $min_core_version
65
+	 * @return string always like '4.3.0.rc.000'
66
+	 */
67
+	protected static function _effective_version($min_core_version)
68
+	{
69
+		// versions: 4 . 3 . 1 . p . 123
70
+		// offsets:    0 . 1 . 2 . 3 . 4
71
+		$version_parts = explode('.', $min_core_version);
72
+		// check they specified the micro version (after 2nd period)
73
+		if (! isset($version_parts[2])) {
74
+			$version_parts[2] = '0';
75
+		}
76
+		// if they didn't specify the 'p', or 'rc' part. Just assume the lowest possible
77
+		// soon we can assume that's 'rc', but this current version is 'alpha'
78
+		if (! isset($version_parts[3])) {
79
+			$version_parts[3] = 'dev';
80
+		}
81
+		if (! isset($version_parts[4])) {
82
+			$version_parts[4] = '000';
83
+		}
84
+		return implode('.', $version_parts);
85
+	}
86
+
87
+
88
+	/**
89
+	 * Returns whether or not the min core version requirement of the addon is met
90
+	 *
91
+	 * @param string $min_core_version    the minimum core version required by the addon
92
+	 * @param string $actual_core_version the actual core version, optional
93
+	 * @return boolean
94
+	 */
95
+	public static function _meets_min_core_version_requirement(
96
+		$min_core_version,
97
+		$actual_core_version = EVENT_ESPRESSO_VERSION
98
+	) {
99
+		return version_compare(
100
+			self::_effective_version($actual_core_version),
101
+			self::_effective_version($min_core_version),
102
+			'>='
103
+		);
104
+	}
105
+
106
+
107
+	/**
108
+	 * Method for registering new EE_Addons.
109
+	 * Should be called AFTER AHEE__EE_System__load_espresso_addons but BEFORE
110
+	 * AHEE__EE_System___detect_if_activation_or_upgrade__begin in order to register all its components. However, it
111
+	 * may also be called after the 'activate_plugin' action (when an addon is activated), because an activating addon
112
+	 * won't be loaded by WP until after AHEE__EE_System__load_espresso_addons has fired. If its called after
113
+	 * 'activate_plugin', it registers the addon still, but its components are not registered
114
+	 * (they shouldn't be needed anyways, because it's just an activation request and they won't have a chance to do
115
+	 * anything anyways). Instead, it just sets the newly-activated addon's activation indicator wp option and returns
116
+	 * (so that we can detect that the addon has activated on the subsequent request)
117
+	 *
118
+	 * @since    4.3.0
119
+	 * @param string                  $addon_name                       [Required] the EE_Addon's name.
120
+	 * @param  array                  $setup_args                       {
121
+	 *                                                                  An array of arguments provided for registering
122
+	 *                                                                  the message type.
123
+	 * @type  string                  $class_name                       the addon's main file name.
124
+	 *                                                                  If left blank, generated from the addon name,
125
+	 *                                                                  changes something like "calendar" to
126
+	 *                                                                  "EE_Calendar"
127
+	 * @type string                   $min_core_version                 the minimum version of EE Core that the
128
+	 *                                                                  addon will work with. eg "4.8.1.rc.084"
129
+	 * @type string                   $version                          the "software" version for the addon. eg
130
+	 *                                                                  "1.0.0.p" for a first stable release, or
131
+	 *                                                                  "1.0.0.rc.043" for a version in progress
132
+	 * @type string                   $main_file_path                   the full server path to the main file
133
+	 *                                                                  loaded directly by WP
134
+	 * @type DomainInterface $domain                                    child class of
135
+	 *                                                                  EventEspresso\core\domain\DomainBase
136
+	 * @type string                   $domain_fqcn                      Fully Qualified Class Name
137
+	 *                                                                  for the addon's Domain class
138
+	 *                                                                  (see EventEspresso\core\domain\Domain)
139
+	 * @type string                   $admin_path                       full server path to the folder where the
140
+	 *                                                                  addon\'s admin files reside
141
+	 * @type string                   $admin_callback                   a method to be called when the EE Admin is
142
+	 *                                                                  first invoked, can be used for hooking into
143
+	 *                                                                  any admin page
144
+	 * @type string                   $config_section                   the section name for this addon's
145
+	 *                                                                  configuration settings section
146
+	 *                                                                  (defaults to "addons")
147
+	 * @type string                   $config_class                     the class name for this addon's
148
+	 *                                                                  configuration settings object
149
+	 * @type string                   $config_name                      the class name for this addon's
150
+	 *                                                                  configuration settings object
151
+	 * @type string                   $autoloader_paths                 [Required] an array of class names and the full
152
+	 *                                                                  server paths to those files.
153
+	 * @type string                   $autoloader_folders               an array of  "full server paths" for any
154
+	 *                                                                  folders containing classes that might be
155
+	 *                                                                  invoked by the addon
156
+	 * @type string                   $dms_paths                        [Required] an array of full server paths to
157
+	 *                                                                  folders that contain data migration scripts.
158
+	 *                                                                  The key should be the EE_Addon class name that
159
+	 *                                                                  this set of data migration scripts belongs to.
160
+	 *                                                                  If the EE_Addon class is namespaced, then this
161
+	 *                                                                  needs to be the Fully Qualified Class Name
162
+	 * @type string                   $module_paths                     an array of full server paths to any
163
+	 *                                                                  EED_Modules used by the addon
164
+	 * @type string                   $shortcode_paths                  an array of full server paths to folders
165
+	 *                                                                  that contain EES_Shortcodes
166
+	 * @type string                   $widget_paths                     an array of full server paths to folders
167
+	 *                                                                  that contain WP_Widgets
168
+	 * @type string                   $pue_options
169
+	 * @type array                    $capabilities                     an array indexed by role name
170
+	 *                                                                  (i.e administrator,author ) and the values
171
+	 *                                                                  are an array of caps to add to the role.
172
+	 *                                                                  'administrator' => array(
173
+	 *                                                                  'read_addon',
174
+	 *                                                                  'edit_addon',
175
+	 *                                                                  etc.
176
+	 *                                                                  ).
177
+	 * @type EE_Meta_Capability_Map[] $capability_maps                  an array of EE_Meta_Capability_Map object
178
+	 *                                                                  for any addons that need to register any
179
+	 *                                                                  special meta mapped capabilities.  Should
180
+	 *                                                                  be indexed where the key is the
181
+	 *                                                                  EE_Meta_Capability_Map class name and the
182
+	 *                                                                  values are the arguments sent to the class.
183
+	 * @type array                    $model_paths                      array of folders containing DB models
184
+	 * @see      EE_Register_Model
185
+	 * @type array                    $class_paths                      array of folders containing DB classes
186
+	 * @see      EE_Register_Model
187
+	 * @type array                    $model_extension_paths            array of folders containing DB model
188
+	 *                                                                  extensions
189
+	 * @see      EE_Register_Model_Extension
190
+	 * @type array                    $class_extension_paths            array of folders containing DB class
191
+	 *                                                                  extensions
192
+	 * @see      EE_Register_Model_Extension
193
+	 * @type array message_types {
194
+	 *                                                                  An array of message types with the key as
195
+	 *                                                                  the message type name and the values as
196
+	 *                                                                  below:
197
+	 * @type string                   $mtfilename                       [Required] The filename of the message type
198
+	 *                                                                  being registered. This will be the main
199
+	 *                                                                  EE_{Message Type Name}_message_type class.
200
+	 *                                                                  for example:
201
+	 *                                                                  EE_Declined_Registration_message_type.class.php
202
+	 * @type array                    $autoloadpaths                    [Required] An array of paths to add to the
203
+	 *                                                                  messages autoloader for the new message type.
204
+	 * @type array                    $messengers_to_activate_with      An array of messengers that this message
205
+	 *                                                                  type should activate with. Each value in
206
+	 *                                                                  the
207
+	 *                                                                  array
208
+	 *                                                                  should match the name property of a
209
+	 *                                                                  EE_messenger. Optional.
210
+	 * @type array                    $messengers_to_validate_with      An array of messengers that this message
211
+	 *                                                                  type should validate with. Each value in
212
+	 *                                                                  the
213
+	 *                                                                  array
214
+	 *                                                                  should match the name property of an
215
+	 *                                                                  EE_messenger.
216
+	 *                                                                  Optional.
217
+	 *                                                                  }
218
+	 * @type array                    $custom_post_types
219
+	 * @type array                    $custom_taxonomies
220
+	 * @type array                    $payment_method_paths             each element is the folder containing the
221
+	 *                                                                  EE_PMT_Base child class
222
+	 *                                                                  (eg,
223
+	 *                                                                  '/wp-content/plugins/my_plugin/Payomatic/'
224
+	 *                                                                  which contains the files
225
+	 *                                                                  EE_PMT_Payomatic.pm.php)
226
+	 * @type array                    $default_terms
227
+	 * @type array                    $namespace                        {
228
+	 *                                                                  An array with two items for registering the
229
+	 *                                                                  addon's namespace. (If, for some reason, you
230
+	 *                                                                  require additional namespaces,
231
+	 *                                                                  use
232
+	 *                                                                  EventEspresso\core\Psr4Autoloader::addNamespace()
233
+	 *                                                                  directly)
234
+	 * @see      EventEspresso\core\Psr4Autoloader::addNamespace()
235
+	 * @type string                   $FQNS                             the namespace prefix
236
+	 * @type string                   $DIR                              a base directory for class files in the
237
+	 *                                                                  namespace.
238
+	 *                                                                  }
239
+	 *                                                                  }
240
+	 * @type string                   $privacy_policies                 FQNSs (namespaces, each of which contains only
241
+	 *                                                                  privacy policy classes) or FQCNs (specific
242
+	 *                                                                  classnames of privacy policy classes)
243
+	 * @type string                   $personal_data_exporters          FQNSs (namespaces, each of which contains only
244
+	 *                                                                  privacy policy classes) or FQCNs (specific
245
+	 *                                                                  classnames of privacy policy classes)
246
+	 * @type string                   $personal_data_erasers            FQNSs (namespaces, each of which contains only
247
+	 *                                                                  privacy policy classes) or FQCNs (specific
248
+	 *                                                                  classnames of privacy policy classes)
249
+	 * @return void
250
+	 * @throws DomainException
251
+	 * @throws EE_Error
252
+	 * @throws InvalidArgumentException
253
+	 * @throws InvalidDataTypeException
254
+	 * @throws InvalidInterfaceException
255
+	 */
256
+	public static function register($addon_name = '', array $setup_args = array())
257
+	{
258
+		// required fields MUST be present, so let's make sure they are.
259
+		EE_Register_Addon::_verify_parameters($addon_name, $setup_args);
260
+		// get class name for addon
261
+		$class_name = EE_Register_Addon::_parse_class_name($addon_name, $setup_args);
262
+		// setup $_settings array from incoming values.
263
+		$addon_settings = EE_Register_Addon::_get_addon_settings($class_name, $setup_args);
264
+		// setup PUE
265
+		EE_Register_Addon::_parse_pue_options($addon_name, $class_name, $setup_args);
266
+		// does this addon work with this version of core or WordPress ?
267
+		// does this addon work with this version of core or WordPress ?
268
+		if (! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
269
+			return;
270
+		}
271
+		// register namespaces
272
+		EE_Register_Addon::_setup_namespaces($addon_settings);
273
+		// check if this is an activation request
274
+		if (EE_Register_Addon::_addon_activation($addon_name, $addon_settings)) {
275
+			// dont bother setting up the rest of the addon atm
276
+			return;
277
+		}
278
+		// we need cars
279
+		EE_Register_Addon::_setup_autoloaders($addon_name);
280
+		// register new models and extensions
281
+		EE_Register_Addon::_register_models_and_extensions($addon_name);
282
+		// setup DMS
283
+		EE_Register_Addon::_register_data_migration_scripts($addon_name);
284
+		// if config_class is present let's register config.
285
+		EE_Register_Addon::_register_config($addon_name);
286
+		// register admin pages
287
+		EE_Register_Addon::_register_admin_pages($addon_name);
288
+		// add to list of modules to be registered
289
+		EE_Register_Addon::_register_modules($addon_name);
290
+		// add to list of shortcodes to be registered
291
+		EE_Register_Addon::_register_shortcodes($addon_name);
292
+		// add to list of widgets to be registered
293
+		EE_Register_Addon::_register_widgets($addon_name);
294
+		// register capability related stuff.
295
+		EE_Register_Addon::_register_capabilities($addon_name);
296
+		// any message type to register?
297
+		EE_Register_Addon::_register_message_types($addon_name);
298
+		// any custom post type/ custom capabilities or default terms to register
299
+		EE_Register_Addon::_register_custom_post_types($addon_name);
300
+		// and any payment methods
301
+		EE_Register_Addon::_register_payment_methods($addon_name);
302
+		// and privacy policy generators
303
+		EE_Register_Addon::registerPrivacyPolicies($addon_name);
304
+		// and privacy policy generators
305
+		EE_Register_Addon::registerPersonalDataExporters($addon_name);
306
+		// and privacy policy generators
307
+		EE_Register_Addon::registerPersonalDataErasers($addon_name);
308
+		// load and instantiate main addon class
309
+		$addon = EE_Register_Addon::_load_and_init_addon_class($addon_name);
310
+		// delay calling after_registration hook on each addon until after all add-ons have been registered.
311
+		add_action('AHEE__EE_System__load_espresso_addons__complete', array($addon, 'after_registration'), 999);
312
+	}
313
+
314
+
315
+	/**
316
+	 * @param string $addon_name
317
+	 * @param array  $setup_args
318
+	 * @return void
319
+	 * @throws EE_Error
320
+	 */
321
+	private static function _verify_parameters($addon_name, array $setup_args)
322
+	{
323
+		// required fields MUST be present, so let's make sure they are.
324
+		if (empty($addon_name) || ! is_array($setup_args)) {
325
+			throw new EE_Error(
326
+				__(
327
+					'In order to register an EE_Addon with EE_Register_Addon::register(), you must include the "addon_name" (the name of the addon), and an array of arguments.',
328
+					'event_espresso'
329
+				)
330
+			);
331
+		}
332
+		if (! isset($setup_args['main_file_path']) || empty($setup_args['main_file_path'])) {
333
+			throw new EE_Error(
334
+				sprintf(
335
+					__(
336
+						'When registering an addon, you didn\'t provide the "main_file_path", which is the full path to the main file loaded directly by Wordpress. You only provided %s',
337
+						'event_espresso'
338
+					),
339
+					implode(',', array_keys($setup_args))
340
+				)
341
+			);
342
+		}
343
+		// check that addon has not already been registered with that name
344
+		if (isset(self::$_settings[ $addon_name ]) && ! did_action('activate_plugin')) {
345
+			throw new EE_Error(
346
+				sprintf(
347
+					__(
348
+						'An EE_Addon with the name "%s" has already been registered and each EE_Addon requires a unique name.',
349
+						'event_espresso'
350
+					),
351
+					$addon_name
352
+				)
353
+			);
354
+		}
355
+	}
356
+
357
+
358
+	/**
359
+	 * @param string $addon_name
360
+	 * @param array  $setup_args
361
+	 * @return string
362
+	 */
363
+	private static function _parse_class_name($addon_name, array $setup_args)
364
+	{
365
+		if (empty($setup_args['class_name'])) {
366
+			// generate one by first separating name with spaces
367
+			$class_name = str_replace(array('-', '_'), ' ', trim($addon_name));
368
+			// capitalize, then replace spaces with underscores
369
+			$class_name = str_replace(' ', '_', ucwords($class_name));
370
+		} else {
371
+			$class_name = $setup_args['class_name'];
372
+		}
373
+		// check if classname is fully  qualified or is a legacy classname already prefixed with 'EE_'
374
+		return strpos($class_name, '\\') || strpos($class_name, 'EE_') === 0
375
+			? $class_name
376
+			: 'EE_' . $class_name;
377
+	}
378
+
379
+
380
+	/**
381
+	 * @param string $class_name
382
+	 * @param array  $setup_args
383
+	 * @return array
384
+	 */
385
+	private static function _get_addon_settings($class_name, array $setup_args)
386
+	{
387
+		// setup $_settings array from incoming values.
388
+		$addon_settings = array(
389
+			// generated from the addon name, changes something like "calendar" to "EE_Calendar"
390
+			'class_name'            => $class_name,
391
+			// the addon slug for use in URLs, etc
392
+			'plugin_slug'           => isset($setup_args['plugin_slug'])
393
+				? (string) $setup_args['plugin_slug']
394
+				: '',
395
+			// page slug to be used when generating the "Settings" link on the WP plugin page
396
+			'plugin_action_slug'    => isset($setup_args['plugin_action_slug'])
397
+				? (string) $setup_args['plugin_action_slug']
398
+				: '',
399
+			// the "software" version for the addon
400
+			'version'               => isset($setup_args['version'])
401
+				? (string) $setup_args['version']
402
+				: '',
403
+			// the minimum version of EE Core that the addon will work with
404
+			'min_core_version'      => isset($setup_args['min_core_version'])
405
+				? (string) $setup_args['min_core_version']
406
+				: '',
407
+			// the minimum version of WordPress that the addon will work with
408
+			'min_wp_version'        => isset($setup_args['min_wp_version'])
409
+				? (string) $setup_args['min_wp_version']
410
+				: EE_MIN_WP_VER_REQUIRED,
411
+			// full server path to main file (file loaded directly by WP)
412
+			'main_file_path'        => isset($setup_args['main_file_path'])
413
+				? (string) $setup_args['main_file_path']
414
+				: '',
415
+			// instance of \EventEspresso\core\domain\DomainInterface
416
+			'domain'                => isset($setup_args['domain']) && $setup_args['domain'] instanceof DomainInterface
417
+				? $setup_args['domain']
418
+				: null,
419
+			// Fully Qualified Class Name for the addon's Domain class
420
+			'domain_fqcn'           => isset($setup_args['domain_fqcn'])
421
+				? (string) $setup_args['domain_fqcn']
422
+				: '',
423
+			// path to folder containing files for integrating with the EE core admin and/or setting up EE admin pages
424
+			'admin_path'            => isset($setup_args['admin_path'])
425
+				? (string) $setup_args['admin_path'] : '',
426
+			// a method to be called when the EE Admin is first invoked, can be used for hooking into any admin page
427
+			'admin_callback'        => isset($setup_args['admin_callback'])
428
+				? (string) $setup_args['admin_callback']
429
+				: '',
430
+			// the section name for this addon's configuration settings section (defaults to "addons")
431
+			'config_section'        => isset($setup_args['config_section'])
432
+				? (string) $setup_args['config_section']
433
+				: 'addons',
434
+			// the class name for this addon's configuration settings object
435
+			'config_class'          => isset($setup_args['config_class'])
436
+				? (string) $setup_args['config_class'] : '',
437
+			// the name given to the config for this addons' configuration settings object (optional)
438
+			'config_name'           => isset($setup_args['config_name'])
439
+				? (string) $setup_args['config_name'] : '',
440
+			// an array of "class names" => "full server paths" for any classes that might be invoked by the addon
441
+			'autoloader_paths'      => isset($setup_args['autoloader_paths'])
442
+				? (array) $setup_args['autoloader_paths']
443
+				: array(),
444
+			// an array of  "full server paths" for any folders containing classes that might be invoked by the addon
445
+			'autoloader_folders'    => isset($setup_args['autoloader_folders'])
446
+				? (array) $setup_args['autoloader_folders']
447
+				: array(),
448
+			// array of full server paths to any EE_DMS data migration scripts used by the addon.
449
+			// The key should be the EE_Addon class name that this set of data migration scripts belongs to.
450
+			// If the EE_Addon class is namespaced, then this needs to be the Fully Qualified Class Name
451
+			'dms_paths'             => isset($setup_args['dms_paths'])
452
+				? (array) $setup_args['dms_paths']
453
+				: array(),
454
+			// array of full server paths to any EED_Modules used by the addon
455
+			'module_paths'          => isset($setup_args['module_paths'])
456
+				? (array) $setup_args['module_paths']
457
+				: array(),
458
+			// array of full server paths to any EES_Shortcodes used by the addon
459
+			'shortcode_paths'       => isset($setup_args['shortcode_paths'])
460
+				? (array) $setup_args['shortcode_paths']
461
+				: array(),
462
+			'shortcode_fqcns'       => isset($setup_args['shortcode_fqcns'])
463
+				? (array) $setup_args['shortcode_fqcns']
464
+				: array(),
465
+			// array of full server paths to any WP_Widgets used by the addon
466
+			'widget_paths'          => isset($setup_args['widget_paths'])
467
+				? (array) $setup_args['widget_paths']
468
+				: array(),
469
+			// array of PUE options used by the addon
470
+			'pue_options'           => isset($setup_args['pue_options'])
471
+				? (array) $setup_args['pue_options']
472
+				: array(),
473
+			'message_types'         => isset($setup_args['message_types'])
474
+				? (array) $setup_args['message_types']
475
+				: array(),
476
+			'capabilities'          => isset($setup_args['capabilities'])
477
+				? (array) $setup_args['capabilities']
478
+				: array(),
479
+			'capability_maps'       => isset($setup_args['capability_maps'])
480
+				? (array) $setup_args['capability_maps']
481
+				: array(),
482
+			'model_paths'           => isset($setup_args['model_paths'])
483
+				? (array) $setup_args['model_paths']
484
+				: array(),
485
+			'class_paths'           => isset($setup_args['class_paths'])
486
+				? (array) $setup_args['class_paths']
487
+				: array(),
488
+			'model_extension_paths' => isset($setup_args['model_extension_paths'])
489
+				? (array) $setup_args['model_extension_paths']
490
+				: array(),
491
+			'class_extension_paths' => isset($setup_args['class_extension_paths'])
492
+				? (array) $setup_args['class_extension_paths']
493
+				: array(),
494
+			'custom_post_types'     => isset($setup_args['custom_post_types'])
495
+				? (array) $setup_args['custom_post_types']
496
+				: array(),
497
+			'custom_taxonomies'     => isset($setup_args['custom_taxonomies'])
498
+				? (array) $setup_args['custom_taxonomies']
499
+				: array(),
500
+			'payment_method_paths'  => isset($setup_args['payment_method_paths'])
501
+				? (array) $setup_args['payment_method_paths']
502
+				: array(),
503
+			'default_terms'         => isset($setup_args['default_terms'])
504
+				? (array) $setup_args['default_terms']
505
+				: array(),
506
+			// if not empty, inserts a new table row after this plugin's row on the WP Plugins page
507
+			// that can be used for adding upgrading/marketing info
508
+			'plugins_page_row'      => isset($setup_args['plugins_page_row']) ? $setup_args['plugins_page_row'] : '',
509
+			'namespace'             => isset(
510
+				$setup_args['namespace']['FQNS'],
511
+				$setup_args['namespace']['DIR']
512
+			)
513
+				? (array) $setup_args['namespace']
514
+				: array(),
515
+			'privacy_policies'      => isset($setup_args['privacy_policies'])
516
+				? (array) $setup_args['privacy_policies']
517
+				: '',
518
+		);
519
+		// if plugin_action_slug is NOT set, but an admin page path IS set,
520
+		// then let's just use the plugin_slug since that will be used for linking to the admin page
521
+		$addon_settings['plugin_action_slug'] = empty($addon_settings['plugin_action_slug'])
522
+												&& ! empty($addon_settings['admin_path'])
523
+			? $addon_settings['plugin_slug']
524
+			: $addon_settings['plugin_action_slug'];
525
+		// full server path to main file (file loaded directly by WP)
526
+		$addon_settings['plugin_basename'] = plugin_basename($addon_settings['main_file_path']);
527
+		return $addon_settings;
528
+	}
529
+
530
+
531
+	/**
532
+	 * @param string $addon_name
533
+	 * @param array  $addon_settings
534
+	 * @return boolean
535
+	 */
536
+	private static function _addon_is_compatible($addon_name, array $addon_settings)
537
+	{
538
+		global $wp_version;
539
+		$incompatibility_message = '';
540
+		// check whether this addon version is compatible with EE core
541
+		if (isset(EE_Register_Addon::$_incompatible_addons[ $addon_name ])
542
+			&& ! self::_meets_min_core_version_requirement(
543
+				EE_Register_Addon::$_incompatible_addons[ $addon_name ],
544
+				$addon_settings['version']
545
+			)
546
+		) {
547
+			$incompatibility_message = sprintf(
548
+				__(
549
+					'%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon is not compatible with this version of Event Espresso.%2$sPlease upgrade your "%1$s" addon to version %3$s or newer to resolve this issue.',
550
+					'event_espresso'
551
+				),
552
+				$addon_name,
553
+				'<br />',
554
+				EE_Register_Addon::$_incompatible_addons[ $addon_name ],
555
+				'<span style="font-weight: bold; color: #D54E21;">',
556
+				'</span><br />'
557
+			);
558
+		} elseif (! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
559
+		) {
560
+			$incompatibility_message = sprintf(
561
+				__(
562
+					'%5$sIMPORTANT!%6$sThe Event Espresso "%1$s" addon requires Event Espresso Core version "%2$s" or higher in order to run.%4$sYour version of Event Espresso Core is currently at "%3$s". Please upgrade Event Espresso Core first and then re-activate "%1$s".',
563
+					'event_espresso'
564
+				),
565
+				$addon_name,
566
+				self::_effective_version($addon_settings['min_core_version']),
567
+				self::_effective_version(espresso_version()),
568
+				'<br />',
569
+				'<span style="font-weight: bold; color: #D54E21;">',
570
+				'</span><br />'
571
+			);
572
+		} elseif (version_compare($wp_version, $addon_settings['min_wp_version'], '<')) {
573
+			$incompatibility_message = sprintf(
574
+				__(
575
+					'%4$sIMPORTANT!%5$sThe Event Espresso "%1$s" addon requires WordPress version "%2$s" or greater.%3$sPlease update your version of WordPress to use the "%1$s" addon and to keep your site secure.',
576
+					'event_espresso'
577
+				),
578
+				$addon_name,
579
+				$addon_settings['min_wp_version'],
580
+				'<br />',
581
+				'<span style="font-weight: bold; color: #D54E21;">',
582
+				'</span><br />'
583
+			);
584
+		}
585
+		if (! empty($incompatibility_message)) {
586
+			// remove 'activate' from the REQUEST
587
+			// so WP doesn't erroneously tell the user the plugin activated fine when it didn't
588
+			/** @var RequestInterface $request */
589
+			$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
590
+			$request->unSetRequestParam('activate', true);
591
+			if (current_user_can('activate_plugins')) {
592
+				// show an error message indicating the plugin didn't activate properly
593
+				EE_Error::add_error($incompatibility_message, __FILE__, __FUNCTION__, __LINE__);
594
+			}
595
+			// BAIL FROM THE ADDON REGISTRATION PROCESS
596
+			return false;
597
+		}
598
+		// addon IS compatible
599
+		return true;
600
+	}
601
+
602
+
603
+	/**
604
+	 * if plugin update engine is being used for auto-updates,
605
+	 * then let's set that up now before going any further so that ALL addons can be updated
606
+	 * (not needed if PUE is not being used)
607
+	 *
608
+	 * @param string $addon_name
609
+	 * @param string $class_name
610
+	 * @param array  $setup_args
611
+	 * @return void
612
+	 */
613
+	private static function _parse_pue_options($addon_name, $class_name, array $setup_args)
614
+	{
615
+		if (! empty($setup_args['pue_options'])) {
616
+			self::$_settings[ $addon_name ]['pue_options'] = array(
617
+				'pue_plugin_slug' => isset($setup_args['pue_options']['pue_plugin_slug'])
618
+					? (string) $setup_args['pue_options']['pue_plugin_slug']
619
+					: 'espresso_' . strtolower($class_name),
620
+				'plugin_basename' => isset($setup_args['pue_options']['plugin_basename'])
621
+					? (string) $setup_args['pue_options']['plugin_basename']
622
+					: plugin_basename($setup_args['main_file_path']),
623
+				'checkPeriod'     => isset($setup_args['pue_options']['checkPeriod'])
624
+					? (string) $setup_args['pue_options']['checkPeriod']
625
+					: '24',
626
+				'use_wp_update'   => isset($setup_args['pue_options']['use_wp_update'])
627
+					? (string) $setup_args['pue_options']['use_wp_update']
628
+					: false,
629
+			);
630
+			add_action(
631
+				'AHEE__EE_System__brew_espresso__after_pue_init',
632
+				array('EE_Register_Addon', 'load_pue_update')
633
+			);
634
+		}
635
+	}
636
+
637
+
638
+	/**
639
+	 * register namespaces right away before any other files or classes get loaded, but AFTER the version checks
640
+	 *
641
+	 * @param array $addon_settings
642
+	 * @return void
643
+	 */
644
+	private static function _setup_namespaces(array $addon_settings)
645
+	{
646
+		//
647
+		if (isset(
648
+			$addon_settings['namespace']['FQNS'],
649
+			$addon_settings['namespace']['DIR']
650
+		)) {
651
+			EE_Psr4AutoloaderInit::psr4_loader()->addNamespace(
652
+				$addon_settings['namespace']['FQNS'],
653
+				$addon_settings['namespace']['DIR']
654
+			);
655
+		}
656
+	}
657
+
658
+
659
+	/**
660
+	 * @param string $addon_name
661
+	 * @param array  $addon_settings
662
+	 * @return bool
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws InvalidInterfaceException
666
+	 */
667
+	private static function _addon_activation($addon_name, array $addon_settings)
668
+	{
669
+		// this is an activation request
670
+		if (did_action('activate_plugin')) {
671
+			// to find if THIS is the addon that was activated, just check if we have already registered it or not
672
+			// (as the newly-activated addon wasn't around the first time addons were registered).
673
+			// Note: the presence of pue_options in the addon registration options will initialize the $_settings
674
+			// property for the add-on, but the add-on is only partially initialized.  Hence, the additional check.
675
+			if (! isset(self::$_settings[ $addon_name ])
676
+				|| (isset(self::$_settings[ $addon_name ])
677
+					&& ! isset(self::$_settings[ $addon_name ]['class_name'])
678
+				)
679
+			) {
680
+				self::$_settings[ $addon_name ] = $addon_settings;
681
+				$addon = self::_load_and_init_addon_class($addon_name);
682
+				$addon->set_activation_indicator_option();
683
+				// dont bother setting up the rest of the addon.
684
+				// we know it was just activated and the request will end soon
685
+			}
686
+			return true;
687
+		}
688
+		// make sure this was called in the right place!
689
+		if (! did_action('AHEE__EE_System__load_espresso_addons')
690
+			|| did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')
691
+		) {
692
+			EE_Error::doing_it_wrong(
693
+				__METHOD__,
694
+				sprintf(
695
+					__(
696
+						'An attempt to register an EE_Addon named "%s" has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__load_espresso_addons" hook to register addons.',
697
+						'event_espresso'
698
+					),
699
+					$addon_name
700
+				),
701
+				'4.3.0'
702
+			);
703
+		}
704
+		// make sure addon settings are set correctly without overwriting anything existing
705
+		if (isset(self::$_settings[ $addon_name ])) {
706
+			self::$_settings[ $addon_name ] += $addon_settings;
707
+		} else {
708
+			self::$_settings[ $addon_name ] = $addon_settings;
709
+		}
710
+		return false;
711
+	}
712
+
713
+
714
+	/**
715
+	 * @param string $addon_name
716
+	 * @return void
717
+	 * @throws EE_Error
718
+	 */
719
+	private static function _setup_autoloaders($addon_name)
720
+	{
721
+		if (! empty(self::$_settings[ $addon_name ]['autoloader_paths'])) {
722
+			// setup autoloader for single file
723
+			EEH_Autoloader::instance()->register_autoloader(self::$_settings[ $addon_name ]['autoloader_paths']);
724
+		}
725
+		// setup autoloaders for folders
726
+		if (! empty(self::$_settings[ $addon_name ]['autoloader_folders'])) {
727
+			foreach ((array) self::$_settings[ $addon_name ]['autoloader_folders'] as $autoloader_folder) {
728
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($autoloader_folder);
729
+			}
730
+		}
731
+	}
732
+
733
+
734
+	/**
735
+	 * register new models and extensions
736
+	 *
737
+	 * @param string $addon_name
738
+	 * @return void
739
+	 * @throws EE_Error
740
+	 */
741
+	private static function _register_models_and_extensions($addon_name)
742
+	{
743
+		// register new models
744
+		if (! empty(self::$_settings[ $addon_name ]['model_paths'])
745
+			|| ! empty(self::$_settings[ $addon_name ]['class_paths'])
746
+		) {
747
+			EE_Register_Model::register(
748
+				$addon_name,
749
+				array(
750
+					'model_paths' => self::$_settings[ $addon_name ]['model_paths'],
751
+					'class_paths' => self::$_settings[ $addon_name ]['class_paths'],
752
+				)
753
+			);
754
+		}
755
+		// register model extensions
756
+		if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
757
+			|| ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
758
+		) {
759
+			EE_Register_Model_Extensions::register(
760
+				$addon_name,
761
+				array(
762
+					'model_extension_paths' => self::$_settings[ $addon_name ]['model_extension_paths'],
763
+					'class_extension_paths' => self::$_settings[ $addon_name ]['class_extension_paths'],
764
+				)
765
+			);
766
+		}
767
+	}
768
+
769
+
770
+	/**
771
+	 * @param string $addon_name
772
+	 * @return void
773
+	 * @throws EE_Error
774
+	 */
775
+	private static function _register_data_migration_scripts($addon_name)
776
+	{
777
+		// setup DMS
778
+		if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
779
+			EE_Register_Data_Migration_Scripts::register(
780
+				$addon_name,
781
+				array('dms_paths' => self::$_settings[ $addon_name ]['dms_paths'])
782
+			);
783
+		}
784
+	}
785
+
786
+
787
+	/**
788
+	 * @param string $addon_name
789
+	 * @return void
790
+	 * @throws EE_Error
791
+	 */
792
+	private static function _register_config($addon_name)
793
+	{
794
+		// if config_class is present let's register config.
795
+		if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
796
+			EE_Register_Config::register(
797
+				self::$_settings[ $addon_name ]['config_class'],
798
+				array(
799
+					'config_section' => self::$_settings[ $addon_name ]['config_section'],
800
+					'config_name'    => self::$_settings[ $addon_name ]['config_name'],
801
+				)
802
+			);
803
+		}
804
+	}
805
+
806
+
807
+	/**
808
+	 * @param string $addon_name
809
+	 * @return void
810
+	 * @throws EE_Error
811
+	 */
812
+	private static function _register_admin_pages($addon_name)
813
+	{
814
+		if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
815
+			EE_Register_Admin_Page::register(
816
+				$addon_name,
817
+				array('page_path' => self::$_settings[ $addon_name ]['admin_path'])
818
+			);
819
+		}
820
+	}
821
+
822
+
823
+	/**
824
+	 * @param string $addon_name
825
+	 * @return void
826
+	 * @throws EE_Error
827
+	 */
828
+	private static function _register_modules($addon_name)
829
+	{
830
+		if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
831
+			EE_Register_Module::register(
832
+				$addon_name,
833
+				array('module_paths' => self::$_settings[ $addon_name ]['module_paths'])
834
+			);
835
+		}
836
+	}
837
+
838
+
839
+	/**
840
+	 * @param string $addon_name
841
+	 * @return void
842
+	 * @throws EE_Error
843
+	 */
844
+	private static function _register_shortcodes($addon_name)
845
+	{
846
+		if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
847
+			|| ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
848
+		) {
849
+			EE_Register_Shortcode::register(
850
+				$addon_name,
851
+				array(
852
+					'shortcode_paths' => isset(self::$_settings[ $addon_name ]['shortcode_paths'])
853
+						? self::$_settings[ $addon_name ]['shortcode_paths'] : array(),
854
+					'shortcode_fqcns' => isset(self::$_settings[ $addon_name ]['shortcode_fqcns'])
855
+						? self::$_settings[ $addon_name ]['shortcode_fqcns'] : array(),
856
+				)
857
+			);
858
+		}
859
+	}
860
+
861
+
862
+	/**
863
+	 * @param string $addon_name
864
+	 * @return void
865
+	 * @throws EE_Error
866
+	 */
867
+	private static function _register_widgets($addon_name)
868
+	{
869
+		if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
870
+			EE_Register_Widget::register(
871
+				$addon_name,
872
+				array('widget_paths' => self::$_settings[ $addon_name ]['widget_paths'])
873
+			);
874
+		}
875
+	}
876
+
877
+
878
+	/**
879
+	 * @param string $addon_name
880
+	 * @return void
881
+	 * @throws EE_Error
882
+	 */
883
+	private static function _register_capabilities($addon_name)
884
+	{
885
+		if (! empty(self::$_settings[ $addon_name ]['capabilities'])) {
886
+			EE_Register_Capabilities::register(
887
+				$addon_name,
888
+				array(
889
+					'capabilities'    => self::$_settings[ $addon_name ]['capabilities'],
890
+					'capability_maps' => self::$_settings[ $addon_name ]['capability_maps'],
891
+				)
892
+			);
893
+		}
894
+	}
895
+
896
+
897
+	/**
898
+	 * @param string $addon_name
899
+	 * @return void
900
+	 */
901
+	private static function _register_message_types($addon_name)
902
+	{
903
+		if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
904
+			add_action(
905
+				'EE_Brewing_Regular___messages_caf',
906
+				array('EE_Register_Addon', 'register_message_types')
907
+			);
908
+		}
909
+	}
910
+
911
+
912
+	/**
913
+	 * @param string $addon_name
914
+	 * @return void
915
+	 * @throws EE_Error
916
+	 */
917
+	private static function _register_custom_post_types($addon_name)
918
+	{
919
+		if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])
920
+			|| ! empty(self::$_settings[ $addon_name ]['custom_taxonomies'])
921
+		) {
922
+			EE_Register_CPT::register(
923
+				$addon_name,
924
+				array(
925
+					'cpts'          => self::$_settings[ $addon_name ]['custom_post_types'],
926
+					'cts'           => self::$_settings[ $addon_name ]['custom_taxonomies'],
927
+					'default_terms' => self::$_settings[ $addon_name ]['default_terms'],
928
+				)
929
+			);
930
+		}
931
+	}
932
+
933
+
934
+	/**
935
+	 * @param string $addon_name
936
+	 * @return void
937
+	 * @throws InvalidArgumentException
938
+	 * @throws InvalidInterfaceException
939
+	 * @throws InvalidDataTypeException
940
+	 * @throws DomainException
941
+	 * @throws EE_Error
942
+	 */
943
+	private static function _register_payment_methods($addon_name)
944
+	{
945
+		if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
946
+			EE_Register_Payment_Method::register(
947
+				$addon_name,
948
+				array('payment_method_paths' => self::$_settings[ $addon_name ]['payment_method_paths'])
949
+			);
950
+		}
951
+	}
952
+
953
+
954
+	/**
955
+	 * @param string $addon_name
956
+	 * @return void
957
+	 * @throws InvalidArgumentException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidDataTypeException
960
+	 * @throws DomainException
961
+	 */
962
+	private static function registerPrivacyPolicies($addon_name)
963
+	{
964
+		if (! empty(self::$_settings[ $addon_name ]['privacy_policies'])) {
965
+			EE_Register_Privacy_Policy::register(
966
+				$addon_name,
967
+				self::$_settings[ $addon_name ]['privacy_policies']
968
+			);
969
+		}
970
+	}
971
+
972
+
973
+	/**
974
+	 * @param string $addon_name
975
+	 * @return void
976
+	 */
977
+	private static function registerPersonalDataExporters($addon_name)
978
+	{
979
+		if (! empty(self::$_settings[ $addon_name ]['personal_data_exporters'])) {
980
+			EE_Register_Personal_Data_Eraser::register(
981
+				$addon_name,
982
+				self::$_settings[ $addon_name ]['personal_data_exporters']
983
+			);
984
+		}
985
+	}
986
+
987
+
988
+	/**
989
+	 * @param string $addon_name
990
+	 * @return void
991
+	 */
992
+	private static function registerPersonalDataErasers($addon_name)
993
+	{
994
+		if (! empty(self::$_settings[ $addon_name ]['personal_data_erasers'])) {
995
+			EE_Register_Personal_Data_Eraser::register(
996
+				$addon_name,
997
+				self::$_settings[ $addon_name ]['personal_data_erasers']
998
+			);
999
+		}
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Loads and instantiates the EE_Addon class and adds it onto the registry
1005
+	 *
1006
+	 * @param string $addon_name
1007
+	 * @return EE_Addon
1008
+	 * @throws InvalidArgumentException
1009
+	 * @throws InvalidInterfaceException
1010
+	 * @throws InvalidDataTypeException
1011
+	 */
1012
+	private static function _load_and_init_addon_class($addon_name)
1013
+	{
1014
+		$addon = LoaderFactory::getLoader()->getShared(
1015
+			self::$_settings[ $addon_name ]['class_name'],
1016
+			array('EE_Registry::create(addon)' => true)
1017
+		);
1018
+		if (! $addon instanceof EE_Addon) {
1019
+			throw new DomainException(
1020
+				sprintf(
1021
+					esc_html__(
1022
+						'Failed to instantiate the %1$s class. PLease check that the class exists.',
1023
+						'event_espresso'
1024
+					),
1025
+					$addon_name
1026
+				)
1027
+			);
1028
+		}
1029
+		// setter inject dep map if required
1030
+		if ($addon->dependencyMap() === null) {
1031
+			$addon->setDependencyMap(LoaderFactory::getLoader()->getShared('EE_Dependency_Map'));
1032
+		}
1033
+		// setter inject domain if required
1034
+		EE_Register_Addon::injectAddonDomain($addon_name, $addon);
1035
+
1036
+		$addon->set_name($addon_name);
1037
+		$addon->set_plugin_slug(self::$_settings[ $addon_name ]['plugin_slug']);
1038
+		$addon->set_plugin_basename(self::$_settings[ $addon_name ]['plugin_basename']);
1039
+		$addon->set_main_plugin_file(self::$_settings[ $addon_name ]['main_file_path']);
1040
+		$addon->set_plugin_action_slug(self::$_settings[ $addon_name ]['plugin_action_slug']);
1041
+		$addon->set_plugins_page_row(self::$_settings[ $addon_name ]['plugins_page_row']);
1042
+		$addon->set_version(self::$_settings[ $addon_name ]['version']);
1043
+		$addon->set_min_core_version(self::_effective_version(self::$_settings[ $addon_name ]['min_core_version']));
1044
+		$addon->set_config_section(self::$_settings[ $addon_name ]['config_section']);
1045
+		$addon->set_config_class(self::$_settings[ $addon_name ]['config_class']);
1046
+		$addon->set_config_name(self::$_settings[ $addon_name ]['config_name']);
1047
+		// setup the add-on's pue_slug if we have one.
1048
+		if (! empty(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug'])) {
1049
+			$addon->setPueSlug(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug']);
1050
+		}
1051
+		// unfortunately this can't be hooked in upon construction,
1052
+		// because we don't have the plugin's mainfile path upon construction.
1053
+		register_deactivation_hook($addon->get_main_plugin_file(), array($addon, 'deactivation'));
1054
+		// call any additional admin_callback functions during load_admin_controller hook
1055
+		if (! empty(self::$_settings[ $addon_name ]['admin_callback'])) {
1056
+			add_action(
1057
+				'AHEE__EE_System__load_controllers__load_admin_controllers',
1058
+				array($addon, self::$_settings[ $addon_name ]['admin_callback'])
1059
+			);
1060
+		}
1061
+		return $addon;
1062
+	}
1063
+
1064
+
1065
+	/**
1066
+	 * @param string   $addon_name
1067
+	 * @param EE_Addon $addon
1068
+	 * @since   4.10.13.p
1069
+	 */
1070
+	private static function injectAddonDomain($addon_name, EE_Addon $addon)
1071
+	{
1072
+		if ($addon instanceof RequiresDomainInterface && $addon->domain() === null) {
1073
+			// using supplied Domain object
1074
+			$domain = self::$_settings[ $addon_name ]['domain'] instanceof DomainInterface
1075
+				? self::$_settings[ $addon_name ]['domain']
1076
+				: null;
1077
+			// or construct one using Domain FQCN
1078
+			if ($domain === null && self::$_settings[ $addon_name ]['domain_fqcn'] !== '') {
1079
+				$domain = LoaderFactory::getLoader()->getShared(
1080
+					self::$_settings[ $addon_name ]['domain_fqcn'],
1081
+					[
1082
+						new EventEspresso\core\domain\values\FilePath(
1083
+							self::$_settings[ $addon_name ]['main_file_path']
1084
+						),
1085
+						EventEspresso\core\domain\values\Version::fromString(
1086
+							self::$_settings[ $addon_name ]['version']
1087
+						),
1088
+					]
1089
+				);
1090
+			}
1091
+			if ($domain instanceof DomainInterface) {
1092
+				$addon->setDomain($domain);
1093
+			}
1094
+		}
1095
+	}
1096
+
1097
+
1098
+	/**
1099
+	 *    load_pue_update - Update notifications
1100
+	 *
1101
+	 * @return void
1102
+	 * @throws InvalidArgumentException
1103
+	 * @throws InvalidDataTypeException
1104
+	 * @throws InvalidInterfaceException
1105
+	 */
1106
+	public static function load_pue_update()
1107
+	{
1108
+		// load PUE client
1109
+		require_once EE_THIRD_PARTY . 'pue/pue-client.php';
1110
+		$license_server = defined('PUE_UPDATES_ENDPOINT') ? PUE_UPDATES_ENDPOINT : 'https://eventespresso.com';
1111
+		// cycle thru settings
1112
+		foreach (self::$_settings as $settings) {
1113
+			if (! empty($settings['pue_options'])) {
1114
+				// initiate the class and start the plugin update engine!
1115
+				new PluginUpdateEngineChecker(
1116
+					// host file URL
1117
+					$license_server,
1118
+					// plugin slug(s)
1119
+					array(
1120
+						'premium'    => array('p' => $settings['pue_options']['pue_plugin_slug']),
1121
+						'prerelease' => array('beta' => $settings['pue_options']['pue_plugin_slug'] . '-pr'),
1122
+					),
1123
+					// options
1124
+					array(
1125
+						'apikey'            => EE_Registry::instance()->NET_CFG->core->site_license_key,
1126
+						'lang_domain'       => 'event_espresso',
1127
+						'checkPeriod'       => $settings['pue_options']['checkPeriod'],
1128
+						'option_key'        => 'ee_site_license_key',
1129
+						'options_page_slug' => 'event_espresso',
1130
+						'plugin_basename'   => $settings['pue_options']['plugin_basename'],
1131
+						// if use_wp_update is TRUE it means you want FREE versions of the plugin to be updated from WP
1132
+						'use_wp_update'     => $settings['pue_options']['use_wp_update'],
1133
+					)
1134
+				);
1135
+			}
1136
+		}
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * Callback for EE_Brewing_Regular__messages_caf hook used to register message types.
1142
+	 *
1143
+	 * @since 4.4.0
1144
+	 * @return void
1145
+	 * @throws EE_Error
1146
+	 */
1147
+	public static function register_message_types()
1148
+	{
1149
+		foreach (self::$_settings as $settings) {
1150
+			if (! empty($settings['message_types'])) {
1151
+				foreach ((array) $settings['message_types'] as $message_type => $message_type_settings) {
1152
+					EE_Register_Message_Type::register($message_type, $message_type_settings);
1153
+				}
1154
+			}
1155
+		}
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * This deregisters an addon that was previously registered with a specific addon_name.
1161
+	 *
1162
+	 * @param string $addon_name the name for the addon that was previously registered
1163
+	 * @throws DomainException
1164
+	 * @throws InvalidArgumentException
1165
+	 * @throws InvalidDataTypeException
1166
+	 * @throws InvalidInterfaceException
1167
+	 *@since    4.3.0
1168
+	 */
1169
+	public static function deregister($addon_name = '')
1170
+	{
1171
+		if (isset(self::$_settings[ $addon_name ]['class_name'])) {
1172
+			try {
1173
+				do_action('AHEE__EE_Register_Addon__deregister__before', $addon_name);
1174
+				$class_name = self::$_settings[ $addon_name ]['class_name'];
1175
+				if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
1176
+					// setup DMS
1177
+					EE_Register_Data_Migration_Scripts::deregister($addon_name);
1178
+				}
1179
+				if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
1180
+					// register admin page
1181
+					EE_Register_Admin_Page::deregister($addon_name);
1182
+				}
1183
+				if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
1184
+					// add to list of modules to be registered
1185
+					EE_Register_Module::deregister($addon_name);
1186
+				}
1187
+				if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
1188
+					|| ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
1189
+				) {
1190
+					// add to list of shortcodes to be registered
1191
+					EE_Register_Shortcode::deregister($addon_name);
1192
+				}
1193
+				if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
1194
+					// if config_class present let's register config.
1195
+					EE_Register_Config::deregister(self::$_settings[ $addon_name ]['config_class']);
1196
+				}
1197
+				if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
1198
+					// add to list of widgets to be registered
1199
+					EE_Register_Widget::deregister($addon_name);
1200
+				}
1201
+				if (! empty(self::$_settings[ $addon_name ]['model_paths'])
1202
+					|| ! empty(self::$_settings[ $addon_name ]['class_paths'])
1203
+				) {
1204
+					// add to list of shortcodes to be registered
1205
+					EE_Register_Model::deregister($addon_name);
1206
+				}
1207
+				if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
1208
+					|| ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
1209
+				) {
1210
+					// add to list of shortcodes to be registered
1211
+					EE_Register_Model_Extensions::deregister($addon_name);
1212
+				}
1213
+				if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
1214
+					foreach ((array) self::$_settings[ $addon_name ]['message_types'] as $message_type => $message_type_settings) {
1215
+						EE_Register_Message_Type::deregister($message_type);
1216
+					}
1217
+				}
1218
+				// deregister capabilities for addon
1219
+				if (! empty(self::$_settings[ $addon_name ]['capabilities'])
1220
+					|| ! empty(self::$_settings[ $addon_name ]['capability_maps'])
1221
+				) {
1222
+					EE_Register_Capabilities::deregister($addon_name);
1223
+				}
1224
+				// deregister custom_post_types for addon
1225
+				if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])) {
1226
+					EE_Register_CPT::deregister($addon_name);
1227
+				}
1228
+				if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
1229
+					EE_Register_Payment_Method::deregister($addon_name);
1230
+				}
1231
+				$addon = EE_Registry::instance()->getAddon($class_name);
1232
+				if ($addon instanceof EE_Addon) {
1233
+					remove_action(
1234
+						'deactivate_' . $addon->get_main_plugin_file_basename(),
1235
+						array($addon, 'deactivation')
1236
+					);
1237
+					remove_action(
1238
+						'AHEE__EE_System__perform_activations_upgrades_and_migrations',
1239
+						array($addon, 'initialize_db_if_no_migrations_required')
1240
+					);
1241
+					// remove `after_registration` call
1242
+					remove_action(
1243
+						'AHEE__EE_System__load_espresso_addons__complete',
1244
+						array($addon, 'after_registration'),
1245
+						999
1246
+					);
1247
+				}
1248
+				EE_Registry::instance()->removeAddon($class_name);
1249
+				LoaderFactory::getLoader()->remove($class_name);
1250
+			} catch (OutOfBoundsException $addon_not_yet_registered_exception) {
1251
+				// the add-on was not yet registered in the registry,
1252
+				// so RegistryContainer::__get() throws this exception.
1253
+				// also no need to worry about this or log it,
1254
+				// it's ok to deregister an add-on before its registered in the registry
1255
+			} catch (Exception $e) {
1256
+				new ExceptionLogger($e);
1257
+			}
1258
+			unset(self::$_settings[ $addon_name ]);
1259
+			do_action('AHEE__EE_Register_Addon__deregister__after', $addon_name);
1260
+		}
1261
+	}
1262 1262
 }
Please login to merge, or discard this patch.
Spacing   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -70,15 +70,15 @@  discard block
 block discarded – undo
70 70
         // offsets:    0 . 1 . 2 . 3 . 4
71 71
         $version_parts = explode('.', $min_core_version);
72 72
         // check they specified the micro version (after 2nd period)
73
-        if (! isset($version_parts[2])) {
73
+        if ( ! isset($version_parts[2])) {
74 74
             $version_parts[2] = '0';
75 75
         }
76 76
         // if they didn't specify the 'p', or 'rc' part. Just assume the lowest possible
77 77
         // soon we can assume that's 'rc', but this current version is 'alpha'
78
-        if (! isset($version_parts[3])) {
78
+        if ( ! isset($version_parts[3])) {
79 79
             $version_parts[3] = 'dev';
80 80
         }
81
-        if (! isset($version_parts[4])) {
81
+        if ( ! isset($version_parts[4])) {
82 82
             $version_parts[4] = '000';
83 83
         }
84 84
         return implode('.', $version_parts);
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
         EE_Register_Addon::_parse_pue_options($addon_name, $class_name, $setup_args);
266 266
         // does this addon work with this version of core or WordPress ?
267 267
         // does this addon work with this version of core or WordPress ?
268
-        if (! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
268
+        if ( ! EE_Register_Addon::_addon_is_compatible($addon_name, $addon_settings)) {
269 269
             return;
270 270
         }
271 271
         // register namespaces
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
                 )
330 330
             );
331 331
         }
332
-        if (! isset($setup_args['main_file_path']) || empty($setup_args['main_file_path'])) {
332
+        if ( ! isset($setup_args['main_file_path']) || empty($setup_args['main_file_path'])) {
333 333
             throw new EE_Error(
334 334
                 sprintf(
335 335
                     __(
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
             );
342 342
         }
343 343
         // check that addon has not already been registered with that name
344
-        if (isset(self::$_settings[ $addon_name ]) && ! did_action('activate_plugin')) {
344
+        if (isset(self::$_settings[$addon_name]) && ! did_action('activate_plugin')) {
345 345
             throw new EE_Error(
346 346
                 sprintf(
347 347
                     __(
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
         // check if classname is fully  qualified or is a legacy classname already prefixed with 'EE_'
374 374
         return strpos($class_name, '\\') || strpos($class_name, 'EE_') === 0
375 375
             ? $class_name
376
-            : 'EE_' . $class_name;
376
+            : 'EE_'.$class_name;
377 377
     }
378 378
 
379 379
 
@@ -538,9 +538,9 @@  discard block
 block discarded – undo
538 538
         global $wp_version;
539 539
         $incompatibility_message = '';
540 540
         // check whether this addon version is compatible with EE core
541
-        if (isset(EE_Register_Addon::$_incompatible_addons[ $addon_name ])
541
+        if (isset(EE_Register_Addon::$_incompatible_addons[$addon_name])
542 542
             && ! self::_meets_min_core_version_requirement(
543
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
543
+                EE_Register_Addon::$_incompatible_addons[$addon_name],
544 544
                 $addon_settings['version']
545 545
             )
546 546
         ) {
@@ -551,11 +551,11 @@  discard block
 block discarded – undo
551 551
                 ),
552 552
                 $addon_name,
553 553
                 '<br />',
554
-                EE_Register_Addon::$_incompatible_addons[ $addon_name ],
554
+                EE_Register_Addon::$_incompatible_addons[$addon_name],
555 555
                 '<span style="font-weight: bold; color: #D54E21;">',
556 556
                 '</span><br />'
557 557
             );
558
-        } elseif (! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
558
+        } elseif ( ! self::_meets_min_core_version_requirement($addon_settings['min_core_version'], espresso_version())
559 559
         ) {
560 560
             $incompatibility_message = sprintf(
561 561
                 __(
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
                 '</span><br />'
583 583
             );
584 584
         }
585
-        if (! empty($incompatibility_message)) {
585
+        if ( ! empty($incompatibility_message)) {
586 586
             // remove 'activate' from the REQUEST
587 587
             // so WP doesn't erroneously tell the user the plugin activated fine when it didn't
588 588
             /** @var RequestInterface $request */
@@ -612,11 +612,11 @@  discard block
 block discarded – undo
612 612
      */
613 613
     private static function _parse_pue_options($addon_name, $class_name, array $setup_args)
614 614
     {
615
-        if (! empty($setup_args['pue_options'])) {
616
-            self::$_settings[ $addon_name ]['pue_options'] = array(
615
+        if ( ! empty($setup_args['pue_options'])) {
616
+            self::$_settings[$addon_name]['pue_options'] = array(
617 617
                 'pue_plugin_slug' => isset($setup_args['pue_options']['pue_plugin_slug'])
618 618
                     ? (string) $setup_args['pue_options']['pue_plugin_slug']
619
-                    : 'espresso_' . strtolower($class_name),
619
+                    : 'espresso_'.strtolower($class_name),
620 620
                 'plugin_basename' => isset($setup_args['pue_options']['plugin_basename'])
621 621
                     ? (string) $setup_args['pue_options']['plugin_basename']
622 622
                     : plugin_basename($setup_args['main_file_path']),
@@ -672,12 +672,12 @@  discard block
 block discarded – undo
672 672
             // (as the newly-activated addon wasn't around the first time addons were registered).
673 673
             // Note: the presence of pue_options in the addon registration options will initialize the $_settings
674 674
             // property for the add-on, but the add-on is only partially initialized.  Hence, the additional check.
675
-            if (! isset(self::$_settings[ $addon_name ])
676
-                || (isset(self::$_settings[ $addon_name ])
677
-                    && ! isset(self::$_settings[ $addon_name ]['class_name'])
675
+            if ( ! isset(self::$_settings[$addon_name])
676
+                || (isset(self::$_settings[$addon_name])
677
+                    && ! isset(self::$_settings[$addon_name]['class_name'])
678 678
                 )
679 679
             ) {
680
-                self::$_settings[ $addon_name ] = $addon_settings;
680
+                self::$_settings[$addon_name] = $addon_settings;
681 681
                 $addon = self::_load_and_init_addon_class($addon_name);
682 682
                 $addon->set_activation_indicator_option();
683 683
                 // dont bother setting up the rest of the addon.
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
             return true;
687 687
         }
688 688
         // make sure this was called in the right place!
689
-        if (! did_action('AHEE__EE_System__load_espresso_addons')
689
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')
690 690
             || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')
691 691
         ) {
692 692
             EE_Error::doing_it_wrong(
@@ -702,10 +702,10 @@  discard block
 block discarded – undo
702 702
             );
703 703
         }
704 704
         // make sure addon settings are set correctly without overwriting anything existing
705
-        if (isset(self::$_settings[ $addon_name ])) {
706
-            self::$_settings[ $addon_name ] += $addon_settings;
705
+        if (isset(self::$_settings[$addon_name])) {
706
+            self::$_settings[$addon_name] += $addon_settings;
707 707
         } else {
708
-            self::$_settings[ $addon_name ] = $addon_settings;
708
+            self::$_settings[$addon_name] = $addon_settings;
709 709
         }
710 710
         return false;
711 711
     }
@@ -718,13 +718,13 @@  discard block
 block discarded – undo
718 718
      */
719 719
     private static function _setup_autoloaders($addon_name)
720 720
     {
721
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_paths'])) {
721
+        if ( ! empty(self::$_settings[$addon_name]['autoloader_paths'])) {
722 722
             // setup autoloader for single file
723
-            EEH_Autoloader::instance()->register_autoloader(self::$_settings[ $addon_name ]['autoloader_paths']);
723
+            EEH_Autoloader::instance()->register_autoloader(self::$_settings[$addon_name]['autoloader_paths']);
724 724
         }
725 725
         // setup autoloaders for folders
726
-        if (! empty(self::$_settings[ $addon_name ]['autoloader_folders'])) {
727
-            foreach ((array) self::$_settings[ $addon_name ]['autoloader_folders'] as $autoloader_folder) {
726
+        if ( ! empty(self::$_settings[$addon_name]['autoloader_folders'])) {
727
+            foreach ((array) self::$_settings[$addon_name]['autoloader_folders'] as $autoloader_folder) {
728 728
                 EEH_Autoloader::register_autoloaders_for_each_file_in_folder($autoloader_folder);
729 729
             }
730 730
         }
@@ -741,26 +741,26 @@  discard block
 block discarded – undo
741 741
     private static function _register_models_and_extensions($addon_name)
742 742
     {
743 743
         // register new models
744
-        if (! empty(self::$_settings[ $addon_name ]['model_paths'])
745
-            || ! empty(self::$_settings[ $addon_name ]['class_paths'])
744
+        if ( ! empty(self::$_settings[$addon_name]['model_paths'])
745
+            || ! empty(self::$_settings[$addon_name]['class_paths'])
746 746
         ) {
747 747
             EE_Register_Model::register(
748 748
                 $addon_name,
749 749
                 array(
750
-                    'model_paths' => self::$_settings[ $addon_name ]['model_paths'],
751
-                    'class_paths' => self::$_settings[ $addon_name ]['class_paths'],
750
+                    'model_paths' => self::$_settings[$addon_name]['model_paths'],
751
+                    'class_paths' => self::$_settings[$addon_name]['class_paths'],
752 752
                 )
753 753
             );
754 754
         }
755 755
         // register model extensions
756
-        if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
757
-            || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
756
+        if ( ! empty(self::$_settings[$addon_name]['model_extension_paths'])
757
+            || ! empty(self::$_settings[$addon_name]['class_extension_paths'])
758 758
         ) {
759 759
             EE_Register_Model_Extensions::register(
760 760
                 $addon_name,
761 761
                 array(
762
-                    'model_extension_paths' => self::$_settings[ $addon_name ]['model_extension_paths'],
763
-                    'class_extension_paths' => self::$_settings[ $addon_name ]['class_extension_paths'],
762
+                    'model_extension_paths' => self::$_settings[$addon_name]['model_extension_paths'],
763
+                    'class_extension_paths' => self::$_settings[$addon_name]['class_extension_paths'],
764 764
                 )
765 765
             );
766 766
         }
@@ -775,10 +775,10 @@  discard block
 block discarded – undo
775 775
     private static function _register_data_migration_scripts($addon_name)
776 776
     {
777 777
         // setup DMS
778
-        if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
778
+        if ( ! empty(self::$_settings[$addon_name]['dms_paths'])) {
779 779
             EE_Register_Data_Migration_Scripts::register(
780 780
                 $addon_name,
781
-                array('dms_paths' => self::$_settings[ $addon_name ]['dms_paths'])
781
+                array('dms_paths' => self::$_settings[$addon_name]['dms_paths'])
782 782
             );
783 783
         }
784 784
     }
@@ -792,12 +792,12 @@  discard block
 block discarded – undo
792 792
     private static function _register_config($addon_name)
793 793
     {
794 794
         // if config_class is present let's register config.
795
-        if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
795
+        if ( ! empty(self::$_settings[$addon_name]['config_class'])) {
796 796
             EE_Register_Config::register(
797
-                self::$_settings[ $addon_name ]['config_class'],
797
+                self::$_settings[$addon_name]['config_class'],
798 798
                 array(
799
-                    'config_section' => self::$_settings[ $addon_name ]['config_section'],
800
-                    'config_name'    => self::$_settings[ $addon_name ]['config_name'],
799
+                    'config_section' => self::$_settings[$addon_name]['config_section'],
800
+                    'config_name'    => self::$_settings[$addon_name]['config_name'],
801 801
                 )
802 802
             );
803 803
         }
@@ -811,10 +811,10 @@  discard block
 block discarded – undo
811 811
      */
812 812
     private static function _register_admin_pages($addon_name)
813 813
     {
814
-        if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
814
+        if ( ! empty(self::$_settings[$addon_name]['admin_path'])) {
815 815
             EE_Register_Admin_Page::register(
816 816
                 $addon_name,
817
-                array('page_path' => self::$_settings[ $addon_name ]['admin_path'])
817
+                array('page_path' => self::$_settings[$addon_name]['admin_path'])
818 818
             );
819 819
         }
820 820
     }
@@ -827,10 +827,10 @@  discard block
 block discarded – undo
827 827
      */
828 828
     private static function _register_modules($addon_name)
829 829
     {
830
-        if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
830
+        if ( ! empty(self::$_settings[$addon_name]['module_paths'])) {
831 831
             EE_Register_Module::register(
832 832
                 $addon_name,
833
-                array('module_paths' => self::$_settings[ $addon_name ]['module_paths'])
833
+                array('module_paths' => self::$_settings[$addon_name]['module_paths'])
834 834
             );
835 835
         }
836 836
     }
@@ -843,16 +843,16 @@  discard block
 block discarded – undo
843 843
      */
844 844
     private static function _register_shortcodes($addon_name)
845 845
     {
846
-        if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
847
-            || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
846
+        if ( ! empty(self::$_settings[$addon_name]['shortcode_paths'])
847
+            || ! empty(self::$_settings[$addon_name]['shortcode_fqcns'])
848 848
         ) {
849 849
             EE_Register_Shortcode::register(
850 850
                 $addon_name,
851 851
                 array(
852
-                    'shortcode_paths' => isset(self::$_settings[ $addon_name ]['shortcode_paths'])
853
-                        ? self::$_settings[ $addon_name ]['shortcode_paths'] : array(),
854
-                    'shortcode_fqcns' => isset(self::$_settings[ $addon_name ]['shortcode_fqcns'])
855
-                        ? self::$_settings[ $addon_name ]['shortcode_fqcns'] : array(),
852
+                    'shortcode_paths' => isset(self::$_settings[$addon_name]['shortcode_paths'])
853
+                        ? self::$_settings[$addon_name]['shortcode_paths'] : array(),
854
+                    'shortcode_fqcns' => isset(self::$_settings[$addon_name]['shortcode_fqcns'])
855
+                        ? self::$_settings[$addon_name]['shortcode_fqcns'] : array(),
856 856
                 )
857 857
             );
858 858
         }
@@ -866,10 +866,10 @@  discard block
 block discarded – undo
866 866
      */
867 867
     private static function _register_widgets($addon_name)
868 868
     {
869
-        if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
869
+        if ( ! empty(self::$_settings[$addon_name]['widget_paths'])) {
870 870
             EE_Register_Widget::register(
871 871
                 $addon_name,
872
-                array('widget_paths' => self::$_settings[ $addon_name ]['widget_paths'])
872
+                array('widget_paths' => self::$_settings[$addon_name]['widget_paths'])
873 873
             );
874 874
         }
875 875
     }
@@ -882,12 +882,12 @@  discard block
 block discarded – undo
882 882
      */
883 883
     private static function _register_capabilities($addon_name)
884 884
     {
885
-        if (! empty(self::$_settings[ $addon_name ]['capabilities'])) {
885
+        if ( ! empty(self::$_settings[$addon_name]['capabilities'])) {
886 886
             EE_Register_Capabilities::register(
887 887
                 $addon_name,
888 888
                 array(
889
-                    'capabilities'    => self::$_settings[ $addon_name ]['capabilities'],
890
-                    'capability_maps' => self::$_settings[ $addon_name ]['capability_maps'],
889
+                    'capabilities'    => self::$_settings[$addon_name]['capabilities'],
890
+                    'capability_maps' => self::$_settings[$addon_name]['capability_maps'],
891 891
                 )
892 892
             );
893 893
         }
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
      */
901 901
     private static function _register_message_types($addon_name)
902 902
     {
903
-        if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
903
+        if ( ! empty(self::$_settings[$addon_name]['message_types'])) {
904 904
             add_action(
905 905
                 'EE_Brewing_Regular___messages_caf',
906 906
                 array('EE_Register_Addon', 'register_message_types')
@@ -916,15 +916,15 @@  discard block
 block discarded – undo
916 916
      */
917 917
     private static function _register_custom_post_types($addon_name)
918 918
     {
919
-        if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])
920
-            || ! empty(self::$_settings[ $addon_name ]['custom_taxonomies'])
919
+        if ( ! empty(self::$_settings[$addon_name]['custom_post_types'])
920
+            || ! empty(self::$_settings[$addon_name]['custom_taxonomies'])
921 921
         ) {
922 922
             EE_Register_CPT::register(
923 923
                 $addon_name,
924 924
                 array(
925
-                    'cpts'          => self::$_settings[ $addon_name ]['custom_post_types'],
926
-                    'cts'           => self::$_settings[ $addon_name ]['custom_taxonomies'],
927
-                    'default_terms' => self::$_settings[ $addon_name ]['default_terms'],
925
+                    'cpts'          => self::$_settings[$addon_name]['custom_post_types'],
926
+                    'cts'           => self::$_settings[$addon_name]['custom_taxonomies'],
927
+                    'default_terms' => self::$_settings[$addon_name]['default_terms'],
928 928
                 )
929 929
             );
930 930
         }
@@ -942,10 +942,10 @@  discard block
 block discarded – undo
942 942
      */
943 943
     private static function _register_payment_methods($addon_name)
944 944
     {
945
-        if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
945
+        if ( ! empty(self::$_settings[$addon_name]['payment_method_paths'])) {
946 946
             EE_Register_Payment_Method::register(
947 947
                 $addon_name,
948
-                array('payment_method_paths' => self::$_settings[ $addon_name ]['payment_method_paths'])
948
+                array('payment_method_paths' => self::$_settings[$addon_name]['payment_method_paths'])
949 949
             );
950 950
         }
951 951
     }
@@ -961,10 +961,10 @@  discard block
 block discarded – undo
961 961
      */
962 962
     private static function registerPrivacyPolicies($addon_name)
963 963
     {
964
-        if (! empty(self::$_settings[ $addon_name ]['privacy_policies'])) {
964
+        if ( ! empty(self::$_settings[$addon_name]['privacy_policies'])) {
965 965
             EE_Register_Privacy_Policy::register(
966 966
                 $addon_name,
967
-                self::$_settings[ $addon_name ]['privacy_policies']
967
+                self::$_settings[$addon_name]['privacy_policies']
968 968
             );
969 969
         }
970 970
     }
@@ -976,10 +976,10 @@  discard block
 block discarded – undo
976 976
      */
977 977
     private static function registerPersonalDataExporters($addon_name)
978 978
     {
979
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_exporters'])) {
979
+        if ( ! empty(self::$_settings[$addon_name]['personal_data_exporters'])) {
980 980
             EE_Register_Personal_Data_Eraser::register(
981 981
                 $addon_name,
982
-                self::$_settings[ $addon_name ]['personal_data_exporters']
982
+                self::$_settings[$addon_name]['personal_data_exporters']
983 983
             );
984 984
         }
985 985
     }
@@ -991,10 +991,10 @@  discard block
 block discarded – undo
991 991
      */
992 992
     private static function registerPersonalDataErasers($addon_name)
993 993
     {
994
-        if (! empty(self::$_settings[ $addon_name ]['personal_data_erasers'])) {
994
+        if ( ! empty(self::$_settings[$addon_name]['personal_data_erasers'])) {
995 995
             EE_Register_Personal_Data_Eraser::register(
996 996
                 $addon_name,
997
-                self::$_settings[ $addon_name ]['personal_data_erasers']
997
+                self::$_settings[$addon_name]['personal_data_erasers']
998 998
             );
999 999
         }
1000 1000
     }
@@ -1012,10 +1012,10 @@  discard block
 block discarded – undo
1012 1012
     private static function _load_and_init_addon_class($addon_name)
1013 1013
     {
1014 1014
         $addon = LoaderFactory::getLoader()->getShared(
1015
-            self::$_settings[ $addon_name ]['class_name'],
1015
+            self::$_settings[$addon_name]['class_name'],
1016 1016
             array('EE_Registry::create(addon)' => true)
1017 1017
         );
1018
-        if (! $addon instanceof EE_Addon) {
1018
+        if ( ! $addon instanceof EE_Addon) {
1019 1019
             throw new DomainException(
1020 1020
                 sprintf(
1021 1021
                     esc_html__(
@@ -1034,28 +1034,28 @@  discard block
 block discarded – undo
1034 1034
         EE_Register_Addon::injectAddonDomain($addon_name, $addon);
1035 1035
 
1036 1036
         $addon->set_name($addon_name);
1037
-        $addon->set_plugin_slug(self::$_settings[ $addon_name ]['plugin_slug']);
1038
-        $addon->set_plugin_basename(self::$_settings[ $addon_name ]['plugin_basename']);
1039
-        $addon->set_main_plugin_file(self::$_settings[ $addon_name ]['main_file_path']);
1040
-        $addon->set_plugin_action_slug(self::$_settings[ $addon_name ]['plugin_action_slug']);
1041
-        $addon->set_plugins_page_row(self::$_settings[ $addon_name ]['plugins_page_row']);
1042
-        $addon->set_version(self::$_settings[ $addon_name ]['version']);
1043
-        $addon->set_min_core_version(self::_effective_version(self::$_settings[ $addon_name ]['min_core_version']));
1044
-        $addon->set_config_section(self::$_settings[ $addon_name ]['config_section']);
1045
-        $addon->set_config_class(self::$_settings[ $addon_name ]['config_class']);
1046
-        $addon->set_config_name(self::$_settings[ $addon_name ]['config_name']);
1037
+        $addon->set_plugin_slug(self::$_settings[$addon_name]['plugin_slug']);
1038
+        $addon->set_plugin_basename(self::$_settings[$addon_name]['plugin_basename']);
1039
+        $addon->set_main_plugin_file(self::$_settings[$addon_name]['main_file_path']);
1040
+        $addon->set_plugin_action_slug(self::$_settings[$addon_name]['plugin_action_slug']);
1041
+        $addon->set_plugins_page_row(self::$_settings[$addon_name]['plugins_page_row']);
1042
+        $addon->set_version(self::$_settings[$addon_name]['version']);
1043
+        $addon->set_min_core_version(self::_effective_version(self::$_settings[$addon_name]['min_core_version']));
1044
+        $addon->set_config_section(self::$_settings[$addon_name]['config_section']);
1045
+        $addon->set_config_class(self::$_settings[$addon_name]['config_class']);
1046
+        $addon->set_config_name(self::$_settings[$addon_name]['config_name']);
1047 1047
         // setup the add-on's pue_slug if we have one.
1048
-        if (! empty(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug'])) {
1049
-            $addon->setPueSlug(self::$_settings[ $addon_name ]['pue_options']['pue_plugin_slug']);
1048
+        if ( ! empty(self::$_settings[$addon_name]['pue_options']['pue_plugin_slug'])) {
1049
+            $addon->setPueSlug(self::$_settings[$addon_name]['pue_options']['pue_plugin_slug']);
1050 1050
         }
1051 1051
         // unfortunately this can't be hooked in upon construction,
1052 1052
         // because we don't have the plugin's mainfile path upon construction.
1053 1053
         register_deactivation_hook($addon->get_main_plugin_file(), array($addon, 'deactivation'));
1054 1054
         // call any additional admin_callback functions during load_admin_controller hook
1055
-        if (! empty(self::$_settings[ $addon_name ]['admin_callback'])) {
1055
+        if ( ! empty(self::$_settings[$addon_name]['admin_callback'])) {
1056 1056
             add_action(
1057 1057
                 'AHEE__EE_System__load_controllers__load_admin_controllers',
1058
-                array($addon, self::$_settings[ $addon_name ]['admin_callback'])
1058
+                array($addon, self::$_settings[$addon_name]['admin_callback'])
1059 1059
             );
1060 1060
         }
1061 1061
         return $addon;
@@ -1071,19 +1071,19 @@  discard block
 block discarded – undo
1071 1071
     {
1072 1072
         if ($addon instanceof RequiresDomainInterface && $addon->domain() === null) {
1073 1073
             // using supplied Domain object
1074
-            $domain = self::$_settings[ $addon_name ]['domain'] instanceof DomainInterface
1075
-                ? self::$_settings[ $addon_name ]['domain']
1074
+            $domain = self::$_settings[$addon_name]['domain'] instanceof DomainInterface
1075
+                ? self::$_settings[$addon_name]['domain']
1076 1076
                 : null;
1077 1077
             // or construct one using Domain FQCN
1078
-            if ($domain === null && self::$_settings[ $addon_name ]['domain_fqcn'] !== '') {
1078
+            if ($domain === null && self::$_settings[$addon_name]['domain_fqcn'] !== '') {
1079 1079
                 $domain = LoaderFactory::getLoader()->getShared(
1080
-                    self::$_settings[ $addon_name ]['domain_fqcn'],
1080
+                    self::$_settings[$addon_name]['domain_fqcn'],
1081 1081
                     [
1082 1082
                         new EventEspresso\core\domain\values\FilePath(
1083
-                            self::$_settings[ $addon_name ]['main_file_path']
1083
+                            self::$_settings[$addon_name]['main_file_path']
1084 1084
                         ),
1085 1085
                         EventEspresso\core\domain\values\Version::fromString(
1086
-                            self::$_settings[ $addon_name ]['version']
1086
+                            self::$_settings[$addon_name]['version']
1087 1087
                         ),
1088 1088
                     ]
1089 1089
                 );
@@ -1106,11 +1106,11 @@  discard block
 block discarded – undo
1106 1106
     public static function load_pue_update()
1107 1107
     {
1108 1108
         // load PUE client
1109
-        require_once EE_THIRD_PARTY . 'pue/pue-client.php';
1109
+        require_once EE_THIRD_PARTY.'pue/pue-client.php';
1110 1110
         $license_server = defined('PUE_UPDATES_ENDPOINT') ? PUE_UPDATES_ENDPOINT : 'https://eventespresso.com';
1111 1111
         // cycle thru settings
1112 1112
         foreach (self::$_settings as $settings) {
1113
-            if (! empty($settings['pue_options'])) {
1113
+            if ( ! empty($settings['pue_options'])) {
1114 1114
                 // initiate the class and start the plugin update engine!
1115 1115
                 new PluginUpdateEngineChecker(
1116 1116
                     // host file URL
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
                     // plugin slug(s)
1119 1119
                     array(
1120 1120
                         'premium'    => array('p' => $settings['pue_options']['pue_plugin_slug']),
1121
-                        'prerelease' => array('beta' => $settings['pue_options']['pue_plugin_slug'] . '-pr'),
1121
+                        'prerelease' => array('beta' => $settings['pue_options']['pue_plugin_slug'].'-pr'),
1122 1122
                     ),
1123 1123
                     // options
1124 1124
                     array(
@@ -1147,7 +1147,7 @@  discard block
 block discarded – undo
1147 1147
     public static function register_message_types()
1148 1148
     {
1149 1149
         foreach (self::$_settings as $settings) {
1150
-            if (! empty($settings['message_types'])) {
1150
+            if ( ! empty($settings['message_types'])) {
1151 1151
                 foreach ((array) $settings['message_types'] as $message_type => $message_type_settings) {
1152 1152
                     EE_Register_Message_Type::register($message_type, $message_type_settings);
1153 1153
                 }
@@ -1168,70 +1168,70 @@  discard block
 block discarded – undo
1168 1168
      */
1169 1169
     public static function deregister($addon_name = '')
1170 1170
     {
1171
-        if (isset(self::$_settings[ $addon_name ]['class_name'])) {
1171
+        if (isset(self::$_settings[$addon_name]['class_name'])) {
1172 1172
             try {
1173 1173
                 do_action('AHEE__EE_Register_Addon__deregister__before', $addon_name);
1174
-                $class_name = self::$_settings[ $addon_name ]['class_name'];
1175
-                if (! empty(self::$_settings[ $addon_name ]['dms_paths'])) {
1174
+                $class_name = self::$_settings[$addon_name]['class_name'];
1175
+                if ( ! empty(self::$_settings[$addon_name]['dms_paths'])) {
1176 1176
                     // setup DMS
1177 1177
                     EE_Register_Data_Migration_Scripts::deregister($addon_name);
1178 1178
                 }
1179
-                if (! empty(self::$_settings[ $addon_name ]['admin_path'])) {
1179
+                if ( ! empty(self::$_settings[$addon_name]['admin_path'])) {
1180 1180
                     // register admin page
1181 1181
                     EE_Register_Admin_Page::deregister($addon_name);
1182 1182
                 }
1183
-                if (! empty(self::$_settings[ $addon_name ]['module_paths'])) {
1183
+                if ( ! empty(self::$_settings[$addon_name]['module_paths'])) {
1184 1184
                     // add to list of modules to be registered
1185 1185
                     EE_Register_Module::deregister($addon_name);
1186 1186
                 }
1187
-                if (! empty(self::$_settings[ $addon_name ]['shortcode_paths'])
1188
-                    || ! empty(self::$_settings[ $addon_name ]['shortcode_fqcns'])
1187
+                if ( ! empty(self::$_settings[$addon_name]['shortcode_paths'])
1188
+                    || ! empty(self::$_settings[$addon_name]['shortcode_fqcns'])
1189 1189
                 ) {
1190 1190
                     // add to list of shortcodes to be registered
1191 1191
                     EE_Register_Shortcode::deregister($addon_name);
1192 1192
                 }
1193
-                if (! empty(self::$_settings[ $addon_name ]['config_class'])) {
1193
+                if ( ! empty(self::$_settings[$addon_name]['config_class'])) {
1194 1194
                     // if config_class present let's register config.
1195
-                    EE_Register_Config::deregister(self::$_settings[ $addon_name ]['config_class']);
1195
+                    EE_Register_Config::deregister(self::$_settings[$addon_name]['config_class']);
1196 1196
                 }
1197
-                if (! empty(self::$_settings[ $addon_name ]['widget_paths'])) {
1197
+                if ( ! empty(self::$_settings[$addon_name]['widget_paths'])) {
1198 1198
                     // add to list of widgets to be registered
1199 1199
                     EE_Register_Widget::deregister($addon_name);
1200 1200
                 }
1201
-                if (! empty(self::$_settings[ $addon_name ]['model_paths'])
1202
-                    || ! empty(self::$_settings[ $addon_name ]['class_paths'])
1201
+                if ( ! empty(self::$_settings[$addon_name]['model_paths'])
1202
+                    || ! empty(self::$_settings[$addon_name]['class_paths'])
1203 1203
                 ) {
1204 1204
                     // add to list of shortcodes to be registered
1205 1205
                     EE_Register_Model::deregister($addon_name);
1206 1206
                 }
1207
-                if (! empty(self::$_settings[ $addon_name ]['model_extension_paths'])
1208
-                    || ! empty(self::$_settings[ $addon_name ]['class_extension_paths'])
1207
+                if ( ! empty(self::$_settings[$addon_name]['model_extension_paths'])
1208
+                    || ! empty(self::$_settings[$addon_name]['class_extension_paths'])
1209 1209
                 ) {
1210 1210
                     // add to list of shortcodes to be registered
1211 1211
                     EE_Register_Model_Extensions::deregister($addon_name);
1212 1212
                 }
1213
-                if (! empty(self::$_settings[ $addon_name ]['message_types'])) {
1214
-                    foreach ((array) self::$_settings[ $addon_name ]['message_types'] as $message_type => $message_type_settings) {
1213
+                if ( ! empty(self::$_settings[$addon_name]['message_types'])) {
1214
+                    foreach ((array) self::$_settings[$addon_name]['message_types'] as $message_type => $message_type_settings) {
1215 1215
                         EE_Register_Message_Type::deregister($message_type);
1216 1216
                     }
1217 1217
                 }
1218 1218
                 // deregister capabilities for addon
1219
-                if (! empty(self::$_settings[ $addon_name ]['capabilities'])
1220
-                    || ! empty(self::$_settings[ $addon_name ]['capability_maps'])
1219
+                if ( ! empty(self::$_settings[$addon_name]['capabilities'])
1220
+                    || ! empty(self::$_settings[$addon_name]['capability_maps'])
1221 1221
                 ) {
1222 1222
                     EE_Register_Capabilities::deregister($addon_name);
1223 1223
                 }
1224 1224
                 // deregister custom_post_types for addon
1225
-                if (! empty(self::$_settings[ $addon_name ]['custom_post_types'])) {
1225
+                if ( ! empty(self::$_settings[$addon_name]['custom_post_types'])) {
1226 1226
                     EE_Register_CPT::deregister($addon_name);
1227 1227
                 }
1228
-                if (! empty(self::$_settings[ $addon_name ]['payment_method_paths'])) {
1228
+                if ( ! empty(self::$_settings[$addon_name]['payment_method_paths'])) {
1229 1229
                     EE_Register_Payment_Method::deregister($addon_name);
1230 1230
                 }
1231 1231
                 $addon = EE_Registry::instance()->getAddon($class_name);
1232 1232
                 if ($addon instanceof EE_Addon) {
1233 1233
                     remove_action(
1234
-                        'deactivate_' . $addon->get_main_plugin_file_basename(),
1234
+                        'deactivate_'.$addon->get_main_plugin_file_basename(),
1235 1235
                         array($addon, 'deactivation')
1236 1236
                     );
1237 1237
                     remove_action(
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
             } catch (Exception $e) {
1256 1256
                 new ExceptionLogger($e);
1257 1257
             }
1258
-            unset(self::$_settings[ $addon_name ]);
1258
+            unset(self::$_settings[$addon_name]);
1259 1259
             do_action('AHEE__EE_Register_Addon__deregister__after', $addon_name);
1260 1260
         }
1261 1261
     }
Please login to merge, or discard this patch.
libraries/messages/data_class/EE_Messages_Preview_incoming_data.class.php 2 patches
Indentation   +595 added lines, -595 removed lines patch added patch discarded remove patch
@@ -21,599 +21,599 @@
 block discarded – undo
21 21
 class EE_Messages_Preview_incoming_data extends EE_Messages_incoming_data
22 22
 {
23 23
 
24
-    // some specific properties we need for this class
25
-    private $_events        = [];
26
-
27
-    private $_attendees     = [];
28
-
29
-    private $_registrations = [];
30
-
31
-
32
-    /**
33
-     * For the constructor of this special preview class.  We're either looking for an event id or empty data.  If we
34
-     * have an event id (or ids) then we'll use that as the source for the "dummy" data.  If the data is empty then
35
-     * we'll get the first three published events from the users database and use that as a source.
36
-     *
37
-     * @param array $data
38
-     * @throws EE_Error
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public function __construct($data = [])
43
-    {
44
-        $this->_data = isset($data['event_ids']) ? $data['event_ids'] : [];
45
-        $this->_setup_attendees_events();
46
-        parent::__construct($data);
47
-    }
48
-
49
-
50
-    /**
51
-     * Returns database safe representation of the data later used to when instantiating this object.
52
-     *
53
-     * @param array $data The incoming data to be prepped.
54
-     *
55
-     * @return array   The prepped data for db
56
-     */
57
-    public static function convert_data_for_persistent_storage($data)
58
-    {
59
-        return $data;
60
-    }
61
-
62
-
63
-    /**
64
-     * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
65
-     * can be sent into this method and converted back into the format used for instantiating with this data handler.
66
-     *
67
-     * @param array $data
68
-     *
69
-     * @return array
70
-     */
71
-    public static function convert_data_from_persistent_storage($data)
72
-    {
73
-        return $data;
74
-    }
75
-
76
-
77
-    /**
78
-     * This will just setup the _events property in the expected format.
79
-     *
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    private function _setup_attendees_events()
84
-    {
85
-
86
-        // setup some attendee objects
87
-        $attendees = $this->_get_some_attendees();
88
-
89
-        // if empty $data we'll do a query to get some events from the server.
90
-        // otherwise we'll retrieve the event data for the given ids.
91
-        $events = $this->_get_some_events($this->_data);
92
-
93
-        $answers_n_questions = $this->_get_some_q_and_as();
94
-
95
-        if (count($events) < 1) {
96
-            throw new EE_Error(
97
-                __(
98
-                    'We can\'t generate a preview for you because there are no active events in your database',
99
-                    'event_espresso'
100
-                )
101
-            );
102
-        }
103
-
104
-
105
-        // now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
106
-        // we'll actually use the generated line_item identifiers for our loop
107
-        $dtts = $tkts = [];
108
-        foreach ($events as $id => $event) {
109
-            if (! $event instanceof EE_Event) {
110
-                continue;
111
-            }
112
-            $this->_events[ $id ]['ID']       = $id;
113
-            $this->_events[ $id ]['name']     = $event->get('EVT_name');
114
-            $datetime                         = $event->get_first_related('Datetime');
115
-            $tickets                          = $datetime instanceof EE_Datetime ? $datetime->get_many_related(
116
-                'Ticket',
117
-                ['default_where_conditions' => 'none']
118
-            ) : [];
119
-            $this->_events[ $id ]['event']    = $event;
120
-            $this->_events[ $id ]['reg_objs'] = [];
121
-            $this->_events[ $id ]['tkt_objs'] = $tickets;
122
-            $this->_events[ $id ]['dtt_objs'] = [];
123
-
124
-            $dttcache = [];
125
-            $tkts     = [];
126
-            foreach ($tickets as $ticket) {
127
-                if (! $ticket instanceof EE_Ticket) {
128
-                    continue;
129
-                }
130
-                $reldatetime                       = $ticket->datetimes();
131
-                $tkts[ $ticket->ID() ]             = [];
132
-                $tkts[ $ticket->ID() ]['ticket']   = $ticket;
133
-                $tkts[ $ticket->ID() ]['dtt_objs'] = $reldatetime;
134
-                $tkts[ $ticket->ID() ]['att_objs'] = $attendees;
135
-                $tkts[ $ticket->ID() ]['count']    = count($attendees);
136
-                $tkts[ $ticket->ID() ]['EE_Event'] = $event;
137
-                foreach ($reldatetime as $datetime) {
138
-                    if ($datetime instanceof EE_Datetime && ! isset($dtts[ $datetime->ID() ])) {
139
-                        $this->_events[ $id ]['dtt_objs'][ $datetime->ID() ] = $datetime;
140
-                        $dtts[ $datetime->ID() ]['datetime']                 = $datetime;
141
-                        $dtts[ $datetime->ID() ]['tkt_objs'][]               = $ticket;
142
-                        $dtts[ $datetime->ID() ]['evt_objs'][]               = $event;
143
-                        $dttcache[ $datetime->ID() ]                         = $datetime;
144
-                    }
145
-                }
146
-            }
147
-
148
-            $this->_events[ $id ]['total_attendees'] = count($attendees);
149
-            $this->_events[ $id ]['att_objs']        = $attendees;
150
-
151
-            // let's also setup the dummy attendees property!
152
-            foreach ($attendees as $att_key => $attendee) {
153
-                if (! $attendee instanceof EE_Attendee) {
154
-                    continue;
155
-                }
156
-                $this->_attendees[ $att_key ]['line_ref'][] =
157
-                    $id;  // so later it can be determined what events this attendee registered for!
158
-                $this->_attendees[ $att_key ]['evt_objs'][] = $event;
159
-                $this->_attendees[ $att_key ]['att_obj']    = $attendee;
160
-                // $this->_attendees[$att_key]['registration_id'] = 0;
161
-                $this->_attendees[ $att_key ]['attendee_email'] = $attendee->email();
162
-                $this->_attendees[ $att_key ]['tkt_objs']       = $tickets;
163
-                if ($att_key == 999999991) {
164
-                    $this->_attendees[ $att_key ]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
-                    $this->_attendees[ $att_key ]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
-                    $this->_attendees[ $att_key ]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
167
-                } elseif ($att_key == 999999992) {
168
-                    $this->_attendees[ $att_key ]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
-                    $this->_attendees[ $att_key ]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
-                    $this->_attendees[ $att_key ]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
171
-                } elseif ($att_key == 999999993) {
172
-                    $this->_attendees[ $att_key ]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
-                    $this->_attendees[ $att_key ]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
-                    $this->_attendees[ $att_key ]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
175
-                }
176
-            }
177
-        }
178
-
179
-        $this->tickets            = $tkts;
180
-        $this->datetimes          = $dtts;
181
-        $this->answers            = $answers_n_questions['answers'];
182
-        $this->questions          = $answers_n_questions['questions'];
183
-        $this->total_ticket_count = count($tkts) * count($this->_attendees);
184
-    }
185
-
186
-
187
-    /**
188
-     * This just returns an array of dummy attendee objects that we'll use to attach to events for our preview data
189
-     *
190
-     * @access private
191
-     * @return array an array of attendee objects
192
-     * @throws EE_Error
193
-     * @throws EE_Error
194
-     */
195
-    private function _get_some_attendees()
196
-    {
197
-        // let's just setup a dummy array of various attendee details
198
-        $dummy_attendees = [
199
-            0 => [
200
-                'Luke',
201
-                'Skywalker',
202
-                '[email protected]',
203
-                '804 Bantha Dr.',
204
-                'Complex 8',
205
-                'Mos Eisley',
206
-                32,
207
-                'US',
208
-                'f0r3e',
209
-                '222-333-4763',
210
-                false,
211
-                '999999991',
212
-            ],
213
-            1 => [
214
-                'Princess',
215
-                'Leia',
216
-                '[email protected]',
217
-                '1456 Valley Way Boulevard',
218
-                'Suite 9',
219
-                'Alderaan',
220
-                15,
221
-                'US',
222
-                'c1h2c',
223
-                '78-123-111-1111',
224
-                false,
225
-                '999999992',
226
-            ],
227
-            2 => [
228
-                'Yoda',
229
-                'I Am',
230
-                '[email protected]',
231
-                '4th Tree',
232
-                '5th Knot',
233
-                'Marsh',
234
-                22,
235
-                'US',
236
-                'l18n',
237
-                '999-999-9999',
238
-                false,
239
-                '999999993',
240
-            ],
241
-        ];
242
-
243
-        // let's generate the attendee objects
244
-        $attendees = [];
245
-        $var_array = [
246
-            'fname',
247
-            'lname',
248
-            'email',
249
-            'address',
250
-            'address2',
251
-            'city',
252
-            'staid',
253
-            'cntry',
254
-            'zip',
255
-            'phone',
256
-            'deleted',
257
-            'attid',
258
-        ];
259
-
260
-        // EE_Registry::instance()->load_class( 'Attendee', array(), FALSE, false, TRUE );
261
-        foreach ($dummy_attendees as $dummy) {
262
-            $att = array_combine($var_array, $dummy);
263
-            extract($att);
264
-            /** @var $fname string */
265
-            /** @var $lname string */
266
-            /** @var $address string */
267
-            /** @var $address2 string */
268
-            /** @var $city string */
269
-            /** @var $staid string */
270
-            /** @var $cntry string */
271
-            /** @var $zip string */
272
-            /** @var $email string */
273
-            /** @var $phone string */
274
-            /** @var $attid string */
275
-            $attendees[ $attid ] = EE_Attendee::new_instance(
276
-                [
277
-                    'ATT_fname'    => $fname,
278
-                    'ATT_lname'    => $lname,
279
-                    'ATT_address'  => $address,
280
-                    'ATT_address2' => $address2,
281
-                    'ATT_city'     => $city,
282
-                    'STA_ID'       => $staid,
283
-                    'CNT_ISO'      => $cntry,
284
-                    'ATT_zip'      => $zip,
285
-                    'ATT_email'    => $email,
286
-                    'ATT_phone'    => $phone,
287
-                    'ATT_ID'       => $attid,
288
-                ]
289
-            );
290
-        }
291
-
292
-        return $attendees;
293
-    }
294
-
295
-
296
-    /**
297
-     * Return an array of dummy question objects indexed by answer id and dummy answer objects indexed by answer id.
298
-     * This will be used in our dummy data setup
299
-     *
300
-     * @return array
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    private function _get_some_q_and_as()
305
-    {
306
-        $quests_array = [
307
-            0 => [
308
-                555,
309
-                __('What is your favorite planet?', 'event_espresso'),
310
-                0,
311
-            ],
312
-            1 => [
313
-                556,
314
-                __('What is your favorite food?', 'event_espresso'),
315
-                0,
316
-            ],
317
-            2 => [
318
-                557,
319
-                __('How many lightyears have you travelled', 'event_espresso'),
320
-                0,
321
-            ],
322
-        ];
323
-
324
-        $ans_array = [
325
-            0 => [
326
-                999,
327
-                555,
328
-                'Tattoine',
329
-            ],
330
-            1 => [
331
-                1000,
332
-                555,
333
-                'Alderaan',
334
-            ],
335
-            2 => [
336
-                1001,
337
-                555,
338
-                'Dantooine',
339
-            ],
340
-            3 => [
341
-                1002,
342
-                556,
343
-                'Fish Fingers',
344
-            ],
345
-            4 => [
346
-                1003,
347
-                556,
348
-                'Sushi',
349
-            ],
350
-            5 => [
351
-                1004,
352
-                556,
353
-                'Water',
354
-            ],
355
-            6 => [
356
-                1005,
357
-                557,
358
-                'A lot',
359
-            ],
360
-            7 => [
361
-                1006,
362
-                557,
363
-                "That's none of your business.",
364
-            ],
365
-            8 => [
366
-                1007,
367
-                557,
368
-                "People less travel me then.",
369
-            ],
370
-        ];
371
-
372
-        $qst_columns = ['QST_ID', 'QST_display_text', 'QST_system'];
373
-        $ans_columns = ['ANS_ID', 'QST_ID', 'ANS_value'];
374
-
375
-        // EE_Registry::instance()->load_class( 'Question', array(), FALSE, TRUE, TRUE );
376
-        // EE_Registry::instance()->load_class( 'Answer', array(), FALSE, TRUE, TRUE );
377
-
378
-        $qsts = [];
379
-        // first the questions
380
-        foreach ($quests_array as $qst) {
381
-            $qstobj                    = array_combine($qst_columns, $qst);
382
-            $qsts[ $qstobj['QST_ID'] ] = EE_Question::new_instance($qstobj);
383
-        }
384
-
385
-        // now the answers (and we'll setup our arrays)
386
-        $q_n_as = [];
387
-        foreach ($ans_array as $ans) {
388
-            $ansobj                               = array_combine($ans_columns, $ans);
389
-            $ansobj                               = EE_Answer::new_instance($ansobj);
390
-            $q_n_as['answers'][ $ansobj->ID() ]   = $ansobj;
391
-            $q_n_as['questions'][ $ansobj->ID() ] = $qsts[ $ansobj->get('QST_ID') ];
392
-        }
393
-
394
-        return $q_n_as;
395
-    }
396
-
397
-
398
-    /**
399
-     * Return an array of event objects from the database
400
-     *
401
-     * If event ids are not included then we'll just retrieve the first published event from the database.
402
-     *
403
-     * @param array $event_ids if set, this will be an array of event ids to obtain events for.
404
-     *
405
-     * @return array    An array of event objects from the db.
406
-     * @throws EE_Error
407
-     */
408
-    private function _get_some_events(array $event_ids = [])
409
-    {
410
-        /** @var RequestInterface $request */
411
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
412
-        // if we have an evt_id then we want to make sure we use that for the preview
413
-        // (because a specific event template is being viewed);
414
-        $event_ids = $request->getRequestParam('evt_id', $event_ids, 'arrayOf|int');
415
-        $limit     = ! empty($event_ids)
416
-            ? null
417
-            : apply_filters('FHEE__EE_Messages_Preview_incoming_data___get_some_events__limit', '0,1');
418
-
419
-        $where = ! empty($event_ids)
420
-            ? [
421
-                'EVT_ID'                 => ['IN', $event_ids],
422
-                'Datetime.Ticket.TKT_ID' => ['>', 1],
423
-            ]
424
-            : ['Datetime.Ticket.TKT_ID' => ['>', 1]];
425
-
426
-        return EEM_Event::instance()->get_all([$where, 'limit' => $limit]);
427
-    }
428
-
429
-
430
-    /**
431
-     * @throws EE_Error
432
-     * @throws ReflectionException
433
-     */
434
-    protected function _setup_data()
435
-    {
436
-        // need to figure out the running total for test purposes so... we're going to create a temp cart and add the tickets to it!
437
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
438
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
439
-            $session = EE_Registry::instance()->SSN;
440
-        } else {
441
-            $session = EE_Registry::instance()->load_core('Session');
442
-        }
443
-        $cart = EE_Cart::instance(null, $session);
444
-
445
-        // add tickets to cart
446
-        foreach ($this->tickets as $ticket) {
447
-            $cart->add_ticket_to_cart($ticket['ticket']);
448
-        }
449
-
450
-        // setup txn property
451
-        $this->txn = EE_Transaction::new_instance(
452
-            [
453
-                'TXN_timestamp'    => time(), // unix timestamp
454
-                'TXN_total'        => 0, // txn_total
455
-                'TXN_paid'         => 0, // txn_paid
456
-                'STS_ID'           => EEM_Transaction::incomplete_status_code, // sts_id
457
-                'TXN_session_data' => null, // dump of txn session object (we're just going to leave blank here)
458
-                'TXN_hash_salt'    => null, // hash salt blank as well
459
-                'TXN_ID'           => 999999,
460
-            ]
461
-        );
462
-
463
-
464
-        // setup reg_objects
465
-        // note we're setting up a reg object for each attendee in each event but ALSO adding to the reg_object array.
466
-        $this->reg_objs = [];
467
-        $regid          = 9999990;
468
-        foreach ($this->_attendees as $key => $attendee) {
469
-            // note we need to setup reg_objects for each event this attendee belongs to
470
-            $regatt = $attendee['att_obj'] instanceof EE_Attendee ? $attendee['att_obj']->ID() : null;
471
-            $regtxn = $this->txn->ID();
472
-            $regcnt = 1;
473
-            foreach ($attendee['line_ref'] as $evtid) {
474
-                foreach ($this->_events[ $evtid ]['tkt_objs'] as $ticket) {
475
-                    if (! $ticket instanceof EE_Ticket) {
476
-                        continue;
477
-                    }
478
-                    $reg_array                                            = [
479
-                        'EVT_ID'           => $evtid,
480
-                        'ATT_ID'           => $regatt,
481
-                        'TXN_ID'           => $regtxn,
482
-                        'TKT_ID'           => $ticket->ID(),
483
-                        'STS_ID'           => EEM_Registration::status_id_pending_payment,
484
-                        'REG_date'         => time(),
485
-                        'REG_final_price'  => $ticket->get('TKT_price'),
486
-                        'REG_session'      => 'dummy_session_id',
487
-                        'REG_code'         => $regid . '-dummy-generated-code',
488
-                        'REG_url_link'     => $regcnt . '-daafpapasdlfakasdfpqasdfasdf',
489
-                        'REG_count'        => $regcnt,
490
-                        'REG_group_size'   => $this->_events[ $evtid ]['total_attendees'],
491
-                        'REG_att_is_going' => true,
492
-                        'REG_ID'           => $regid,
493
-                    ];
494
-                    $REG_OBJ                                              = EE_Registration::new_instance($reg_array);
495
-                    $this->_attendees[ $key ]['reg_objs'][ $regid ]       = $REG_OBJ;
496
-                    $this->_events[ $evtid ]['reg_objs'][]                = $REG_OBJ;
497
-                    $this->reg_objs[]                                     = $REG_OBJ;
498
-                    $this->tickets[ $ticket->ID() ]['reg_objs'][ $regid ] = $REG_OBJ;
499
-
500
-                    $regcnt++;
501
-                    $regid++;
502
-                }
503
-            }
504
-        }
505
-
506
-
507
-        // setup line items!
508
-        $line_item_total = EEH_Line_Item::create_total_line_item($this->txn);
509
-
510
-        // add tickets
511
-        foreach ($this->tickets as $item) {
512
-            $qty    = $item['count'];
513
-            $ticket = $item['ticket'];
514
-            EEH_Line_Item::add_ticket_purchase($line_item_total, $ticket, $qty);
515
-        }
516
-
517
-        $shipping_line_item = EE_Line_Item::new_instance(
518
-            [
519
-                'LIN_name'       => __('Shipping Surcharge',
520
-                                       'event_espresso'),
521
-                'LIN_desc'       => __('Sent via Millenium Falcon',
522
-                                       'event_espresso'),
523
-                'LIN_unit_price' => 20,
524
-                'LIN_quantity'   => 1,
525
-                'LIN_is_taxable' => true,
526
-                'LIN_total'      => 20,
527
-                'LIN_type'       => EEM_Line_Item::type_line_item,
528
-            ]
529
-        );
530
-        EEH_Line_Item::add_item($line_item_total, $shipping_line_item);
531
-        $this->additional_line_items = [$shipping_line_item];
532
-
533
-        // now let's add taxes
534
-        EEH_Line_Item::apply_taxes($line_item_total);
535
-
536
-        // now we should be able to get the items we need from this object
537
-        $event_line_items = EEH_Line_Item::get_pre_tax_subtotal($line_item_total)->children();
538
-        $line_items       = [];
539
-        foreach ($event_line_items as $line_item) {
540
-            if (! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
541
-                continue;
542
-            }
543
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
544
-            foreach ($ticket_line_items as $ticket_line_item) {
545
-                if (! $ticket_line_item instanceof EE_Line_Item) {
546
-                    continue;
547
-                }
548
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['line_item']      = $ticket_line_item;
549
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['sub_line_items'] = $ticket_line_item->children();
550
-                $line_items[ $ticket_line_item->ID() ]['children']              = $ticket_line_item->children();
551
-                $line_items[ $ticket_line_item->ID() ]['EE_Ticket']             =
552
-                    $this->tickets[ $ticket_line_item->OBJ_ID() ]['ticket'];
553
-            }
554
-        }
555
-
556
-        $this->line_items_with_children = $line_items;
557
-        $this->tax_line_items           = $line_item_total->tax_descendants();
558
-
559
-        // add proper total to transaction object.
560
-        $grand_total                 = $line_item_total->recalculate_total_including_taxes();
561
-        $this->grand_total_line_item = $line_item_total;
562
-        $this->txn->set_total($grand_total);
563
-
564
-
565
-        // add additional details for each registration
566
-        foreach ($this->reg_objs as $reg) {
567
-            if (! $reg instanceof EE_Registration) {
568
-                continue;
569
-            }
570
-            $this->_registrations[ $reg->ID() ]['tkt_obj']  = $this->tickets[ $reg->get('TKT_ID') ]['ticket'];
571
-            $this->_registrations[ $reg->ID() ]['evt_obj']  = $this->_events[ $reg->get('EVT_ID') ]['event'];
572
-            $this->_registrations[ $reg->ID() ]['reg_obj']  = $reg;
573
-            $this->_registrations[ $reg->ID() ]['ans_objs'] = $this->_attendees[ $reg->get('ATT_ID') ]['ans_objs'];
574
-            $this->_registrations[ $reg->ID() ]['att_obj']  = $this->_attendees[ $reg->get('ATT_ID') ]['att_obj'];
575
-            $this->_registrations[ $reg->ID() ]['dtt_objs'] = $this->tickets[ $reg->get('TKT_ID') ]['dtt_objs'];
576
-        }
577
-
578
-
579
-        // events and attendees
580
-        $this->events        = $this->_events;
581
-        $this->attendees     = $this->_attendees;
582
-        $this->registrations = $this->_registrations;
583
-
584
-        $attendees_to_shift = $this->_attendees;
585
-
586
-        // setup primary attendee property
587
-        $this->primary_attendee_data = [
588
-            'fname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
589
-                ? $this->_attendees[999999991]['att_obj']->fname()
590
-                : '',
591
-
592
-            'lname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
593
-                ? $this->_attendees[999999991]['att_obj']->lname()
594
-                : '',
595
-
596
-            'email' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
597
-                ? $this->_attendees[999999991]['att_obj']->email()
598
-                : '',
599
-
600
-            'att_obj' => $this->_attendees[999999991]['att_obj'],
601
-
602
-            'reg_obj' => array_shift($attendees_to_shift[999999991]['reg_objs']),
603
-        ];
604
-
605
-        // reg_info property
606
-        // note this isn't referenced by any shortcode parsers so we'll ignore for now.
607
-        $this->reg_info = [];
608
-
609
-        // let's set a reg_obj for messengers expecting one.
610
-        $this->reg_obj = array_shift($this->_attendees[999999991]['reg_objs']);
611
-
612
-        // the below are just dummy items.
613
-        $this->user_id     = 1;
614
-        $this->ip_address  = '192.0.2.1';
615
-        $this->user_agent  = '';
616
-        $this->init_access = time();
617
-        $this->last_access = time();
618
-    }
24
+	// some specific properties we need for this class
25
+	private $_events        = [];
26
+
27
+	private $_attendees     = [];
28
+
29
+	private $_registrations = [];
30
+
31
+
32
+	/**
33
+	 * For the constructor of this special preview class.  We're either looking for an event id or empty data.  If we
34
+	 * have an event id (or ids) then we'll use that as the source for the "dummy" data.  If the data is empty then
35
+	 * we'll get the first three published events from the users database and use that as a source.
36
+	 *
37
+	 * @param array $data
38
+	 * @throws EE_Error
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function __construct($data = [])
43
+	{
44
+		$this->_data = isset($data['event_ids']) ? $data['event_ids'] : [];
45
+		$this->_setup_attendees_events();
46
+		parent::__construct($data);
47
+	}
48
+
49
+
50
+	/**
51
+	 * Returns database safe representation of the data later used to when instantiating this object.
52
+	 *
53
+	 * @param array $data The incoming data to be prepped.
54
+	 *
55
+	 * @return array   The prepped data for db
56
+	 */
57
+	public static function convert_data_for_persistent_storage($data)
58
+	{
59
+		return $data;
60
+	}
61
+
62
+
63
+	/**
64
+	 * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
65
+	 * can be sent into this method and converted back into the format used for instantiating with this data handler.
66
+	 *
67
+	 * @param array $data
68
+	 *
69
+	 * @return array
70
+	 */
71
+	public static function convert_data_from_persistent_storage($data)
72
+	{
73
+		return $data;
74
+	}
75
+
76
+
77
+	/**
78
+	 * This will just setup the _events property in the expected format.
79
+	 *
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	private function _setup_attendees_events()
84
+	{
85
+
86
+		// setup some attendee objects
87
+		$attendees = $this->_get_some_attendees();
88
+
89
+		// if empty $data we'll do a query to get some events from the server.
90
+		// otherwise we'll retrieve the event data for the given ids.
91
+		$events = $this->_get_some_events($this->_data);
92
+
93
+		$answers_n_questions = $this->_get_some_q_and_as();
94
+
95
+		if (count($events) < 1) {
96
+			throw new EE_Error(
97
+				__(
98
+					'We can\'t generate a preview for you because there are no active events in your database',
99
+					'event_espresso'
100
+				)
101
+			);
102
+		}
103
+
104
+
105
+		// now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
106
+		// we'll actually use the generated line_item identifiers for our loop
107
+		$dtts = $tkts = [];
108
+		foreach ($events as $id => $event) {
109
+			if (! $event instanceof EE_Event) {
110
+				continue;
111
+			}
112
+			$this->_events[ $id ]['ID']       = $id;
113
+			$this->_events[ $id ]['name']     = $event->get('EVT_name');
114
+			$datetime                         = $event->get_first_related('Datetime');
115
+			$tickets                          = $datetime instanceof EE_Datetime ? $datetime->get_many_related(
116
+				'Ticket',
117
+				['default_where_conditions' => 'none']
118
+			) : [];
119
+			$this->_events[ $id ]['event']    = $event;
120
+			$this->_events[ $id ]['reg_objs'] = [];
121
+			$this->_events[ $id ]['tkt_objs'] = $tickets;
122
+			$this->_events[ $id ]['dtt_objs'] = [];
123
+
124
+			$dttcache = [];
125
+			$tkts     = [];
126
+			foreach ($tickets as $ticket) {
127
+				if (! $ticket instanceof EE_Ticket) {
128
+					continue;
129
+				}
130
+				$reldatetime                       = $ticket->datetimes();
131
+				$tkts[ $ticket->ID() ]             = [];
132
+				$tkts[ $ticket->ID() ]['ticket']   = $ticket;
133
+				$tkts[ $ticket->ID() ]['dtt_objs'] = $reldatetime;
134
+				$tkts[ $ticket->ID() ]['att_objs'] = $attendees;
135
+				$tkts[ $ticket->ID() ]['count']    = count($attendees);
136
+				$tkts[ $ticket->ID() ]['EE_Event'] = $event;
137
+				foreach ($reldatetime as $datetime) {
138
+					if ($datetime instanceof EE_Datetime && ! isset($dtts[ $datetime->ID() ])) {
139
+						$this->_events[ $id ]['dtt_objs'][ $datetime->ID() ] = $datetime;
140
+						$dtts[ $datetime->ID() ]['datetime']                 = $datetime;
141
+						$dtts[ $datetime->ID() ]['tkt_objs'][]               = $ticket;
142
+						$dtts[ $datetime->ID() ]['evt_objs'][]               = $event;
143
+						$dttcache[ $datetime->ID() ]                         = $datetime;
144
+					}
145
+				}
146
+			}
147
+
148
+			$this->_events[ $id ]['total_attendees'] = count($attendees);
149
+			$this->_events[ $id ]['att_objs']        = $attendees;
150
+
151
+			// let's also setup the dummy attendees property!
152
+			foreach ($attendees as $att_key => $attendee) {
153
+				if (! $attendee instanceof EE_Attendee) {
154
+					continue;
155
+				}
156
+				$this->_attendees[ $att_key ]['line_ref'][] =
157
+					$id;  // so later it can be determined what events this attendee registered for!
158
+				$this->_attendees[ $att_key ]['evt_objs'][] = $event;
159
+				$this->_attendees[ $att_key ]['att_obj']    = $attendee;
160
+				// $this->_attendees[$att_key]['registration_id'] = 0;
161
+				$this->_attendees[ $att_key ]['attendee_email'] = $attendee->email();
162
+				$this->_attendees[ $att_key ]['tkt_objs']       = $tickets;
163
+				if ($att_key == 999999991) {
164
+					$this->_attendees[ $att_key ]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
+					$this->_attendees[ $att_key ]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
+					$this->_attendees[ $att_key ]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
167
+				} elseif ($att_key == 999999992) {
168
+					$this->_attendees[ $att_key ]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
+					$this->_attendees[ $att_key ]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
+					$this->_attendees[ $att_key ]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
171
+				} elseif ($att_key == 999999993) {
172
+					$this->_attendees[ $att_key ]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
+					$this->_attendees[ $att_key ]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
+					$this->_attendees[ $att_key ]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
175
+				}
176
+			}
177
+		}
178
+
179
+		$this->tickets            = $tkts;
180
+		$this->datetimes          = $dtts;
181
+		$this->answers            = $answers_n_questions['answers'];
182
+		$this->questions          = $answers_n_questions['questions'];
183
+		$this->total_ticket_count = count($tkts) * count($this->_attendees);
184
+	}
185
+
186
+
187
+	/**
188
+	 * This just returns an array of dummy attendee objects that we'll use to attach to events for our preview data
189
+	 *
190
+	 * @access private
191
+	 * @return array an array of attendee objects
192
+	 * @throws EE_Error
193
+	 * @throws EE_Error
194
+	 */
195
+	private function _get_some_attendees()
196
+	{
197
+		// let's just setup a dummy array of various attendee details
198
+		$dummy_attendees = [
199
+			0 => [
200
+				'Luke',
201
+				'Skywalker',
202
+				'[email protected]',
203
+				'804 Bantha Dr.',
204
+				'Complex 8',
205
+				'Mos Eisley',
206
+				32,
207
+				'US',
208
+				'f0r3e',
209
+				'222-333-4763',
210
+				false,
211
+				'999999991',
212
+			],
213
+			1 => [
214
+				'Princess',
215
+				'Leia',
216
+				'[email protected]',
217
+				'1456 Valley Way Boulevard',
218
+				'Suite 9',
219
+				'Alderaan',
220
+				15,
221
+				'US',
222
+				'c1h2c',
223
+				'78-123-111-1111',
224
+				false,
225
+				'999999992',
226
+			],
227
+			2 => [
228
+				'Yoda',
229
+				'I Am',
230
+				'[email protected]',
231
+				'4th Tree',
232
+				'5th Knot',
233
+				'Marsh',
234
+				22,
235
+				'US',
236
+				'l18n',
237
+				'999-999-9999',
238
+				false,
239
+				'999999993',
240
+			],
241
+		];
242
+
243
+		// let's generate the attendee objects
244
+		$attendees = [];
245
+		$var_array = [
246
+			'fname',
247
+			'lname',
248
+			'email',
249
+			'address',
250
+			'address2',
251
+			'city',
252
+			'staid',
253
+			'cntry',
254
+			'zip',
255
+			'phone',
256
+			'deleted',
257
+			'attid',
258
+		];
259
+
260
+		// EE_Registry::instance()->load_class( 'Attendee', array(), FALSE, false, TRUE );
261
+		foreach ($dummy_attendees as $dummy) {
262
+			$att = array_combine($var_array, $dummy);
263
+			extract($att);
264
+			/** @var $fname string */
265
+			/** @var $lname string */
266
+			/** @var $address string */
267
+			/** @var $address2 string */
268
+			/** @var $city string */
269
+			/** @var $staid string */
270
+			/** @var $cntry string */
271
+			/** @var $zip string */
272
+			/** @var $email string */
273
+			/** @var $phone string */
274
+			/** @var $attid string */
275
+			$attendees[ $attid ] = EE_Attendee::new_instance(
276
+				[
277
+					'ATT_fname'    => $fname,
278
+					'ATT_lname'    => $lname,
279
+					'ATT_address'  => $address,
280
+					'ATT_address2' => $address2,
281
+					'ATT_city'     => $city,
282
+					'STA_ID'       => $staid,
283
+					'CNT_ISO'      => $cntry,
284
+					'ATT_zip'      => $zip,
285
+					'ATT_email'    => $email,
286
+					'ATT_phone'    => $phone,
287
+					'ATT_ID'       => $attid,
288
+				]
289
+			);
290
+		}
291
+
292
+		return $attendees;
293
+	}
294
+
295
+
296
+	/**
297
+	 * Return an array of dummy question objects indexed by answer id and dummy answer objects indexed by answer id.
298
+	 * This will be used in our dummy data setup
299
+	 *
300
+	 * @return array
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	private function _get_some_q_and_as()
305
+	{
306
+		$quests_array = [
307
+			0 => [
308
+				555,
309
+				__('What is your favorite planet?', 'event_espresso'),
310
+				0,
311
+			],
312
+			1 => [
313
+				556,
314
+				__('What is your favorite food?', 'event_espresso'),
315
+				0,
316
+			],
317
+			2 => [
318
+				557,
319
+				__('How many lightyears have you travelled', 'event_espresso'),
320
+				0,
321
+			],
322
+		];
323
+
324
+		$ans_array = [
325
+			0 => [
326
+				999,
327
+				555,
328
+				'Tattoine',
329
+			],
330
+			1 => [
331
+				1000,
332
+				555,
333
+				'Alderaan',
334
+			],
335
+			2 => [
336
+				1001,
337
+				555,
338
+				'Dantooine',
339
+			],
340
+			3 => [
341
+				1002,
342
+				556,
343
+				'Fish Fingers',
344
+			],
345
+			4 => [
346
+				1003,
347
+				556,
348
+				'Sushi',
349
+			],
350
+			5 => [
351
+				1004,
352
+				556,
353
+				'Water',
354
+			],
355
+			6 => [
356
+				1005,
357
+				557,
358
+				'A lot',
359
+			],
360
+			7 => [
361
+				1006,
362
+				557,
363
+				"That's none of your business.",
364
+			],
365
+			8 => [
366
+				1007,
367
+				557,
368
+				"People less travel me then.",
369
+			],
370
+		];
371
+
372
+		$qst_columns = ['QST_ID', 'QST_display_text', 'QST_system'];
373
+		$ans_columns = ['ANS_ID', 'QST_ID', 'ANS_value'];
374
+
375
+		// EE_Registry::instance()->load_class( 'Question', array(), FALSE, TRUE, TRUE );
376
+		// EE_Registry::instance()->load_class( 'Answer', array(), FALSE, TRUE, TRUE );
377
+
378
+		$qsts = [];
379
+		// first the questions
380
+		foreach ($quests_array as $qst) {
381
+			$qstobj                    = array_combine($qst_columns, $qst);
382
+			$qsts[ $qstobj['QST_ID'] ] = EE_Question::new_instance($qstobj);
383
+		}
384
+
385
+		// now the answers (and we'll setup our arrays)
386
+		$q_n_as = [];
387
+		foreach ($ans_array as $ans) {
388
+			$ansobj                               = array_combine($ans_columns, $ans);
389
+			$ansobj                               = EE_Answer::new_instance($ansobj);
390
+			$q_n_as['answers'][ $ansobj->ID() ]   = $ansobj;
391
+			$q_n_as['questions'][ $ansobj->ID() ] = $qsts[ $ansobj->get('QST_ID') ];
392
+		}
393
+
394
+		return $q_n_as;
395
+	}
396
+
397
+
398
+	/**
399
+	 * Return an array of event objects from the database
400
+	 *
401
+	 * If event ids are not included then we'll just retrieve the first published event from the database.
402
+	 *
403
+	 * @param array $event_ids if set, this will be an array of event ids to obtain events for.
404
+	 *
405
+	 * @return array    An array of event objects from the db.
406
+	 * @throws EE_Error
407
+	 */
408
+	private function _get_some_events(array $event_ids = [])
409
+	{
410
+		/** @var RequestInterface $request */
411
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
412
+		// if we have an evt_id then we want to make sure we use that for the preview
413
+		// (because a specific event template is being viewed);
414
+		$event_ids = $request->getRequestParam('evt_id', $event_ids, 'arrayOf|int');
415
+		$limit     = ! empty($event_ids)
416
+			? null
417
+			: apply_filters('FHEE__EE_Messages_Preview_incoming_data___get_some_events__limit', '0,1');
418
+
419
+		$where = ! empty($event_ids)
420
+			? [
421
+				'EVT_ID'                 => ['IN', $event_ids],
422
+				'Datetime.Ticket.TKT_ID' => ['>', 1],
423
+			]
424
+			: ['Datetime.Ticket.TKT_ID' => ['>', 1]];
425
+
426
+		return EEM_Event::instance()->get_all([$where, 'limit' => $limit]);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @throws EE_Error
432
+	 * @throws ReflectionException
433
+	 */
434
+	protected function _setup_data()
435
+	{
436
+		// need to figure out the running total for test purposes so... we're going to create a temp cart and add the tickets to it!
437
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
438
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
439
+			$session = EE_Registry::instance()->SSN;
440
+		} else {
441
+			$session = EE_Registry::instance()->load_core('Session');
442
+		}
443
+		$cart = EE_Cart::instance(null, $session);
444
+
445
+		// add tickets to cart
446
+		foreach ($this->tickets as $ticket) {
447
+			$cart->add_ticket_to_cart($ticket['ticket']);
448
+		}
449
+
450
+		// setup txn property
451
+		$this->txn = EE_Transaction::new_instance(
452
+			[
453
+				'TXN_timestamp'    => time(), // unix timestamp
454
+				'TXN_total'        => 0, // txn_total
455
+				'TXN_paid'         => 0, // txn_paid
456
+				'STS_ID'           => EEM_Transaction::incomplete_status_code, // sts_id
457
+				'TXN_session_data' => null, // dump of txn session object (we're just going to leave blank here)
458
+				'TXN_hash_salt'    => null, // hash salt blank as well
459
+				'TXN_ID'           => 999999,
460
+			]
461
+		);
462
+
463
+
464
+		// setup reg_objects
465
+		// note we're setting up a reg object for each attendee in each event but ALSO adding to the reg_object array.
466
+		$this->reg_objs = [];
467
+		$regid          = 9999990;
468
+		foreach ($this->_attendees as $key => $attendee) {
469
+			// note we need to setup reg_objects for each event this attendee belongs to
470
+			$regatt = $attendee['att_obj'] instanceof EE_Attendee ? $attendee['att_obj']->ID() : null;
471
+			$regtxn = $this->txn->ID();
472
+			$regcnt = 1;
473
+			foreach ($attendee['line_ref'] as $evtid) {
474
+				foreach ($this->_events[ $evtid ]['tkt_objs'] as $ticket) {
475
+					if (! $ticket instanceof EE_Ticket) {
476
+						continue;
477
+					}
478
+					$reg_array                                            = [
479
+						'EVT_ID'           => $evtid,
480
+						'ATT_ID'           => $regatt,
481
+						'TXN_ID'           => $regtxn,
482
+						'TKT_ID'           => $ticket->ID(),
483
+						'STS_ID'           => EEM_Registration::status_id_pending_payment,
484
+						'REG_date'         => time(),
485
+						'REG_final_price'  => $ticket->get('TKT_price'),
486
+						'REG_session'      => 'dummy_session_id',
487
+						'REG_code'         => $regid . '-dummy-generated-code',
488
+						'REG_url_link'     => $regcnt . '-daafpapasdlfakasdfpqasdfasdf',
489
+						'REG_count'        => $regcnt,
490
+						'REG_group_size'   => $this->_events[ $evtid ]['total_attendees'],
491
+						'REG_att_is_going' => true,
492
+						'REG_ID'           => $regid,
493
+					];
494
+					$REG_OBJ                                              = EE_Registration::new_instance($reg_array);
495
+					$this->_attendees[ $key ]['reg_objs'][ $regid ]       = $REG_OBJ;
496
+					$this->_events[ $evtid ]['reg_objs'][]                = $REG_OBJ;
497
+					$this->reg_objs[]                                     = $REG_OBJ;
498
+					$this->tickets[ $ticket->ID() ]['reg_objs'][ $regid ] = $REG_OBJ;
499
+
500
+					$regcnt++;
501
+					$regid++;
502
+				}
503
+			}
504
+		}
505
+
506
+
507
+		// setup line items!
508
+		$line_item_total = EEH_Line_Item::create_total_line_item($this->txn);
509
+
510
+		// add tickets
511
+		foreach ($this->tickets as $item) {
512
+			$qty    = $item['count'];
513
+			$ticket = $item['ticket'];
514
+			EEH_Line_Item::add_ticket_purchase($line_item_total, $ticket, $qty);
515
+		}
516
+
517
+		$shipping_line_item = EE_Line_Item::new_instance(
518
+			[
519
+				'LIN_name'       => __('Shipping Surcharge',
520
+									   'event_espresso'),
521
+				'LIN_desc'       => __('Sent via Millenium Falcon',
522
+									   'event_espresso'),
523
+				'LIN_unit_price' => 20,
524
+				'LIN_quantity'   => 1,
525
+				'LIN_is_taxable' => true,
526
+				'LIN_total'      => 20,
527
+				'LIN_type'       => EEM_Line_Item::type_line_item,
528
+			]
529
+		);
530
+		EEH_Line_Item::add_item($line_item_total, $shipping_line_item);
531
+		$this->additional_line_items = [$shipping_line_item];
532
+
533
+		// now let's add taxes
534
+		EEH_Line_Item::apply_taxes($line_item_total);
535
+
536
+		// now we should be able to get the items we need from this object
537
+		$event_line_items = EEH_Line_Item::get_pre_tax_subtotal($line_item_total)->children();
538
+		$line_items       = [];
539
+		foreach ($event_line_items as $line_item) {
540
+			if (! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
541
+				continue;
542
+			}
543
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
544
+			foreach ($ticket_line_items as $ticket_line_item) {
545
+				if (! $ticket_line_item instanceof EE_Line_Item) {
546
+					continue;
547
+				}
548
+				$this->tickets[ $ticket_line_item->OBJ_ID() ]['line_item']      = $ticket_line_item;
549
+				$this->tickets[ $ticket_line_item->OBJ_ID() ]['sub_line_items'] = $ticket_line_item->children();
550
+				$line_items[ $ticket_line_item->ID() ]['children']              = $ticket_line_item->children();
551
+				$line_items[ $ticket_line_item->ID() ]['EE_Ticket']             =
552
+					$this->tickets[ $ticket_line_item->OBJ_ID() ]['ticket'];
553
+			}
554
+		}
555
+
556
+		$this->line_items_with_children = $line_items;
557
+		$this->tax_line_items           = $line_item_total->tax_descendants();
558
+
559
+		// add proper total to transaction object.
560
+		$grand_total                 = $line_item_total->recalculate_total_including_taxes();
561
+		$this->grand_total_line_item = $line_item_total;
562
+		$this->txn->set_total($grand_total);
563
+
564
+
565
+		// add additional details for each registration
566
+		foreach ($this->reg_objs as $reg) {
567
+			if (! $reg instanceof EE_Registration) {
568
+				continue;
569
+			}
570
+			$this->_registrations[ $reg->ID() ]['tkt_obj']  = $this->tickets[ $reg->get('TKT_ID') ]['ticket'];
571
+			$this->_registrations[ $reg->ID() ]['evt_obj']  = $this->_events[ $reg->get('EVT_ID') ]['event'];
572
+			$this->_registrations[ $reg->ID() ]['reg_obj']  = $reg;
573
+			$this->_registrations[ $reg->ID() ]['ans_objs'] = $this->_attendees[ $reg->get('ATT_ID') ]['ans_objs'];
574
+			$this->_registrations[ $reg->ID() ]['att_obj']  = $this->_attendees[ $reg->get('ATT_ID') ]['att_obj'];
575
+			$this->_registrations[ $reg->ID() ]['dtt_objs'] = $this->tickets[ $reg->get('TKT_ID') ]['dtt_objs'];
576
+		}
577
+
578
+
579
+		// events and attendees
580
+		$this->events        = $this->_events;
581
+		$this->attendees     = $this->_attendees;
582
+		$this->registrations = $this->_registrations;
583
+
584
+		$attendees_to_shift = $this->_attendees;
585
+
586
+		// setup primary attendee property
587
+		$this->primary_attendee_data = [
588
+			'fname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
589
+				? $this->_attendees[999999991]['att_obj']->fname()
590
+				: '',
591
+
592
+			'lname' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
593
+				? $this->_attendees[999999991]['att_obj']->lname()
594
+				: '',
595
+
596
+			'email' => $this->_attendees[999999991]['att_obj'] instanceof EE_Attendee
597
+				? $this->_attendees[999999991]['att_obj']->email()
598
+				: '',
599
+
600
+			'att_obj' => $this->_attendees[999999991]['att_obj'],
601
+
602
+			'reg_obj' => array_shift($attendees_to_shift[999999991]['reg_objs']),
603
+		];
604
+
605
+		// reg_info property
606
+		// note this isn't referenced by any shortcode parsers so we'll ignore for now.
607
+		$this->reg_info = [];
608
+
609
+		// let's set a reg_obj for messengers expecting one.
610
+		$this->reg_obj = array_shift($this->_attendees[999999991]['reg_objs']);
611
+
612
+		// the below are just dummy items.
613
+		$this->user_id     = 1;
614
+		$this->ip_address  = '192.0.2.1';
615
+		$this->user_agent  = '';
616
+		$this->init_access = time();
617
+		$this->last_access = time();
618
+	}
619 619
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -106,72 +106,72 @@  discard block
 block discarded – undo
106 106
         // we'll actually use the generated line_item identifiers for our loop
107 107
         $dtts = $tkts = [];
108 108
         foreach ($events as $id => $event) {
109
-            if (! $event instanceof EE_Event) {
109
+            if ( ! $event instanceof EE_Event) {
110 110
                 continue;
111 111
             }
112
-            $this->_events[ $id ]['ID']       = $id;
113
-            $this->_events[ $id ]['name']     = $event->get('EVT_name');
112
+            $this->_events[$id]['ID']       = $id;
113
+            $this->_events[$id]['name']     = $event->get('EVT_name');
114 114
             $datetime                         = $event->get_first_related('Datetime');
115 115
             $tickets                          = $datetime instanceof EE_Datetime ? $datetime->get_many_related(
116 116
                 'Ticket',
117 117
                 ['default_where_conditions' => 'none']
118 118
             ) : [];
119
-            $this->_events[ $id ]['event']    = $event;
120
-            $this->_events[ $id ]['reg_objs'] = [];
121
-            $this->_events[ $id ]['tkt_objs'] = $tickets;
122
-            $this->_events[ $id ]['dtt_objs'] = [];
119
+            $this->_events[$id]['event']    = $event;
120
+            $this->_events[$id]['reg_objs'] = [];
121
+            $this->_events[$id]['tkt_objs'] = $tickets;
122
+            $this->_events[$id]['dtt_objs'] = [];
123 123
 
124 124
             $dttcache = [];
125 125
             $tkts     = [];
126 126
             foreach ($tickets as $ticket) {
127
-                if (! $ticket instanceof EE_Ticket) {
127
+                if ( ! $ticket instanceof EE_Ticket) {
128 128
                     continue;
129 129
                 }
130 130
                 $reldatetime                       = $ticket->datetimes();
131
-                $tkts[ $ticket->ID() ]             = [];
132
-                $tkts[ $ticket->ID() ]['ticket']   = $ticket;
133
-                $tkts[ $ticket->ID() ]['dtt_objs'] = $reldatetime;
134
-                $tkts[ $ticket->ID() ]['att_objs'] = $attendees;
135
-                $tkts[ $ticket->ID() ]['count']    = count($attendees);
136
-                $tkts[ $ticket->ID() ]['EE_Event'] = $event;
131
+                $tkts[$ticket->ID()]             = [];
132
+                $tkts[$ticket->ID()]['ticket']   = $ticket;
133
+                $tkts[$ticket->ID()]['dtt_objs'] = $reldatetime;
134
+                $tkts[$ticket->ID()]['att_objs'] = $attendees;
135
+                $tkts[$ticket->ID()]['count']    = count($attendees);
136
+                $tkts[$ticket->ID()]['EE_Event'] = $event;
137 137
                 foreach ($reldatetime as $datetime) {
138
-                    if ($datetime instanceof EE_Datetime && ! isset($dtts[ $datetime->ID() ])) {
139
-                        $this->_events[ $id ]['dtt_objs'][ $datetime->ID() ] = $datetime;
140
-                        $dtts[ $datetime->ID() ]['datetime']                 = $datetime;
141
-                        $dtts[ $datetime->ID() ]['tkt_objs'][]               = $ticket;
142
-                        $dtts[ $datetime->ID() ]['evt_objs'][]               = $event;
143
-                        $dttcache[ $datetime->ID() ]                         = $datetime;
138
+                    if ($datetime instanceof EE_Datetime && ! isset($dtts[$datetime->ID()])) {
139
+                        $this->_events[$id]['dtt_objs'][$datetime->ID()] = $datetime;
140
+                        $dtts[$datetime->ID()]['datetime']                 = $datetime;
141
+                        $dtts[$datetime->ID()]['tkt_objs'][]               = $ticket;
142
+                        $dtts[$datetime->ID()]['evt_objs'][]               = $event;
143
+                        $dttcache[$datetime->ID()]                         = $datetime;
144 144
                     }
145 145
                 }
146 146
             }
147 147
 
148
-            $this->_events[ $id ]['total_attendees'] = count($attendees);
149
-            $this->_events[ $id ]['att_objs']        = $attendees;
148
+            $this->_events[$id]['total_attendees'] = count($attendees);
149
+            $this->_events[$id]['att_objs']        = $attendees;
150 150
 
151 151
             // let's also setup the dummy attendees property!
152 152
             foreach ($attendees as $att_key => $attendee) {
153
-                if (! $attendee instanceof EE_Attendee) {
153
+                if ( ! $attendee instanceof EE_Attendee) {
154 154
                     continue;
155 155
                 }
156
-                $this->_attendees[ $att_key ]['line_ref'][] =
157
-                    $id;  // so later it can be determined what events this attendee registered for!
158
-                $this->_attendees[ $att_key ]['evt_objs'][] = $event;
159
-                $this->_attendees[ $att_key ]['att_obj']    = $attendee;
156
+                $this->_attendees[$att_key]['line_ref'][] =
157
+                    $id; // so later it can be determined what events this attendee registered for!
158
+                $this->_attendees[$att_key]['evt_objs'][] = $event;
159
+                $this->_attendees[$att_key]['att_obj']    = $attendee;
160 160
                 // $this->_attendees[$att_key]['registration_id'] = 0;
161
-                $this->_attendees[ $att_key ]['attendee_email'] = $attendee->email();
162
-                $this->_attendees[ $att_key ]['tkt_objs']       = $tickets;
161
+                $this->_attendees[$att_key]['attendee_email'] = $attendee->email();
162
+                $this->_attendees[$att_key]['tkt_objs']       = $tickets;
163 163
                 if ($att_key == 999999991) {
164
-                    $this->_attendees[ $att_key ]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
-                    $this->_attendees[ $att_key ]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
-                    $this->_attendees[ $att_key ]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
164
+                    $this->_attendees[$att_key]['ans_objs'][999]  = $answers_n_questions['answers'][999];
165
+                    $this->_attendees[$att_key]['ans_objs'][1002] = $answers_n_questions['answers'][1002];
166
+                    $this->_attendees[$att_key]['ans_objs'][1005] = $answers_n_questions['answers'][1005];
167 167
                 } elseif ($att_key == 999999992) {
168
-                    $this->_attendees[ $att_key ]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
-                    $this->_attendees[ $att_key ]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
-                    $this->_attendees[ $att_key ]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
168
+                    $this->_attendees[$att_key]['ans_objs'][1000] = $answers_n_questions['answers'][1000];
169
+                    $this->_attendees[$att_key]['ans_objs'][1003] = $answers_n_questions['answers'][1003];
170
+                    $this->_attendees[$att_key]['ans_objs'][1006] = $answers_n_questions['answers'][1006];
171 171
                 } elseif ($att_key == 999999993) {
172
-                    $this->_attendees[ $att_key ]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
-                    $this->_attendees[ $att_key ]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
-                    $this->_attendees[ $att_key ]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
172
+                    $this->_attendees[$att_key]['ans_objs'][1001] = $answers_n_questions['answers'][1001];
173
+                    $this->_attendees[$att_key]['ans_objs'][1004] = $answers_n_questions['answers'][1004];
174
+                    $this->_attendees[$att_key]['ans_objs'][1007] = $answers_n_questions['answers'][1007];
175 175
                 }
176 176
             }
177 177
         }
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
             /** @var $email string */
273 273
             /** @var $phone string */
274 274
             /** @var $attid string */
275
-            $attendees[ $attid ] = EE_Attendee::new_instance(
275
+            $attendees[$attid] = EE_Attendee::new_instance(
276 276
                 [
277 277
                     'ATT_fname'    => $fname,
278 278
                     'ATT_lname'    => $lname,
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
         // first the questions
380 380
         foreach ($quests_array as $qst) {
381 381
             $qstobj                    = array_combine($qst_columns, $qst);
382
-            $qsts[ $qstobj['QST_ID'] ] = EE_Question::new_instance($qstobj);
382
+            $qsts[$qstobj['QST_ID']] = EE_Question::new_instance($qstobj);
383 383
         }
384 384
 
385 385
         // now the answers (and we'll setup our arrays)
@@ -387,8 +387,8 @@  discard block
 block discarded – undo
387 387
         foreach ($ans_array as $ans) {
388 388
             $ansobj                               = array_combine($ans_columns, $ans);
389 389
             $ansobj                               = EE_Answer::new_instance($ansobj);
390
-            $q_n_as['answers'][ $ansobj->ID() ]   = $ansobj;
391
-            $q_n_as['questions'][ $ansobj->ID() ] = $qsts[ $ansobj->get('QST_ID') ];
390
+            $q_n_as['answers'][$ansobj->ID()]   = $ansobj;
391
+            $q_n_as['questions'][$ansobj->ID()] = $qsts[$ansobj->get('QST_ID')];
392 392
         }
393 393
 
394 394
         return $q_n_as;
@@ -471,11 +471,11 @@  discard block
 block discarded – undo
471 471
             $regtxn = $this->txn->ID();
472 472
             $regcnt = 1;
473 473
             foreach ($attendee['line_ref'] as $evtid) {
474
-                foreach ($this->_events[ $evtid ]['tkt_objs'] as $ticket) {
475
-                    if (! $ticket instanceof EE_Ticket) {
474
+                foreach ($this->_events[$evtid]['tkt_objs'] as $ticket) {
475
+                    if ( ! $ticket instanceof EE_Ticket) {
476 476
                         continue;
477 477
                     }
478
-                    $reg_array                                            = [
478
+                    $reg_array = [
479 479
                         'EVT_ID'           => $evtid,
480 480
                         'ATT_ID'           => $regatt,
481 481
                         'TXN_ID'           => $regtxn,
@@ -484,18 +484,18 @@  discard block
 block discarded – undo
484 484
                         'REG_date'         => time(),
485 485
                         'REG_final_price'  => $ticket->get('TKT_price'),
486 486
                         'REG_session'      => 'dummy_session_id',
487
-                        'REG_code'         => $regid . '-dummy-generated-code',
488
-                        'REG_url_link'     => $regcnt . '-daafpapasdlfakasdfpqasdfasdf',
487
+                        'REG_code'         => $regid.'-dummy-generated-code',
488
+                        'REG_url_link'     => $regcnt.'-daafpapasdlfakasdfpqasdfasdf',
489 489
                         'REG_count'        => $regcnt,
490
-                        'REG_group_size'   => $this->_events[ $evtid ]['total_attendees'],
490
+                        'REG_group_size'   => $this->_events[$evtid]['total_attendees'],
491 491
                         'REG_att_is_going' => true,
492 492
                         'REG_ID'           => $regid,
493 493
                     ];
494 494
                     $REG_OBJ                                              = EE_Registration::new_instance($reg_array);
495
-                    $this->_attendees[ $key ]['reg_objs'][ $regid ]       = $REG_OBJ;
496
-                    $this->_events[ $evtid ]['reg_objs'][]                = $REG_OBJ;
495
+                    $this->_attendees[$key]['reg_objs'][$regid]       = $REG_OBJ;
496
+                    $this->_events[$evtid]['reg_objs'][]                = $REG_OBJ;
497 497
                     $this->reg_objs[]                                     = $REG_OBJ;
498
-                    $this->tickets[ $ticket->ID() ]['reg_objs'][ $regid ] = $REG_OBJ;
498
+                    $this->tickets[$ticket->ID()]['reg_objs'][$regid] = $REG_OBJ;
499 499
 
500 500
                     $regcnt++;
501 501
                     $regid++;
@@ -537,19 +537,19 @@  discard block
 block discarded – undo
537 537
         $event_line_items = EEH_Line_Item::get_pre_tax_subtotal($line_item_total)->children();
538 538
         $line_items       = [];
539 539
         foreach ($event_line_items as $line_item) {
540
-            if (! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
540
+            if ( ! $line_item instanceof EE_Line_Item || $line_item->OBJ_type() !== 'Event') {
541 541
                 continue;
542 542
             }
543 543
             $ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
544 544
             foreach ($ticket_line_items as $ticket_line_item) {
545
-                if (! $ticket_line_item instanceof EE_Line_Item) {
545
+                if ( ! $ticket_line_item instanceof EE_Line_Item) {
546 546
                     continue;
547 547
                 }
548
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['line_item']      = $ticket_line_item;
549
-                $this->tickets[ $ticket_line_item->OBJ_ID() ]['sub_line_items'] = $ticket_line_item->children();
550
-                $line_items[ $ticket_line_item->ID() ]['children']              = $ticket_line_item->children();
551
-                $line_items[ $ticket_line_item->ID() ]['EE_Ticket']             =
552
-                    $this->tickets[ $ticket_line_item->OBJ_ID() ]['ticket'];
548
+                $this->tickets[$ticket_line_item->OBJ_ID()]['line_item']      = $ticket_line_item;
549
+                $this->tickets[$ticket_line_item->OBJ_ID()]['sub_line_items'] = $ticket_line_item->children();
550
+                $line_items[$ticket_line_item->ID()]['children']              = $ticket_line_item->children();
551
+                $line_items[$ticket_line_item->ID()]['EE_Ticket']             =
552
+                    $this->tickets[$ticket_line_item->OBJ_ID()]['ticket'];
553 553
             }
554 554
         }
555 555
 
@@ -564,15 +564,15 @@  discard block
 block discarded – undo
564 564
 
565 565
         // add additional details for each registration
566 566
         foreach ($this->reg_objs as $reg) {
567
-            if (! $reg instanceof EE_Registration) {
567
+            if ( ! $reg instanceof EE_Registration) {
568 568
                 continue;
569 569
             }
570
-            $this->_registrations[ $reg->ID() ]['tkt_obj']  = $this->tickets[ $reg->get('TKT_ID') ]['ticket'];
571
-            $this->_registrations[ $reg->ID() ]['evt_obj']  = $this->_events[ $reg->get('EVT_ID') ]['event'];
572
-            $this->_registrations[ $reg->ID() ]['reg_obj']  = $reg;
573
-            $this->_registrations[ $reg->ID() ]['ans_objs'] = $this->_attendees[ $reg->get('ATT_ID') ]['ans_objs'];
574
-            $this->_registrations[ $reg->ID() ]['att_obj']  = $this->_attendees[ $reg->get('ATT_ID') ]['att_obj'];
575
-            $this->_registrations[ $reg->ID() ]['dtt_objs'] = $this->tickets[ $reg->get('TKT_ID') ]['dtt_objs'];
570
+            $this->_registrations[$reg->ID()]['tkt_obj']  = $this->tickets[$reg->get('TKT_ID')]['ticket'];
571
+            $this->_registrations[$reg->ID()]['evt_obj']  = $this->_events[$reg->get('EVT_ID')]['event'];
572
+            $this->_registrations[$reg->ID()]['reg_obj']  = $reg;
573
+            $this->_registrations[$reg->ID()]['ans_objs'] = $this->_attendees[$reg->get('ATT_ID')]['ans_objs'];
574
+            $this->_registrations[$reg->ID()]['att_obj']  = $this->_attendees[$reg->get('ATT_ID')]['att_obj'];
575
+            $this->_registrations[$reg->ID()]['dtt_objs'] = $this->tickets[$reg->get('TKT_ID')]['dtt_objs'];
576 576
         }
577 577
 
578 578
 
Please login to merge, or discard this patch.
core/libraries/messages/data_class/EE_Messages_REG_incoming_data.class.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -18,137 +18,137 @@
 block discarded – undo
18 18
 
19 19
 
20 20
 
21
-    /**
22
-     * For the constructor of this special preview class.
23
-     *
24
-     * The data is expected to be an array that came from the request data
25
-     * and should have at least one property from the list looked for.
26
-     *
27
-     * @param EE_Registration|array $data
28
-     * @throws \EE_Error
29
-     */
30
-    public function __construct($data)
31
-    {
32
-        $filtered_reg_status = null;
33
-
34
-        if (! is_array($data) && $data instanceof EE_Registration) {
35
-            $this->reg_obj = $data;
36
-        } else {
37
-            $this->reg_obj = is_array($data) && isset($data[0]) && $data[0] instanceof EE_Registration ? $data[0] : null;
38
-            $filtered_reg_status = is_array($data) && ! empty($data[1]) ? $data[1] : null;
39
-        }
40
-
41
-        if (! $this->reg_obj instanceof EE_Registration) {
42
-            throw new EE_Error(
43
-                sprintf(
44
-                    __('%1$s requires the incoming data argument to be an instance of %2$s or an array where the first value is an instance of %2$s', 'event_espresso'),
45
-                    'EE_Messages_REG_incoming_data',
46
-                    'EE_Registration'
47
-                )
48
-            );
49
-        }
50
-
51
-        $data = array(
52
-            'reg_obj' => $this->reg_obj,
53
-            'filtered_reg_status' => $filtered_reg_status
54
-            );
55
-
56
-        parent::__construct($data);
57
-    }
58
-
59
-    /**
60
-     * Returns database safe representation of the data later used to when instantiating this object.
61
-     *
62
-     * @param mixed $data The incoming data to be prepped.
63
-     *
64
-     * @return array   The prepped data for db
65
-     */
66
-    public static function convert_data_for_persistent_storage($data)
67
-    {
68
-        $prepped_data = array();
69
-        if (! is_array($data) && $data instanceof EE_Registration) {
70
-            $prepped_data['Registration'] = $data->ID();
71
-            return $prepped_data;
72
-        } elseif (! is_array($data)) {
73
-            return array();
74
-        } else {
75
-            if ($data[0] instanceof EE_Registration) {
76
-                $prepped_data['Registration'] = $data[0];
77
-            }
78
-            if (! empty($data[1])) {
79
-                $prepped_data['filter'] = $data[1];
80
-            }
81
-        }
82
-
83
-        return $prepped_data;
84
-    }
85
-
86
-    /**
87
-     * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
88
-     * can be sent into this method and converted back into the format used for instantiating with this data handler.
89
-     *
90
-     * @param $data
91
-     *
92
-     * @return mixed
93
-     */
94
-    public static function convert_data_from_persistent_storage($data)
95
-    {
96
-        $registration = null;
97
-        // $data['Registration'] could be either an ID (back compat) or a registration object (prepped using old system).
98
-        if (isset($data['Registration'])) {
99
-            $registration = $data['Registration'] instanceof EE_Registration
100
-                ? $data['Registration']
101
-                : EEM_Registration::instance()->get_one_by_ID($data['Registration']);
102
-        }
103
-        $prepped_data = array(
104
-            0 => $registration,
105
-            1 => isset($data['filter']) ? $data['filter'] : null
106
-        );
107
-        return $prepped_data;
108
-    }
109
-
110
-
111
-    /**
112
-     * This will just setup the _events property in the expected format.
113
-     * @return void
114
-     */
115
-    protected function _setup_data()
116
-    {
117
-
118
-        // now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
119
-        $this->filtered_reg_status = $this->_data['filtered_reg_status'];
120
-        // get txn
121
-        $this->txn = $this->reg_obj->transaction();
122
-        // possible session stuff?
123
-        $session = $this->txn->session_data();
124
-        $session_data =  $session instanceof EE_Session ? $session->get_session_data() : array();
125
-
126
-        // other data from the session (if possible)
127
-        $this->user_id = isset($session_data['user_id']) ? $session_data['user_id'] : '';
128
-        $this->ip_address = isset($session_data['ip_address']) ? $session_data['ip_address'] : '';
129
-        $this->user_agent = isset($session_data['user_agent']) ? $session_data['user_agent'] : '';
130
-        $this->init_access = $this->last_access = '';
131
-
132
-        $this->payment = $this->txn->get_first_related('Payment');
133
-        // if there is no payments associated with the transaction
134
-        // then we just create a default payment object for potential parsing.
135
-        $this->payment = empty($this->payment)
136
-            ? EE_Payment::new_instance(
137
-                array(
138
-                    'STS_ID'               => EEM_Payment::status_id_pending,
139
-                    'PAY_timestamp'        => time(),
140
-                    'PMD_ID'               => $this->txn->payment_method_ID(),
141
-                    'PAY_gateway_response' => $this->txn->gateway_response_on_transaction(),
142
-                )
143
-            )
144
-            : $this->payment;
145
-
146
-
147
-        // get reg_objs for txn
148
-        $this->reg_objs = $this->txn->registrations();
149
-
150
-        // now we can set things up like we do for other handlers
151
-
152
-        $this->_assemble_data();
153
-    }
21
+	/**
22
+	 * For the constructor of this special preview class.
23
+	 *
24
+	 * The data is expected to be an array that came from the request data
25
+	 * and should have at least one property from the list looked for.
26
+	 *
27
+	 * @param EE_Registration|array $data
28
+	 * @throws \EE_Error
29
+	 */
30
+	public function __construct($data)
31
+	{
32
+		$filtered_reg_status = null;
33
+
34
+		if (! is_array($data) && $data instanceof EE_Registration) {
35
+			$this->reg_obj = $data;
36
+		} else {
37
+			$this->reg_obj = is_array($data) && isset($data[0]) && $data[0] instanceof EE_Registration ? $data[0] : null;
38
+			$filtered_reg_status = is_array($data) && ! empty($data[1]) ? $data[1] : null;
39
+		}
40
+
41
+		if (! $this->reg_obj instanceof EE_Registration) {
42
+			throw new EE_Error(
43
+				sprintf(
44
+					__('%1$s requires the incoming data argument to be an instance of %2$s or an array where the first value is an instance of %2$s', 'event_espresso'),
45
+					'EE_Messages_REG_incoming_data',
46
+					'EE_Registration'
47
+				)
48
+			);
49
+		}
50
+
51
+		$data = array(
52
+			'reg_obj' => $this->reg_obj,
53
+			'filtered_reg_status' => $filtered_reg_status
54
+			);
55
+
56
+		parent::__construct($data);
57
+	}
58
+
59
+	/**
60
+	 * Returns database safe representation of the data later used to when instantiating this object.
61
+	 *
62
+	 * @param mixed $data The incoming data to be prepped.
63
+	 *
64
+	 * @return array   The prepped data for db
65
+	 */
66
+	public static function convert_data_for_persistent_storage($data)
67
+	{
68
+		$prepped_data = array();
69
+		if (! is_array($data) && $data instanceof EE_Registration) {
70
+			$prepped_data['Registration'] = $data->ID();
71
+			return $prepped_data;
72
+		} elseif (! is_array($data)) {
73
+			return array();
74
+		} else {
75
+			if ($data[0] instanceof EE_Registration) {
76
+				$prepped_data['Registration'] = $data[0];
77
+			}
78
+			if (! empty($data[1])) {
79
+				$prepped_data['filter'] = $data[1];
80
+			}
81
+		}
82
+
83
+		return $prepped_data;
84
+	}
85
+
86
+	/**
87
+	 * Data that has been stored in persistent storage that was prepped by _convert_data_for_persistent_storage
88
+	 * can be sent into this method and converted back into the format used for instantiating with this data handler.
89
+	 *
90
+	 * @param $data
91
+	 *
92
+	 * @return mixed
93
+	 */
94
+	public static function convert_data_from_persistent_storage($data)
95
+	{
96
+		$registration = null;
97
+		// $data['Registration'] could be either an ID (back compat) or a registration object (prepped using old system).
98
+		if (isset($data['Registration'])) {
99
+			$registration = $data['Registration'] instanceof EE_Registration
100
+				? $data['Registration']
101
+				: EEM_Registration::instance()->get_one_by_ID($data['Registration']);
102
+		}
103
+		$prepped_data = array(
104
+			0 => $registration,
105
+			1 => isset($data['filter']) ? $data['filter'] : null
106
+		);
107
+		return $prepped_data;
108
+	}
109
+
110
+
111
+	/**
112
+	 * This will just setup the _events property in the expected format.
113
+	 * @return void
114
+	 */
115
+	protected function _setup_data()
116
+	{
117
+
118
+		// now let's loop and set up the _events property.  At the same time we'll set up attendee properties.
119
+		$this->filtered_reg_status = $this->_data['filtered_reg_status'];
120
+		// get txn
121
+		$this->txn = $this->reg_obj->transaction();
122
+		// possible session stuff?
123
+		$session = $this->txn->session_data();
124
+		$session_data =  $session instanceof EE_Session ? $session->get_session_data() : array();
125
+
126
+		// other data from the session (if possible)
127
+		$this->user_id = isset($session_data['user_id']) ? $session_data['user_id'] : '';
128
+		$this->ip_address = isset($session_data['ip_address']) ? $session_data['ip_address'] : '';
129
+		$this->user_agent = isset($session_data['user_agent']) ? $session_data['user_agent'] : '';
130
+		$this->init_access = $this->last_access = '';
131
+
132
+		$this->payment = $this->txn->get_first_related('Payment');
133
+		// if there is no payments associated with the transaction
134
+		// then we just create a default payment object for potential parsing.
135
+		$this->payment = empty($this->payment)
136
+			? EE_Payment::new_instance(
137
+				array(
138
+					'STS_ID'               => EEM_Payment::status_id_pending,
139
+					'PAY_timestamp'        => time(),
140
+					'PMD_ID'               => $this->txn->payment_method_ID(),
141
+					'PAY_gateway_response' => $this->txn->gateway_response_on_transaction(),
142
+				)
143
+			)
144
+			: $this->payment;
145
+
146
+
147
+		// get reg_objs for txn
148
+		$this->reg_objs = $this->txn->registrations();
149
+
150
+		// now we can set things up like we do for other handlers
151
+
152
+		$this->_assemble_data();
153
+	}
154 154
 }
Please login to merge, or discard this patch.
core/libraries/payment_methods/EE_Offsite_Gateway.lib.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -15,117 +15,117 @@
 block discarded – undo
15 15
 abstract class EE_Offsite_Gateway extends EE_Gateway
16 16
 {
17 17
 
18
-    /**
19
-     * whether or not the gateway uses an IPN
20
-     * that is sent in a separate request than the returning registrant.
21
-     * if false, then we need to process the payment results manually
22
-     * as soon as the registrant returns from the off-site gateway
23
-     *
24
-     * @type bool
25
-     */
26
-    protected $_uses_separate_IPN_request = false;
18
+	/**
19
+	 * whether or not the gateway uses an IPN
20
+	 * that is sent in a separate request than the returning registrant.
21
+	 * if false, then we need to process the payment results manually
22
+	 * as soon as the registrant returns from the off-site gateway
23
+	 *
24
+	 * @type bool
25
+	 */
26
+	protected $_uses_separate_IPN_request = false;
27 27
 
28 28
 
29
-    /**
30
-     * @return EE_Offsite_Gateway
31
-     */
32
-    public function __construct()
33
-    {
34
-        $this->_supports_receiving_refunds = true;
35
-        parent::__construct();
36
-    }
29
+	/**
30
+	 * @return EE_Offsite_Gateway
31
+	 */
32
+	public function __construct()
33
+	{
34
+		$this->_supports_receiving_refunds = true;
35
+		parent::__construct();
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Adds information into the payment object's redirect_url and redirect_args so
41
-     * client code can use that payment to know where (and with what information)
42
-     * to redirect the user to in order to make the payment on the offsite gateway's website.
43
-     * Saving the payment from within this method is unnecessary,
44
-     * as it is the responsibility of client code to save it.
45
-     *
46
-     * @param EE_Payment $payment    to process
47
-     * @param array      $billing_info
48
-     * @param string     $return_url URL to send the user to after a successful payment on the payment provider's
49
-     *                               website
50
-     * @param string     $notify_url URL to send the instant payment notification
51
-     * @param string     $cancel_url URL to send the user to after a cancelled payment attempt on teh payment
52
-     *                               provider's website
53
-     * @return EE_Payment
54
-     */
55
-    abstract public function set_redirection_info(
56
-        $payment,
57
-        $billing_info = array(),
58
-        $return_url = null,
59
-        $notify_url = null,
60
-        $cancel_url = null
61
-    );
39
+	/**
40
+	 * Adds information into the payment object's redirect_url and redirect_args so
41
+	 * client code can use that payment to know where (and with what information)
42
+	 * to redirect the user to in order to make the payment on the offsite gateway's website.
43
+	 * Saving the payment from within this method is unnecessary,
44
+	 * as it is the responsibility of client code to save it.
45
+	 *
46
+	 * @param EE_Payment $payment    to process
47
+	 * @param array      $billing_info
48
+	 * @param string     $return_url URL to send the user to after a successful payment on the payment provider's
49
+	 *                               website
50
+	 * @param string     $notify_url URL to send the instant payment notification
51
+	 * @param string     $cancel_url URL to send the user to after a cancelled payment attempt on teh payment
52
+	 *                               provider's website
53
+	 * @return EE_Payment
54
+	 */
55
+	abstract public function set_redirection_info(
56
+		$payment,
57
+		$billing_info = array(),
58
+		$return_url = null,
59
+		$notify_url = null,
60
+		$cancel_url = null
61
+	);
62 62
 
63 63
 
64
-    /**
65
-     * Often used for IPNs. But applies the info in $update_info to the payment.
66
-     * What is $update_info? Often the contents of request, but not necessarily. Whatever
67
-     * the payment method passes in. Saving the payment from within this method is unnecessary,
68
-     * as it is the responsibility of client code to save it.
69
-     *
70
-     * @param array           $update_info of whatever
71
-     * @param EEI_Transaction $transaction
72
-     * @return EEI_Payment updated
73
-     */
74
-    abstract public function handle_payment_update($update_info, $transaction);
64
+	/**
65
+	 * Often used for IPNs. But applies the info in $update_info to the payment.
66
+	 * What is $update_info? Often the contents of request, but not necessarily. Whatever
67
+	 * the payment method passes in. Saving the payment from within this method is unnecessary,
68
+	 * as it is the responsibility of client code to save it.
69
+	 *
70
+	 * @param array           $update_info of whatever
71
+	 * @param EEI_Transaction $transaction
72
+	 * @return EEI_Payment updated
73
+	 */
74
+	abstract public function handle_payment_update($update_info, $transaction);
75 75
 
76 76
 
77
-    /**
78
-     * uses_separate_IPN_request
79
-     *
80
-     * return true or false for whether or not the gateway uses an IPN
81
-     * that is sent in a separate request than the returning registrant.
82
-     * if false, then we need to process the payment results manually
83
-     * as soon as the registrant returns from the off-site gateway
84
-     *
85
-     * @deprecated since version 4.8.39.rc.001 please use handle_IPN_in_this_request() instead
86
-     *
87
-     * @return bool
88
-     */
89
-    public function uses_separate_IPN_request()
90
-    {
91
-        return $this->_uses_separate_IPN_request;
92
-    }
77
+	/**
78
+	 * uses_separate_IPN_request
79
+	 *
80
+	 * return true or false for whether or not the gateway uses an IPN
81
+	 * that is sent in a separate request than the returning registrant.
82
+	 * if false, then we need to process the payment results manually
83
+	 * as soon as the registrant returns from the off-site gateway
84
+	 *
85
+	 * @deprecated since version 4.8.39.rc.001 please use handle_IPN_in_this_request() instead
86
+	 *
87
+	 * @return bool
88
+	 */
89
+	public function uses_separate_IPN_request()
90
+	{
91
+		return $this->_uses_separate_IPN_request;
92
+	}
93 93
 
94 94
 
95
-    /**
96
-     * set_uses_separate_IPN_request
97
-     *
98
-     * @access protected
99
-     * @param boolean $uses_separate_IPN_request
100
-     */
101
-    protected function set_uses_separate_IPN_request($uses_separate_IPN_request)
102
-    {
103
-        $this->_uses_separate_IPN_request = filter_var($uses_separate_IPN_request, FILTER_VALIDATE_BOOLEAN);
104
-    }
95
+	/**
96
+	 * set_uses_separate_IPN_request
97
+	 *
98
+	 * @access protected
99
+	 * @param boolean $uses_separate_IPN_request
100
+	 */
101
+	protected function set_uses_separate_IPN_request($uses_separate_IPN_request)
102
+	{
103
+		$this->_uses_separate_IPN_request = filter_var($uses_separate_IPN_request, FILTER_VALIDATE_BOOLEAN);
104
+	}
105 105
 
106
-    /**
107
-     * Allows gateway to dynamically decide whether or not to handle a payment update
108
-     * by overriding this method. By default, if this is a "true" IPN (meaning
109
-     * it's a separate request from when the user returns from the offsite gateway)
110
-     * and this gateway class is setup to handle IPNs in separate "true" IPNs, then
111
-     * this will return true, otherwise it will return false.
112
-     * If however, this is a request when the user is returning
113
-     * from an offsite gateway, and this gateway class is setup to process the payment
114
-     * data when the user returns, then this will return true.
115
-     *
116
-     * @param array   $request_data
117
-     * @param boolean $separate_IPN_request
118
-     * @return boolean
119
-     */
120
-    public function handle_IPN_in_this_request($request_data, $separate_IPN_request)
121
-    {
122
-        if ($separate_IPN_request) {
123
-            // payment data being sent in a request separate from the user
124
-            // it is this other request that will update the TXN and payment info
125
-            return $this->_uses_separate_IPN_request;
126
-        } else {
127
-            // it's a request where the user returned from an offsite gateway WITH the payment data
128
-            return ! $this->_uses_separate_IPN_request;
129
-        }
130
-    }
106
+	/**
107
+	 * Allows gateway to dynamically decide whether or not to handle a payment update
108
+	 * by overriding this method. By default, if this is a "true" IPN (meaning
109
+	 * it's a separate request from when the user returns from the offsite gateway)
110
+	 * and this gateway class is setup to handle IPNs in separate "true" IPNs, then
111
+	 * this will return true, otherwise it will return false.
112
+	 * If however, this is a request when the user is returning
113
+	 * from an offsite gateway, and this gateway class is setup to process the payment
114
+	 * data when the user returns, then this will return true.
115
+	 *
116
+	 * @param array   $request_data
117
+	 * @param boolean $separate_IPN_request
118
+	 * @return boolean
119
+	 */
120
+	public function handle_IPN_in_this_request($request_data, $separate_IPN_request)
121
+	{
122
+		if ($separate_IPN_request) {
123
+			// payment data being sent in a request separate from the user
124
+			// it is this other request that will update the TXN and payment info
125
+			return $this->_uses_separate_IPN_request;
126
+		} else {
127
+			// it's a request where the user returned from an offsite gateway WITH the payment data
128
+			return ! $this->_uses_separate_IPN_request;
129
+		}
130
+	}
131 131
 }
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/JobParameters.php 1 patch
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -14,396 +14,396 @@
 block discarded – undo
14 14
  */
15 15
 class JobParameters
16 16
 {
17
-    // phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
18
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
19
-    // phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
20
-    /**
21
-     * status indicating the job should continue
22
-     */
23
-    const status_continue = 'continue';
24
-
25
-    /**
26
-     * status indicated the job has been completed successfully and should be cleaned up next
27
-     */
28
-    const status_complete = 'complete';
29
-
30
-    /**
31
-     * status indicating there was an error and the job should be cleaned up
32
-     */
33
-    const status_error = 'error';
34
-
35
-    /**
36
-     * status indicating the job has been cleaned up, and so this is probably the last
37
-     * time you'll see this job
38
-     */
39
-    const status_cleaned_up = 'cleaned_up';
40
-
41
-    const wp_option_prefix = 'ee_job_parameters_';
42
-
43
-
44
-    /**
45
-     * String uniquely identifying the job
46
-     *
47
-     * @var string
48
-     */
49
-    protected $_job_id;
50
-
51
-    /**
52
-     * @var string
53
-     */
54
-    protected $_classname;
55
-
56
-    /**
57
-     * @var array
58
-     */
59
-    protected $_request_data;
60
-
61
-    /**
62
-     * Array of any extra data we want to remember about this request, that
63
-     * wasn't necessarily past in with the request data
64
-     *
65
-     * @var array
66
-     */
67
-    protected $_extra_data;
68
-
69
-    /**
70
-     * Estimate of how many units HAVE been processed
71
-     *
72
-     * @var int
73
-     */
74
-    protected $_units_processed = 0;
75
-
76
-    /**
77
-     * @var string
78
-     */
79
-    protected $_status;
80
-
81
-    /**
82
-     * The size of the total job in whatever units you want.
83
-     * If you can't provide an estimate leave as 0.
84
-     * Once _units_processed equals _job_size, we should be done
85
-     *
86
-     * @var int
87
-     */
88
-    protected $_job_size = 0;
89
-
90
-
91
-    /**
92
-     * @param string $job_id
93
-     * @param string $classname
94
-     * @param array  $request_data
95
-     * @param array  $extra_data
96
-     */
97
-    public function __construct($job_id, $classname, $request_data, $extra_data = array())
98
-    {
99
-        $this->set_job_id($job_id);
100
-        $this->set_classname($classname);
101
-        $this->set_request_data($request_data);
102
-        $this->set_extra_data($extra_data);
103
-        $this->set_status(JobParameters::status_continue);
104
-    }
105
-
106
-
107
-    /**
108
-     * Returns the array of strings of valid stati
109
-     *
110
-     * @return array
111
-     */
112
-    public static function valid_stati()
113
-    {
114
-        return array(
115
-            JobParameters::status_complete,
116
-            JobParameters::status_continue,
117
-            JobParameters::status_error,
118
-            JobParameters::status_cleaned_up,
119
-        );
120
-    }
121
-
122
-
123
-    /**
124
-     * Saves this option to the database (wordpress options table)
125
-     *
126
-     * @param boolean $first
127
-     * @return boolean success
128
-     */
129
-    public function save($first = false)
130
-    {
131
-        $object_vars = get_object_vars($this);
132
-        if ($first) {
133
-            return add_option($this->option_name(), $object_vars, null, 'no');
134
-        } else {
135
-            return update_option($this->option_name(), $object_vars);
136
-        }
137
-    }
138
-
139
-
140
-    /**
141
-     * Deletes the job from teh database, although this object is still usable
142
-     * for the rest of the request
143
-     *
144
-     * @return boolean
145
-     */
146
-    public function delete()
147
-    {
148
-        return delete_option($this->option_name());
149
-    }
150
-
151
-
152
-    /**
153
-     * Loads the specified job from the database
154
-     *
155
-     * @param string $job_id
156
-     * @return JobParameters
157
-     * @throws BatchRequestException
158
-     */
159
-    public static function load($job_id)
160
-    {
161
-        $job_parameter_vars = get_option(JobParameters::wp_option_prefix . $job_id);
162
-        if (! is_array($job_parameter_vars) ||
163
-            ! isset($job_parameter_vars['_classname']) ||
164
-            ! isset($job_parameter_vars['_request_data'])
165
-        ) {
166
-            throw new BatchRequestException(
167
-                sprintf(
168
-                    __(
169
-                        'Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s',
170
-                        'event_espresso'
171
-                    ),
172
-                    $job_id,
173
-                    get_option(JobParameters::wp_option_prefix . $job_id)
174
-                )
175
-            );
176
-        }
177
-        $job_parameters = new JobParameters(
178
-            $job_id,
179
-            $job_parameter_vars['_classname'],
180
-            $job_parameter_vars['_request_data']
181
-        );
182
-        foreach ($job_parameter_vars as $key => $value) {
183
-            $job_parameters->{$key} = $value;
184
-        }
185
-        return $job_parameters;
186
-    }
187
-
188
-
189
-    /**
190
-     * Gets the job's unique string
191
-     *
192
-     * @return string
193
-     */
194
-    public function job_id()
195
-    {
196
-        return $this->_job_id;
197
-    }
198
-
199
-
200
-    /**
201
-     * Gets the classname that should run this job
202
-     *
203
-     * @return string
204
-     */
205
-    public function classname()
206
-    {
207
-        return $this->_classname;
208
-    }
209
-
210
-
211
-    /**
212
-     * Gets the original array of request data for this job
213
-     *
214
-     * @return array
215
-     */
216
-    public function request_data()
217
-    {
218
-        return $this->_request_data;
219
-    }
220
-
221
-
222
-    /**
223
-     * Gets a single item from the request data
224
-     *
225
-     * @param string       $key
226
-     * @param string|array $default
227
-     * @return string|array
228
-     */
229
-    public function request_datum($key, $default = '')
230
-    {
231
-        if (isset($this->_request_data[ $key ])) {
232
-            return $this->_request_data[ $key ];
233
-        } else {
234
-            return $default;
235
-        }
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets a single item from the extra data
241
-     *
242
-     * @param string       $key
243
-     * @param string|array $default
244
-     * @return string|array
245
-     */
246
-    public function extra_datum($key, $default = '')
247
-    {
248
-        if (isset($this->_extra_data[ $key ])) {
249
-            return $this->_extra_data[ $key ];
250
-        } else {
251
-            return $default;
252
-        }
253
-    }
254
-
255
-
256
-    /**
257
-     * Adds an extra piece of extra data that we're going to want later during the job
258
-     *
259
-     * @param string                $key
260
-     * @param string|int|array|null $value almost any extra data you want to store
261
-     */
262
-    public function add_extra_data($key, $value)
263
-    {
264
-        $this->_extra_data[ $key ] = $value;
265
-    }
266
-
267
-
268
-    /**
269
-     * Array of any extra data we want to store
270
-     *
271
-     * @return array
272
-     */
273
-    public function extra_data()
274
-    {
275
-        return $this->_extra_data;
276
-    }
277
-
278
-
279
-    /**
280
-     * Returns the job size, in whatever units you want
281
-     *
282
-     * @return int
283
-     */
284
-    public function job_size()
285
-    {
286
-        return $this->_job_size;
287
-    }
288
-
289
-
290
-    /**
291
-     * Sets the job size. You decide what units to use
292
-     *
293
-     * @param int $size
294
-     */
295
-    public function set_job_size($size)
296
-    {
297
-        $this->_job_size = $size;
298
-    }
299
-
300
-
301
-    /**
302
-     * The number of "units" processed, in the same units as the "job size"
303
-     *
304
-     * @return int
305
-     */
306
-    public function units_processed()
307
-    {
308
-        return $this->_units_processed;
309
-    }
310
-
311
-
312
-    /**
313
-     * Marks more units as processed
314
-     *
315
-     * @param int $newly_processed
316
-     * @return int updated units processed
317
-     */
318
-    public function mark_processed($newly_processed)
319
-    {
320
-        $this->_units_processed += $newly_processed;
321
-        return $this->_units_processed;
322
-    }
323
-
324
-
325
-    /**
326
-     * Sets the total count of units processed. You might prefer to use mark_processed
327
-     *
328
-     * @param int $total_units_processed
329
-     */
330
-    public function set_units_processed($total_units_processed)
331
-    {
332
-        $this->_units_processed = $total_units_processed;
333
-    }
334
-
335
-
336
-    /**
337
-     * Sets the job's ID
338
-     *
339
-     * @param string $job_id
340
-     */
341
-    public function set_job_id($job_id)
342
-    {
343
-        $this->_job_id = $job_id;
344
-    }
345
-
346
-
347
-    /**
348
-     * sets the classname
349
-     *
350
-     * @param string $classname
351
-     */
352
-    public function set_classname($classname)
353
-    {
354
-        $this->_classname = $classname;
355
-    }
356
-
357
-
358
-    /**
359
-     * Sets the request data
360
-     *
361
-     * @param array $request_data
362
-     */
363
-    public function set_request_data($request_data)
364
-    {
365
-        $this->_request_data = $request_data;
366
-    }
367
-
368
-
369
-    /**
370
-     * Sets the array of extra data we want to store on this request
371
-     *
372
-     * @param array $extra_data
373
-     */
374
-    public function set_extra_data($extra_data)
375
-    {
376
-        $this->_extra_data = $extra_data;
377
-    }
378
-
379
-
380
-    /**
381
-     * Gets the name of the wordpress option that should store these job parameters
382
-     *
383
-     * @return string
384
-     */
385
-    public function option_name()
386
-    {
387
-        return JobParameters::wp_option_prefix . $this->job_id();
388
-    }
389
-
390
-
391
-    /**
392
-     * Gets the job\s current status. One of JobParameters::valid_stati();
393
-     *
394
-     * @return string
395
-     */
396
-    public function status()
397
-    {
398
-        return $this->_status;
399
-    }
400
-
401
-
402
-    /**
403
-     * @param string $status on eof JobParameters::valid_stati()
404
-     */
405
-    public function set_status($status)
406
-    {
407
-        $this->_status = $status;
408
-    }
17
+	// phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
18
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
19
+	// phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
20
+	/**
21
+	 * status indicating the job should continue
22
+	 */
23
+	const status_continue = 'continue';
24
+
25
+	/**
26
+	 * status indicated the job has been completed successfully and should be cleaned up next
27
+	 */
28
+	const status_complete = 'complete';
29
+
30
+	/**
31
+	 * status indicating there was an error and the job should be cleaned up
32
+	 */
33
+	const status_error = 'error';
34
+
35
+	/**
36
+	 * status indicating the job has been cleaned up, and so this is probably the last
37
+	 * time you'll see this job
38
+	 */
39
+	const status_cleaned_up = 'cleaned_up';
40
+
41
+	const wp_option_prefix = 'ee_job_parameters_';
42
+
43
+
44
+	/**
45
+	 * String uniquely identifying the job
46
+	 *
47
+	 * @var string
48
+	 */
49
+	protected $_job_id;
50
+
51
+	/**
52
+	 * @var string
53
+	 */
54
+	protected $_classname;
55
+
56
+	/**
57
+	 * @var array
58
+	 */
59
+	protected $_request_data;
60
+
61
+	/**
62
+	 * Array of any extra data we want to remember about this request, that
63
+	 * wasn't necessarily past in with the request data
64
+	 *
65
+	 * @var array
66
+	 */
67
+	protected $_extra_data;
68
+
69
+	/**
70
+	 * Estimate of how many units HAVE been processed
71
+	 *
72
+	 * @var int
73
+	 */
74
+	protected $_units_processed = 0;
75
+
76
+	/**
77
+	 * @var string
78
+	 */
79
+	protected $_status;
80
+
81
+	/**
82
+	 * The size of the total job in whatever units you want.
83
+	 * If you can't provide an estimate leave as 0.
84
+	 * Once _units_processed equals _job_size, we should be done
85
+	 *
86
+	 * @var int
87
+	 */
88
+	protected $_job_size = 0;
89
+
90
+
91
+	/**
92
+	 * @param string $job_id
93
+	 * @param string $classname
94
+	 * @param array  $request_data
95
+	 * @param array  $extra_data
96
+	 */
97
+	public function __construct($job_id, $classname, $request_data, $extra_data = array())
98
+	{
99
+		$this->set_job_id($job_id);
100
+		$this->set_classname($classname);
101
+		$this->set_request_data($request_data);
102
+		$this->set_extra_data($extra_data);
103
+		$this->set_status(JobParameters::status_continue);
104
+	}
105
+
106
+
107
+	/**
108
+	 * Returns the array of strings of valid stati
109
+	 *
110
+	 * @return array
111
+	 */
112
+	public static function valid_stati()
113
+	{
114
+		return array(
115
+			JobParameters::status_complete,
116
+			JobParameters::status_continue,
117
+			JobParameters::status_error,
118
+			JobParameters::status_cleaned_up,
119
+		);
120
+	}
121
+
122
+
123
+	/**
124
+	 * Saves this option to the database (wordpress options table)
125
+	 *
126
+	 * @param boolean $first
127
+	 * @return boolean success
128
+	 */
129
+	public function save($first = false)
130
+	{
131
+		$object_vars = get_object_vars($this);
132
+		if ($first) {
133
+			return add_option($this->option_name(), $object_vars, null, 'no');
134
+		} else {
135
+			return update_option($this->option_name(), $object_vars);
136
+		}
137
+	}
138
+
139
+
140
+	/**
141
+	 * Deletes the job from teh database, although this object is still usable
142
+	 * for the rest of the request
143
+	 *
144
+	 * @return boolean
145
+	 */
146
+	public function delete()
147
+	{
148
+		return delete_option($this->option_name());
149
+	}
150
+
151
+
152
+	/**
153
+	 * Loads the specified job from the database
154
+	 *
155
+	 * @param string $job_id
156
+	 * @return JobParameters
157
+	 * @throws BatchRequestException
158
+	 */
159
+	public static function load($job_id)
160
+	{
161
+		$job_parameter_vars = get_option(JobParameters::wp_option_prefix . $job_id);
162
+		if (! is_array($job_parameter_vars) ||
163
+			! isset($job_parameter_vars['_classname']) ||
164
+			! isset($job_parameter_vars['_request_data'])
165
+		) {
166
+			throw new BatchRequestException(
167
+				sprintf(
168
+					__(
169
+						'Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s',
170
+						'event_espresso'
171
+					),
172
+					$job_id,
173
+					get_option(JobParameters::wp_option_prefix . $job_id)
174
+				)
175
+			);
176
+		}
177
+		$job_parameters = new JobParameters(
178
+			$job_id,
179
+			$job_parameter_vars['_classname'],
180
+			$job_parameter_vars['_request_data']
181
+		);
182
+		foreach ($job_parameter_vars as $key => $value) {
183
+			$job_parameters->{$key} = $value;
184
+		}
185
+		return $job_parameters;
186
+	}
187
+
188
+
189
+	/**
190
+	 * Gets the job's unique string
191
+	 *
192
+	 * @return string
193
+	 */
194
+	public function job_id()
195
+	{
196
+		return $this->_job_id;
197
+	}
198
+
199
+
200
+	/**
201
+	 * Gets the classname that should run this job
202
+	 *
203
+	 * @return string
204
+	 */
205
+	public function classname()
206
+	{
207
+		return $this->_classname;
208
+	}
209
+
210
+
211
+	/**
212
+	 * Gets the original array of request data for this job
213
+	 *
214
+	 * @return array
215
+	 */
216
+	public function request_data()
217
+	{
218
+		return $this->_request_data;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Gets a single item from the request data
224
+	 *
225
+	 * @param string       $key
226
+	 * @param string|array $default
227
+	 * @return string|array
228
+	 */
229
+	public function request_datum($key, $default = '')
230
+	{
231
+		if (isset($this->_request_data[ $key ])) {
232
+			return $this->_request_data[ $key ];
233
+		} else {
234
+			return $default;
235
+		}
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets a single item from the extra data
241
+	 *
242
+	 * @param string       $key
243
+	 * @param string|array $default
244
+	 * @return string|array
245
+	 */
246
+	public function extra_datum($key, $default = '')
247
+	{
248
+		if (isset($this->_extra_data[ $key ])) {
249
+			return $this->_extra_data[ $key ];
250
+		} else {
251
+			return $default;
252
+		}
253
+	}
254
+
255
+
256
+	/**
257
+	 * Adds an extra piece of extra data that we're going to want later during the job
258
+	 *
259
+	 * @param string                $key
260
+	 * @param string|int|array|null $value almost any extra data you want to store
261
+	 */
262
+	public function add_extra_data($key, $value)
263
+	{
264
+		$this->_extra_data[ $key ] = $value;
265
+	}
266
+
267
+
268
+	/**
269
+	 * Array of any extra data we want to store
270
+	 *
271
+	 * @return array
272
+	 */
273
+	public function extra_data()
274
+	{
275
+		return $this->_extra_data;
276
+	}
277
+
278
+
279
+	/**
280
+	 * Returns the job size, in whatever units you want
281
+	 *
282
+	 * @return int
283
+	 */
284
+	public function job_size()
285
+	{
286
+		return $this->_job_size;
287
+	}
288
+
289
+
290
+	/**
291
+	 * Sets the job size. You decide what units to use
292
+	 *
293
+	 * @param int $size
294
+	 */
295
+	public function set_job_size($size)
296
+	{
297
+		$this->_job_size = $size;
298
+	}
299
+
300
+
301
+	/**
302
+	 * The number of "units" processed, in the same units as the "job size"
303
+	 *
304
+	 * @return int
305
+	 */
306
+	public function units_processed()
307
+	{
308
+		return $this->_units_processed;
309
+	}
310
+
311
+
312
+	/**
313
+	 * Marks more units as processed
314
+	 *
315
+	 * @param int $newly_processed
316
+	 * @return int updated units processed
317
+	 */
318
+	public function mark_processed($newly_processed)
319
+	{
320
+		$this->_units_processed += $newly_processed;
321
+		return $this->_units_processed;
322
+	}
323
+
324
+
325
+	/**
326
+	 * Sets the total count of units processed. You might prefer to use mark_processed
327
+	 *
328
+	 * @param int $total_units_processed
329
+	 */
330
+	public function set_units_processed($total_units_processed)
331
+	{
332
+		$this->_units_processed = $total_units_processed;
333
+	}
334
+
335
+
336
+	/**
337
+	 * Sets the job's ID
338
+	 *
339
+	 * @param string $job_id
340
+	 */
341
+	public function set_job_id($job_id)
342
+	{
343
+		$this->_job_id = $job_id;
344
+	}
345
+
346
+
347
+	/**
348
+	 * sets the classname
349
+	 *
350
+	 * @param string $classname
351
+	 */
352
+	public function set_classname($classname)
353
+	{
354
+		$this->_classname = $classname;
355
+	}
356
+
357
+
358
+	/**
359
+	 * Sets the request data
360
+	 *
361
+	 * @param array $request_data
362
+	 */
363
+	public function set_request_data($request_data)
364
+	{
365
+		$this->_request_data = $request_data;
366
+	}
367
+
368
+
369
+	/**
370
+	 * Sets the array of extra data we want to store on this request
371
+	 *
372
+	 * @param array $extra_data
373
+	 */
374
+	public function set_extra_data($extra_data)
375
+	{
376
+		$this->_extra_data = $extra_data;
377
+	}
378
+
379
+
380
+	/**
381
+	 * Gets the name of the wordpress option that should store these job parameters
382
+	 *
383
+	 * @return string
384
+	 */
385
+	public function option_name()
386
+	{
387
+		return JobParameters::wp_option_prefix . $this->job_id();
388
+	}
389
+
390
+
391
+	/**
392
+	 * Gets the job\s current status. One of JobParameters::valid_stati();
393
+	 *
394
+	 * @return string
395
+	 */
396
+	public function status()
397
+	{
398
+		return $this->_status;
399
+	}
400
+
401
+
402
+	/**
403
+	 * @param string $status on eof JobParameters::valid_stati()
404
+	 */
405
+	public function set_status($status)
406
+	{
407
+		$this->_status = $status;
408
+	}
409 409
 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/PreviewEventDeletion.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -34,149 +34,149 @@  discard block
 block discarded – undo
34 34
 class PreviewEventDeletion extends JobHandler
35 35
 {
36 36
 
37
-    /**
38
-     * @var NodeGroupDao
39
-     */
40
-    protected $model_obj_node_group_persister;
37
+	/**
38
+	 * @var NodeGroupDao
39
+	 */
40
+	protected $model_obj_node_group_persister;
41 41
 
42
-    public function __construct(NodeGroupDao $model_obj_node_group_persister)
43
-    {
44
-        $this->model_obj_node_group_persister = $model_obj_node_group_persister;
45
-    }
42
+	public function __construct(NodeGroupDao $model_obj_node_group_persister)
43
+	{
44
+		$this->model_obj_node_group_persister = $model_obj_node_group_persister;
45
+	}
46 46
 
47
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
47
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
48 48
 
49
-    /**
50
-     *
51
-     * @param JobParameters $job_parameters
52
-     * @return JobStepResponse
53
-     * @throws EE_Error
54
-     * @throws InvalidDataTypeException
55
-     * @throws InvalidInterfaceException
56
-     * @throws InvalidArgumentException
57
-     * @throws ReflectionException
58
-     */
59
-    public function create_job(JobParameters $job_parameters)
60
-    {
61
-        // Set the "root" model objects we will want to delete (record their ID and model)
62
-        $event_ids = $job_parameters->request_datum('EVT_IDs', array());
63
-        // Find all the root nodes to delete (this isn't just events, because there's other data, like related tickets,
64
-        // prices, message templates, etc, whose model definition doesn't make them dependent on events. But,
65
-        // we have no UI to access them independent of events, so they may as well get deleted too.)
66
-        $roots = [];
67
-        foreach ($event_ids as $event_id) {
68
-            $roots[] = new ModelObjNode(
69
-                $event_id,
70
-                EEM_Event::instance()
71
-            );
72
-            // Also, we want to delete their related, non-global, tickets, prices and message templates
73
-            $related_non_global_tickets = EEM_Ticket::instance()->get_all_deleted_and_undeleted(
74
-                [
75
-                    [
76
-                        'TKT_is_default' => false,
77
-                        'Datetime.EVT_ID' => $event_id
78
-                    ]
79
-                ]
80
-            );
81
-            foreach ($related_non_global_tickets as $ticket) {
82
-                $roots[] = new ModelObjNode(
83
-                    $ticket->ID(),
84
-                    $ticket->get_model(),
85
-                    ['Registration']
86
-                );
87
-            }
88
-            $related_non_global_prices = EEM_Price::instance()->get_all_deleted_and_undeleted(
89
-                [
90
-                    [
91
-                        'PRC_is_default' => false,
92
-                        'Ticket.Datetime.EVT_ID' => $event_id
93
-                    ]
94
-                ]
95
-            );
96
-            foreach ($related_non_global_prices as $price) {
97
-                $roots[] = new ModelObjNode(
98
-                    $price->ID(),
99
-                    $price->get_model()
100
-                );
101
-            }
102
-        }
103
-        $transactions_ids = $this->getTransactionsToDelete($event_ids);
104
-        foreach ($transactions_ids as $transaction_id) {
105
-            $roots[] = new ModelObjNode(
106
-                $transaction_id,
107
-                EEM_Transaction::instance(),
108
-                ['Registration']
109
-            );
110
-        }
111
-        $job_parameters->add_extra_data('roots', $roots);
112
-        // Set an estimate of how long this will take (we're discovering as we go, so it seems impossible to give
113
-        // an accurate count.)
114
-        $estimated_work_per_model_obj = 10;
115
-        $count_regs = EEM_Registration::instance()->count(
116
-            [
117
-                [
118
-                    'EVT_ID' => ['IN', $event_ids]
119
-                ]
120
-            ]
121
-        );
122
-        $job_parameters->set_job_size((count($roots) + $count_regs) * $estimated_work_per_model_obj);
123
-        return new JobStepResponse(
124
-            $job_parameters,
125
-            esc_html__('Generating preview of data to be deleted...', 'event_espresso')
126
-        );
127
-    }
49
+	/**
50
+	 *
51
+	 * @param JobParameters $job_parameters
52
+	 * @return JobStepResponse
53
+	 * @throws EE_Error
54
+	 * @throws InvalidDataTypeException
55
+	 * @throws InvalidInterfaceException
56
+	 * @throws InvalidArgumentException
57
+	 * @throws ReflectionException
58
+	 */
59
+	public function create_job(JobParameters $job_parameters)
60
+	{
61
+		// Set the "root" model objects we will want to delete (record their ID and model)
62
+		$event_ids = $job_parameters->request_datum('EVT_IDs', array());
63
+		// Find all the root nodes to delete (this isn't just events, because there's other data, like related tickets,
64
+		// prices, message templates, etc, whose model definition doesn't make them dependent on events. But,
65
+		// we have no UI to access them independent of events, so they may as well get deleted too.)
66
+		$roots = [];
67
+		foreach ($event_ids as $event_id) {
68
+			$roots[] = new ModelObjNode(
69
+				$event_id,
70
+				EEM_Event::instance()
71
+			);
72
+			// Also, we want to delete their related, non-global, tickets, prices and message templates
73
+			$related_non_global_tickets = EEM_Ticket::instance()->get_all_deleted_and_undeleted(
74
+				[
75
+					[
76
+						'TKT_is_default' => false,
77
+						'Datetime.EVT_ID' => $event_id
78
+					]
79
+				]
80
+			);
81
+			foreach ($related_non_global_tickets as $ticket) {
82
+				$roots[] = new ModelObjNode(
83
+					$ticket->ID(),
84
+					$ticket->get_model(),
85
+					['Registration']
86
+				);
87
+			}
88
+			$related_non_global_prices = EEM_Price::instance()->get_all_deleted_and_undeleted(
89
+				[
90
+					[
91
+						'PRC_is_default' => false,
92
+						'Ticket.Datetime.EVT_ID' => $event_id
93
+					]
94
+				]
95
+			);
96
+			foreach ($related_non_global_prices as $price) {
97
+				$roots[] = new ModelObjNode(
98
+					$price->ID(),
99
+					$price->get_model()
100
+				);
101
+			}
102
+		}
103
+		$transactions_ids = $this->getTransactionsToDelete($event_ids);
104
+		foreach ($transactions_ids as $transaction_id) {
105
+			$roots[] = new ModelObjNode(
106
+				$transaction_id,
107
+				EEM_Transaction::instance(),
108
+				['Registration']
109
+			);
110
+		}
111
+		$job_parameters->add_extra_data('roots', $roots);
112
+		// Set an estimate of how long this will take (we're discovering as we go, so it seems impossible to give
113
+		// an accurate count.)
114
+		$estimated_work_per_model_obj = 10;
115
+		$count_regs = EEM_Registration::instance()->count(
116
+			[
117
+				[
118
+					'EVT_ID' => ['IN', $event_ids]
119
+				]
120
+			]
121
+		);
122
+		$job_parameters->set_job_size((count($roots) + $count_regs) * $estimated_work_per_model_obj);
123
+		return new JobStepResponse(
124
+			$job_parameters,
125
+			esc_html__('Generating preview of data to be deleted...', 'event_espresso')
126
+		);
127
+	}
128 128
 
129
-    /**
130
-     * @since 4.10.12.p
131
-     * @param EE_Base_Class[] $model_objs
132
-     * @param array $dont_traverse_models
133
-     * @return array
134
-     * @throws EE_Error
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidDataTypeException
137
-     * @throws InvalidInterfaceException
138
-     * @throws ReflectionException
139
-     */
140
-    protected function createModelObjNodes($model_objs, array $dont_traverse_models = [])
141
-    {
142
-        $nodes = [];
143
-        foreach ($model_objs as $model_obj) {
144
-            $nodes[] = new ModelObjNode(
145
-                $model_obj->ID(),
146
-                $model_obj->get_model(),
147
-                $dont_traverse_models
148
-            );
149
-        }
150
-        return $nodes;
151
-    }
129
+	/**
130
+	 * @since 4.10.12.p
131
+	 * @param EE_Base_Class[] $model_objs
132
+	 * @param array $dont_traverse_models
133
+	 * @return array
134
+	 * @throws EE_Error
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws InvalidInterfaceException
138
+	 * @throws ReflectionException
139
+	 */
140
+	protected function createModelObjNodes($model_objs, array $dont_traverse_models = [])
141
+	{
142
+		$nodes = [];
143
+		foreach ($model_objs as $model_obj) {
144
+			$nodes[] = new ModelObjNode(
145
+				$model_obj->ID(),
146
+				$model_obj->get_model(),
147
+				$dont_traverse_models
148
+			);
149
+		}
150
+		return $nodes;
151
+	}
152 152
 
153
-    /**
154
-     * Gets all the transactions related to these events that aren't related to other events. They'll be deleted too.
155
-     * (Ones that are related to other events can stay around until those other events are deleted too.)
156
-     * @since 4.10.12.p
157
-     * @param $event_ids
158
-     * @return array of transaction IDs
159
-     */
160
-    protected function getTransactionsToDelete($event_ids)
161
-    {
162
-        if (empty($event_ids)) {
163
-            return [];
164
-        }
165
-        global $wpdb;
166
-        $event_ids = array_map(
167
-            'intval',
168
-            $event_ids
169
-        );
170
-        $imploded_sanitized_event_ids = implode(',', $event_ids);
171
-        // Select transactions with registrations for the events $event_ids which also don't have registrations
172
-        // for any events NOT in $event_ids.
173
-        // Notice the outer query searched for transactions whose registrations ARE in $event_ids,
174
-        // whereas the inner query checks if the outer query's transaction has any registrations that are
175
-        // NOT IN $event_ids (ie, don't have registrations for events we're not just about to delete.)
176
-        return array_map(
177
-            'intval',
178
-            $wpdb->get_col(
179
-                "SELECT 
153
+	/**
154
+	 * Gets all the transactions related to these events that aren't related to other events. They'll be deleted too.
155
+	 * (Ones that are related to other events can stay around until those other events are deleted too.)
156
+	 * @since 4.10.12.p
157
+	 * @param $event_ids
158
+	 * @return array of transaction IDs
159
+	 */
160
+	protected function getTransactionsToDelete($event_ids)
161
+	{
162
+		if (empty($event_ids)) {
163
+			return [];
164
+		}
165
+		global $wpdb;
166
+		$event_ids = array_map(
167
+			'intval',
168
+			$event_ids
169
+		);
170
+		$imploded_sanitized_event_ids = implode(',', $event_ids);
171
+		// Select transactions with registrations for the events $event_ids which also don't have registrations
172
+		// for any events NOT in $event_ids.
173
+		// Notice the outer query searched for transactions whose registrations ARE in $event_ids,
174
+		// whereas the inner query checks if the outer query's transaction has any registrations that are
175
+		// NOT IN $event_ids (ie, don't have registrations for events we're not just about to delete.)
176
+		return array_map(
177
+			'intval',
178
+			$wpdb->get_col(
179
+				"SELECT 
180 180
                       DISTINCT t.TXN_ID
181 181
                     FROM 
182 182
                       {$wpdb->prefix}esp_transaction t INNER JOIN 
@@ -194,83 +194,83 @@  discard block
 block discarded – undo
194 194
                            tsub.TXN_ID=t.TXN_ID AND
195 195
                            rsub.EVT_ID NOT IN ({$imploded_sanitized_event_ids})
196 196
                        )"
197
-            )
198
-        );
199
-    }
197
+			)
198
+		);
199
+	}
200 200
 
201
-    /**
202
-     * Performs another step of the job
203
-     * @param JobParameters $job_parameters
204
-     * @param int $batch_size
205
-     * @return JobStepResponse
206
-     */
207
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
208
-    {
209
-        // Serializing and unserializing is what really makes this drag on (eg on localhost, the ajax requests took
210
-        // about 4 seconds when the batch size was 250, but 3 seconds when the batch size was 50. So like
211
-        // 50% of the request is just serializing and unserializing.) So, make the batches much bigger.
212
-        $batch_size *= 3;
213
-        $units_processed = 0;
214
-        foreach ($job_parameters->extra_datum('roots', array()) as $root_node) {
215
-            if ($units_processed >= $batch_size) {
216
-                break;
217
-            }
218
-            if (!$root_node instanceof ModelObjNode) {
219
-                throw new InvalidClassException('ModelObjNode');
220
-            }
221
-            if ($root_node->isComplete()) {
222
-                continue;
223
-            }
224
-            $units_processed += $root_node->visit($batch_size - $units_processed);
225
-        }
226
-        $job_parameters->mark_processed($units_processed);
227
-        // If the most-recently processed root node is complete, we must be all done because we're doing them
228
-        // sequentially.
229
-        if (isset($root_node) && $root_node instanceof ModelObjNode && $root_node->isComplete()) {
230
-            $job_parameters->set_status(JobParameters::status_complete);
231
-            // Show a full progress bar.
232
-            $job_parameters->set_units_processed($job_parameters->job_size());
233
-            $deletion_job_code = $job_parameters->request_datum('deletion_job_code');
234
-            $this->model_obj_node_group_persister->persistModelObjNodesGroup(
235
-                $job_parameters->extra_datum('roots'),
236
-                $deletion_job_code
237
-            );
238
-            return new JobStepResponse(
239
-                $job_parameters,
240
-                esc_html__('Finished identifying items for deletion.', 'event_espresso'),
241
-                [
242
-                    'deletion_job_code' => $deletion_job_code
243
-                ]
244
-            );
245
-        } else {
246
-            // Because the job size was a guess, it may have likely been proven wrong. We don't want to show more work
247
-            // done than we originally said there would be. So adjust the estimate.
248
-            if (($job_parameters->units_processed() / $job_parameters->job_size()) > .8) {
249
-                $job_parameters->set_job_size($job_parameters->job_size() * 2);
250
-            }
251
-            return new JobStepResponse(
252
-                $job_parameters,
253
-                sprintf(
254
-                    esc_html__('Identified %d items for deletion.', 'event_espresso'),
255
-                    $units_processed
256
-                )
257
-            );
258
-        }
259
-    }
201
+	/**
202
+	 * Performs another step of the job
203
+	 * @param JobParameters $job_parameters
204
+	 * @param int $batch_size
205
+	 * @return JobStepResponse
206
+	 */
207
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
208
+	{
209
+		// Serializing and unserializing is what really makes this drag on (eg on localhost, the ajax requests took
210
+		// about 4 seconds when the batch size was 250, but 3 seconds when the batch size was 50. So like
211
+		// 50% of the request is just serializing and unserializing.) So, make the batches much bigger.
212
+		$batch_size *= 3;
213
+		$units_processed = 0;
214
+		foreach ($job_parameters->extra_datum('roots', array()) as $root_node) {
215
+			if ($units_processed >= $batch_size) {
216
+				break;
217
+			}
218
+			if (!$root_node instanceof ModelObjNode) {
219
+				throw new InvalidClassException('ModelObjNode');
220
+			}
221
+			if ($root_node->isComplete()) {
222
+				continue;
223
+			}
224
+			$units_processed += $root_node->visit($batch_size - $units_processed);
225
+		}
226
+		$job_parameters->mark_processed($units_processed);
227
+		// If the most-recently processed root node is complete, we must be all done because we're doing them
228
+		// sequentially.
229
+		if (isset($root_node) && $root_node instanceof ModelObjNode && $root_node->isComplete()) {
230
+			$job_parameters->set_status(JobParameters::status_complete);
231
+			// Show a full progress bar.
232
+			$job_parameters->set_units_processed($job_parameters->job_size());
233
+			$deletion_job_code = $job_parameters->request_datum('deletion_job_code');
234
+			$this->model_obj_node_group_persister->persistModelObjNodesGroup(
235
+				$job_parameters->extra_datum('roots'),
236
+				$deletion_job_code
237
+			);
238
+			return new JobStepResponse(
239
+				$job_parameters,
240
+				esc_html__('Finished identifying items for deletion.', 'event_espresso'),
241
+				[
242
+					'deletion_job_code' => $deletion_job_code
243
+				]
244
+			);
245
+		} else {
246
+			// Because the job size was a guess, it may have likely been proven wrong. We don't want to show more work
247
+			// done than we originally said there would be. So adjust the estimate.
248
+			if (($job_parameters->units_processed() / $job_parameters->job_size()) > .8) {
249
+				$job_parameters->set_job_size($job_parameters->job_size() * 2);
250
+			}
251
+			return new JobStepResponse(
252
+				$job_parameters,
253
+				sprintf(
254
+					esc_html__('Identified %d items for deletion.', 'event_espresso'),
255
+					$units_processed
256
+				)
257
+			);
258
+		}
259
+	}
260 260
 
261
-    /**
262
-     * Performs any clean-up logic when we know the job is completed
263
-     * @param JobParameters $job_parameters
264
-     * @return JobStepResponse
265
-     */
266
-    public function cleanup_job(JobParameters $job_parameters)
267
-    {
268
-        // Nothing much to do. We can't delete the option with the built tree because we may need it in a moment for the deletion
269
-        return new JobStepResponse(
270
-            $job_parameters,
271
-            esc_html__('All done', 'event_espresso')
272
-        );
273
-    }
261
+	/**
262
+	 * Performs any clean-up logic when we know the job is completed
263
+	 * @param JobParameters $job_parameters
264
+	 * @return JobStepResponse
265
+	 */
266
+	public function cleanup_job(JobParameters $job_parameters)
267
+	{
268
+		// Nothing much to do. We can't delete the option with the built tree because we may need it in a moment for the deletion
269
+		return new JobStepResponse(
270
+			$job_parameters,
271
+			esc_html__('All done', 'event_espresso')
272
+		);
273
+	}
274 274
 }
275 275
 // End of file EventDeletion.php
276 276
 // Location: EventEspressoBatchRequest\JobHandlers/EventDeletion.php
Please login to merge, or discard this patch.
core/libraries/rest_api/ModelDataTranslator.php 1 patch
Indentation   +642 added lines, -642 removed lines patch added patch discarded remove patch
@@ -39,646 +39,646 @@
 block discarded – undo
39 39
 class ModelDataTranslator
40 40
 {
41 41
 
42
-    /**
43
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
44
-     * fields that COULD contain -1; so we use null
45
-     */
46
-    const EE_INF_IN_REST = null;
47
-
48
-
49
-    /**
50
-     * Prepares a possible array of input values from JSON for use by the models
51
-     *
52
-     * @param EE_Model_Field_Base $field_obj
53
-     * @param mixed               $original_value_maybe_array
54
-     * @param string              $requested_version
55
-     * @param string              $timezone_string treat values as being in this timezone
56
-     * @return mixed
57
-     * @throws RestException
58
-     */
59
-    public static function prepareFieldValuesFromJson(
60
-        $field_obj,
61
-        $original_value_maybe_array,
62
-        $requested_version,
63
-        $timezone_string = 'UTC'
64
-    ) {
65
-        if (is_array($original_value_maybe_array)
66
-            && ! $field_obj instanceof EE_Serialized_Text_Field
67
-        ) {
68
-            $new_value_maybe_array = array();
69
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
70
-                $new_value_maybe_array[ $array_key ] = ModelDataTranslator::prepareFieldValueFromJson(
71
-                    $field_obj,
72
-                    $array_item,
73
-                    $requested_version,
74
-                    $timezone_string
75
-                );
76
-            }
77
-        } else {
78
-            $new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
79
-                $field_obj,
80
-                $original_value_maybe_array,
81
-                $requested_version,
82
-                $timezone_string
83
-            );
84
-        }
85
-        return $new_value_maybe_array;
86
-    }
87
-
88
-
89
-    /**
90
-     * Prepares an array of field values FOR use in JSON/REST API
91
-     *
92
-     * @param EE_Model_Field_Base $field_obj
93
-     * @param mixed               $original_value_maybe_array
94
-     * @param string              $request_version (eg 4.8.36)
95
-     * @return array
96
-     */
97
-    public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
98
-    {
99
-        if (is_array($original_value_maybe_array)) {
100
-            $new_value = array();
101
-            foreach ($original_value_maybe_array as $key => $value) {
102
-                $new_value[ $key ] = ModelDataTranslator::prepareFieldValuesForJson(
103
-                    $field_obj,
104
-                    $value,
105
-                    $request_version
106
-                );
107
-            }
108
-        } else {
109
-            $new_value = ModelDataTranslator::prepareFieldValueForJson(
110
-                $field_obj,
111
-                $original_value_maybe_array,
112
-                $request_version
113
-            );
114
-        }
115
-        return $new_value;
116
-    }
117
-
118
-
119
-    /**
120
-     * Prepares incoming data from the json or request parameters for the models'
121
-     * "$query_params".
122
-     *
123
-     * @param EE_Model_Field_Base $field_obj
124
-     * @param mixed               $original_value
125
-     * @param string              $requested_version
126
-     * @param string              $timezone_string treat values as being in this timezone
127
-     * @return mixed
128
-     * @throws RestException
129
-     * @throws DomainException
130
-     * @throws EE_Error
131
-     */
132
-    public static function prepareFieldValueFromJson(
133
-        $field_obj,
134
-        $original_value,
135
-        $requested_version,
136
-        $timezone_string = 'UTC' // UTC
137
-    ) {
138
-        // check if they accidentally submitted an error value. If so throw an exception
139
-        if (is_array($original_value)
140
-            && isset($original_value['error_code'], $original_value['error_message'])) {
141
-            throw new RestException(
142
-                'rest_submitted_error_value',
143
-                sprintf(
144
-                    esc_html__(
145
-                        'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
146
-                        'event_espresso'
147
-                    ),
148
-                    $field_obj->get_name()
149
-                ),
150
-                array(
151
-                    'status' => 400,
152
-                )
153
-            );
154
-        }
155
-        // double-check for serialized PHP. We never accept serialized PHP. No way Jose.
156
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
157
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
158
-        $new_value = null;
159
-        // walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
160
-        // way Jose.
161
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
162
-        if ($field_obj instanceof EE_Infinite_Integer_Field
163
-            && in_array($original_value, array(null, ''), true)
164
-        ) {
165
-            $new_value = EE_INF;
166
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
167
-            $new_value = rest_parse_date(
168
-                self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
169
-            );
170
-            if ($new_value === false) {
171
-                throw new RestException(
172
-                    'invalid_format_for_timestamp',
173
-                    sprintf(
174
-                        esc_html__(
175
-                            'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
176
-                            'event_espresso'
177
-                        ),
178
-                        'RFC3339',
179
-                        'ISO8601',
180
-                        $original_value
181
-                    ),
182
-                    array(
183
-                        'status' => 400,
184
-                    )
185
-                );
186
-            }
187
-        } elseif ($field_obj instanceof EE_Boolean_Field) {
188
-            // Interpreted the strings "false", "true", "on", "off" appropriately.
189
-            $new_value = filter_var($original_value, FILTER_VALIDATE_BOOLEAN);
190
-        } else {
191
-            $new_value = $original_value;
192
-        }
193
-        return $new_value;
194
-    }
195
-
196
-
197
-    /**
198
-     * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
199
-     * information via details obtained from the host site.
200
-     *
201
-     * @param string            $original_timestamp
202
-     * @param EE_Datetime_Field $datetime_field
203
-     * @param                   $timezone_string
204
-     * @return string
205
-     * @throws DomainException
206
-     */
207
-    private static function getTimestampWithTimezoneOffset(
208
-        $original_timestamp,
209
-        EE_Datetime_Field $datetime_field,
210
-        $timezone_string
211
-    ) {
212
-        // already have timezone information?
213
-        if (preg_match('/Z|(\+|\-)(\d{2}:\d{2})/', $original_timestamp)) {
214
-            // yes, we're ignoring the timezone.
215
-            return $original_timestamp;
216
-        }
217
-        // need to append timezone
218
-        list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
219
-            $datetime_field->get_timezone_offset(
220
-                new \DateTimeZone($timezone_string),
221
-                $original_timestamp
222
-            )
223
-        );
224
-        $offset_string =
225
-            str_pad(
226
-                floor($offset_secs / HOUR_IN_SECONDS),
227
-                2,
228
-                '0',
229
-                STR_PAD_LEFT
230
-            )
231
-            . ':'
232
-            . str_pad(
233
-                ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
234
-                2,
235
-                '0',
236
-                STR_PAD_LEFT
237
-            );
238
-        return $original_timestamp . $offset_sign . $offset_string;
239
-    }
240
-
241
-
242
-    /**
243
-     * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
244
-     * think that can happen). If $data is an array, recurses into its keys and values
245
-     *
246
-     * @param mixed $data
247
-     * @throws RestException
248
-     * @return void
249
-     */
250
-    public static function throwExceptionIfContainsSerializedData($data)
251
-    {
252
-        if (is_array($data)) {
253
-            foreach ($data as $key => $value) {
254
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
255
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
256
-            }
257
-        } else {
258
-            if (is_serialized($data) || is_object($data)) {
259
-                throw new RestException(
260
-                    'serialized_data_submission_prohibited',
261
-                    esc_html__(
262
-                    // @codingStandardsIgnoreStart
263
-                        'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
264
-                        // @codingStandardsIgnoreEnd
265
-                        'event_espresso'
266
-                    )
267
-                );
268
-            }
269
-        }
270
-    }
271
-
272
-
273
-    /**
274
-     * determines what's going on with them timezone strings
275
-     *
276
-     * @param int $timezone_offset
277
-     * @return array
278
-     */
279
-    private static function parseTimezoneOffset($timezone_offset)
280
-    {
281
-        $first_char = substr((string) $timezone_offset, 0, 1);
282
-        if ($first_char === '+' || $first_char === '-') {
283
-            $offset_sign = $first_char;
284
-            $offset_secs = substr((string) $timezone_offset, 1);
285
-        } else {
286
-            $offset_sign = '+';
287
-            $offset_secs = $timezone_offset;
288
-        }
289
-        return array($offset_sign, $offset_secs);
290
-    }
291
-
292
-
293
-    /**
294
-     * Prepares a field's value for display in the API
295
-     *
296
-     * @param EE_Model_Field_Base $field_obj
297
-     * @param mixed               $original_value
298
-     * @param string              $requested_version
299
-     * @return mixed
300
-     */
301
-    public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
302
-    {
303
-        if ($original_value === EE_INF) {
304
-            $new_value = ModelDataTranslator::EE_INF_IN_REST;
305
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
306
-            if (is_string($original_value)) {
307
-                // did they submit a string of a unix timestamp?
308
-                if (is_numeric($original_value)) {
309
-                    $datetime_obj = new \DateTime();
310
-                    $datetime_obj->setTimestamp((int) $original_value);
311
-                } else {
312
-                    // first, check if its a MySQL timestamp in GMT
313
-                    $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
314
-                }
315
-                if (! $datetime_obj instanceof \DateTime) {
316
-                    // so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
317
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
318
-                }
319
-                $original_value = $datetime_obj;
320
-            }
321
-            if ($original_value instanceof \DateTime) {
322
-                $new_value = $original_value->format('Y-m-d H:i:s');
323
-            } elseif (is_int($original_value) || is_float($original_value)) {
324
-                $new_value = date('Y-m-d H:i:s', $original_value);
325
-            } elseif ($original_value === null || $original_value === '') {
326
-                $new_value = null;
327
-            } else {
328
-                // so it's not a datetime object, unix timestamp (as string or int),
329
-                // MySQL timestamp, or even a string in the field object's format. So no idea what it is
330
-                throw new \EE_Error(
331
-                    sprintf(
332
-                        esc_html__(
333
-                        // @codingStandardsIgnoreStart
334
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
335
-                            // @codingStandardsIgnoreEnd
336
-                            'event_espresso'
337
-                        ),
338
-                        $original_value,
339
-                        $field_obj->get_name(),
340
-                        $field_obj->get_model_name(),
341
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
342
-                    )
343
-                );
344
-            }
345
-            if ($new_value !== null) {
346
-                $new_value = mysql_to_rfc3339($new_value);
347
-            }
348
-        } else {
349
-            $new_value = $original_value;
350
-        }
351
-        // are we about to send an object? just don't. We have no good way to represent it in JSON.
352
-        // can't just check using is_object() because that missed PHP incomplete objects
353
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
354
-            $new_value = array(
355
-                'error_code'    => 'php_object_not_return',
356
-                'error_message' => esc_html__(
357
-                    'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
358
-                    'event_espresso'
359
-                ),
360
-            );
361
-        }
362
-        return apply_filters(
363
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
364
-            $new_value,
365
-            $field_obj,
366
-            $original_value,
367
-            $requested_version
368
-        );
369
-    }
370
-
371
-
372
-    /**
373
-     * Prepares condition-query-parameters (like what's in where and having) from
374
-     * the format expected in the API to use in the models
375
-     *
376
-     * @param array $inputted_query_params_of_this_type
377
-     * @param EEM_Base $model
378
-     * @param string $requested_version
379
-     * @param boolean $writing whether this data will be written to the DB, or if we're just building a query.
380
-     *                          If we're writing to the DB, we don't expect any operators, or any logic query
381
-     *                          parameters, and we also won't accept serialized data unless the current user has
382
-     *                          unfiltered_html.
383
-     * @return array
384
-     * @throws DomainException
385
-     * @throws EE_Error
386
-     * @throws RestException
387
-     * @throws InvalidDataTypeException
388
-     * @throws InvalidInterfaceException
389
-     * @throws InvalidArgumentException
390
-     */
391
-    public static function prepareConditionsQueryParamsForModels(
392
-        $inputted_query_params_of_this_type,
393
-        EEM_Base $model,
394
-        $requested_version,
395
-        $writing = false
396
-    ) {
397
-        $query_param_for_models = array();
398
-        $context = new RestIncomingQueryParamContext($model, $requested_version, $writing);
399
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
400
-            $query_param_meta = new RestIncomingQueryParamMetadata($query_param_key, $query_param_value, $context);
401
-            if ($query_param_meta->getField() instanceof EE_Model_Field_Base) {
402
-                $translated_value = $query_param_meta->determineConditionsQueryParameterValue();
403
-                if ((isset($query_param_for_models[ $query_param_meta->getQueryParamKey() ]) && $query_param_meta->isGmtField())
404
-                    || $translated_value === null
405
-                ) {
406
-                    // they have already provided a non-gmt field, ignore the gmt one. That's what WP core
407
-                    // currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
408
-                    // OR we couldn't create a translated value from their input
409
-                    continue;
410
-                }
411
-                $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $translated_value;
412
-            } else {
413
-                $nested_query_params = $query_param_meta->determineNestedConditionQueryParameters();
414
-                if ($nested_query_params) {
415
-                    $query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $nested_query_params;
416
-                }
417
-            }
418
-        }
419
-        return $query_param_for_models;
420
-    }
421
-
422
-    /**
423
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
424
-     * gmt date field name
425
-     *
426
-     * @param string $field_name
427
-     * @return boolean
428
-     */
429
-    public static function isGmtDateFieldName($field_name)
430
-    {
431
-        return substr(
432
-            ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
433
-            -4,
434
-            4
435
-        ) === '_gmt';
436
-    }
437
-
438
-
439
-    /**
440
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
441
-     *
442
-     * @param string $field_name
443
-     * @return string
444
-     */
445
-    public static function removeGmtFromFieldName($field_name)
446
-    {
447
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
448
-            return $field_name;
449
-        }
450
-        $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
451
-            $field_name
452
-        );
453
-        $query_param_sans_gmt_and_sans_stars = substr(
454
-            $query_param_sans_stars,
455
-            0,
456
-            strrpos(
457
-                $field_name,
458
-                '_gmt'
459
-            )
460
-        );
461
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
462
-    }
463
-
464
-
465
-    /**
466
-     * Takes a field name from the REST API and prepares it for the model querying
467
-     *
468
-     * @param string $field_name
469
-     * @return string
470
-     */
471
-    public static function prepareFieldNameFromJson($field_name)
472
-    {
473
-        if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
474
-            return ModelDataTranslator::removeGmtFromFieldName($field_name);
475
-        }
476
-        return $field_name;
477
-    }
478
-
479
-
480
-    /**
481
-     * Takes array of field names from REST API and prepares for models
482
-     *
483
-     * @param array $field_names
484
-     * @return array of field names (possibly include model prefixes)
485
-     */
486
-    public static function prepareFieldNamesFromJson(array $field_names)
487
-    {
488
-        $new_array = array();
489
-        foreach ($field_names as $key => $field_name) {
490
-            $new_array[ $key ] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
491
-        }
492
-        return $new_array;
493
-    }
494
-
495
-
496
-    /**
497
-     * Takes array where array keys are field names (possibly with model path prefixes)
498
-     * from the REST API and prepares them for model querying
499
-     *
500
-     * @param array $field_names_as_keys
501
-     * @return array
502
-     */
503
-    public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
504
-    {
505
-        $new_array = array();
506
-        foreach ($field_names_as_keys as $field_name => $value) {
507
-            $new_array[ ModelDataTranslator::prepareFieldNameFromJson($field_name) ] = $value;
508
-        }
509
-        return $new_array;
510
-    }
511
-
512
-
513
-    /**
514
-     * Prepares an array of model query params for use in the REST API
515
-     *
516
-     * @param array    $model_query_params
517
-     * @param EEM_Base $model
518
-     * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
519
-     *                                     REST API
520
-     * @return array which can be passed into the EE4 REST API when querying a model resource
521
-     * @throws EE_Error
522
-     */
523
-    public static function prepareQueryParamsForRestApi(
524
-        array $model_query_params,
525
-        EEM_Base $model,
526
-        $requested_version = null
527
-    ) {
528
-        if ($requested_version === null) {
529
-            $requested_version = EED_Core_Rest_Api::latest_rest_api_version();
530
-        }
531
-        $rest_query_params = $model_query_params;
532
-        if (isset($model_query_params[0])) {
533
-            $rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
534
-                $model_query_params[0],
535
-                $model,
536
-                $requested_version
537
-            );
538
-            unset($rest_query_params[0]);
539
-        }
540
-        if (isset($model_query_params['having'])) {
541
-            $rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
542
-                $model_query_params['having'],
543
-                $model,
544
-                $requested_version
545
-            );
546
-        }
547
-        return apply_filters(
548
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
549
-            $rest_query_params,
550
-            $model_query_params,
551
-            $model,
552
-            $requested_version
553
-        );
554
-    }
555
-
556
-
557
-    /**
558
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
559
-     *
560
-     * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
561
-     *                                                      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
562
-     * @param EEM_Base $model
563
-     * @param string   $requested_version                   eg "4.8.36"
564
-     * @return array ready for use in the rest api query params
565
-     * @throws EE_Error
566
-     * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
567
-     *                                                      (which would be really unusual)
568
-     */
569
-    public static function prepareConditionsQueryParamsForRestApi(
570
-        $inputted_query_params_of_this_type,
571
-        EEM_Base $model,
572
-        $requested_version
573
-    ) {
574
-        $query_param_for_models = array();
575
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
576
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
577
-                ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
578
-                $model
579
-            );
580
-            if ($field instanceof EE_Model_Field_Base) {
581
-                // did they specify an operator?
582
-                if (is_array($query_param_value)) {
583
-                    $op = $query_param_value[0];
584
-                    $translated_value = array($op);
585
-                    if (isset($query_param_value[1])) {
586
-                        $value = $query_param_value[1];
587
-                        $translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
588
-                            $field,
589
-                            $value,
590
-                            $requested_version
591
-                        );
592
-                    }
593
-                } else {
594
-                    $translated_value = ModelDataTranslator::prepareFieldValueForJson(
595
-                        $field,
596
-                        $query_param_value,
597
-                        $requested_version
598
-                    );
599
-                }
600
-                $query_param_for_models[ $query_param_key ] = $translated_value;
601
-            } else {
602
-                // so it's not for a field, assume it's a logic query param key
603
-                $query_param_for_models[ $query_param_key ] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
604
-                    $query_param_value,
605
-                    $model,
606
-                    $requested_version
607
-                );
608
-            }
609
-        }
610
-        return $query_param_for_models;
611
-    }
612
-
613
-
614
-    /**
615
-     * @param $condition_query_param_key
616
-     * @return string
617
-     */
618
-    public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
619
-    {
620
-        $pos_of_star = strpos($condition_query_param_key, '*');
621
-        if ($pos_of_star === false) {
622
-            return $condition_query_param_key;
623
-        } else {
624
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
625
-            return $condition_query_param_sans_star;
626
-        }
627
-    }
628
-
629
-
630
-    /**
631
-     * Takes the input parameter and finds the model field that it indicates.
632
-     *
633
-     * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
634
-     * @param EEM_Base $model
635
-     * @return EE_Model_Field_Base
636
-     * @throws EE_Error
637
-     */
638
-    public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
639
-    {
640
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
641
-        // which will help us find the database table and column
642
-        $query_param_parts = explode('.', $query_param_name);
643
-        if (empty($query_param_parts)) {
644
-            throw new EE_Error(
645
-                sprintf(
646
-                    __(
647
-                        '_extract_column_name is empty when trying to extract column and table name from %s',
648
-                        'event_espresso'
649
-                    ),
650
-                    $query_param_name
651
-                )
652
-            );
653
-        }
654
-        $number_of_parts = count($query_param_parts);
655
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
656
-        if ($number_of_parts === 1) {
657
-            $field_name = $last_query_param_part;
658
-        } else {// $number_of_parts >= 2
659
-            // the last part is the column name, and there are only 2parts. therefore...
660
-            $field_name = $last_query_param_part;
661
-            $model = \EE_Registry::instance()->load_model($query_param_parts[ $number_of_parts - 2 ]);
662
-        }
663
-        try {
664
-            return $model->field_settings_for($field_name, false);
665
-        } catch (EE_Error $e) {
666
-            return null;
667
-        }
668
-    }
669
-
670
-
671
-    /**
672
-     * Returns true if $data can be easily represented in JSON.
673
-     * Basically, objects and resources can't be represented in JSON easily.
674
-     *
675
-     * @param mixed $data
676
-     * @return bool
677
-     */
678
-    protected static function isRepresentableInJson($data)
679
-    {
680
-        return is_scalar($data)
681
-               || is_array($data)
682
-               || is_null($data);
683
-    }
42
+	/**
43
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
44
+	 * fields that COULD contain -1; so we use null
45
+	 */
46
+	const EE_INF_IN_REST = null;
47
+
48
+
49
+	/**
50
+	 * Prepares a possible array of input values from JSON for use by the models
51
+	 *
52
+	 * @param EE_Model_Field_Base $field_obj
53
+	 * @param mixed               $original_value_maybe_array
54
+	 * @param string              $requested_version
55
+	 * @param string              $timezone_string treat values as being in this timezone
56
+	 * @return mixed
57
+	 * @throws RestException
58
+	 */
59
+	public static function prepareFieldValuesFromJson(
60
+		$field_obj,
61
+		$original_value_maybe_array,
62
+		$requested_version,
63
+		$timezone_string = 'UTC'
64
+	) {
65
+		if (is_array($original_value_maybe_array)
66
+			&& ! $field_obj instanceof EE_Serialized_Text_Field
67
+		) {
68
+			$new_value_maybe_array = array();
69
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
70
+				$new_value_maybe_array[ $array_key ] = ModelDataTranslator::prepareFieldValueFromJson(
71
+					$field_obj,
72
+					$array_item,
73
+					$requested_version,
74
+					$timezone_string
75
+				);
76
+			}
77
+		} else {
78
+			$new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
79
+				$field_obj,
80
+				$original_value_maybe_array,
81
+				$requested_version,
82
+				$timezone_string
83
+			);
84
+		}
85
+		return $new_value_maybe_array;
86
+	}
87
+
88
+
89
+	/**
90
+	 * Prepares an array of field values FOR use in JSON/REST API
91
+	 *
92
+	 * @param EE_Model_Field_Base $field_obj
93
+	 * @param mixed               $original_value_maybe_array
94
+	 * @param string              $request_version (eg 4.8.36)
95
+	 * @return array
96
+	 */
97
+	public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
98
+	{
99
+		if (is_array($original_value_maybe_array)) {
100
+			$new_value = array();
101
+			foreach ($original_value_maybe_array as $key => $value) {
102
+				$new_value[ $key ] = ModelDataTranslator::prepareFieldValuesForJson(
103
+					$field_obj,
104
+					$value,
105
+					$request_version
106
+				);
107
+			}
108
+		} else {
109
+			$new_value = ModelDataTranslator::prepareFieldValueForJson(
110
+				$field_obj,
111
+				$original_value_maybe_array,
112
+				$request_version
113
+			);
114
+		}
115
+		return $new_value;
116
+	}
117
+
118
+
119
+	/**
120
+	 * Prepares incoming data from the json or request parameters for the models'
121
+	 * "$query_params".
122
+	 *
123
+	 * @param EE_Model_Field_Base $field_obj
124
+	 * @param mixed               $original_value
125
+	 * @param string              $requested_version
126
+	 * @param string              $timezone_string treat values as being in this timezone
127
+	 * @return mixed
128
+	 * @throws RestException
129
+	 * @throws DomainException
130
+	 * @throws EE_Error
131
+	 */
132
+	public static function prepareFieldValueFromJson(
133
+		$field_obj,
134
+		$original_value,
135
+		$requested_version,
136
+		$timezone_string = 'UTC' // UTC
137
+	) {
138
+		// check if they accidentally submitted an error value. If so throw an exception
139
+		if (is_array($original_value)
140
+			&& isset($original_value['error_code'], $original_value['error_message'])) {
141
+			throw new RestException(
142
+				'rest_submitted_error_value',
143
+				sprintf(
144
+					esc_html__(
145
+						'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
146
+						'event_espresso'
147
+					),
148
+					$field_obj->get_name()
149
+				),
150
+				array(
151
+					'status' => 400,
152
+				)
153
+			);
154
+		}
155
+		// double-check for serialized PHP. We never accept serialized PHP. No way Jose.
156
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
157
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
158
+		$new_value = null;
159
+		// walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
160
+		// way Jose.
161
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
162
+		if ($field_obj instanceof EE_Infinite_Integer_Field
163
+			&& in_array($original_value, array(null, ''), true)
164
+		) {
165
+			$new_value = EE_INF;
166
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
167
+			$new_value = rest_parse_date(
168
+				self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
169
+			);
170
+			if ($new_value === false) {
171
+				throw new RestException(
172
+					'invalid_format_for_timestamp',
173
+					sprintf(
174
+						esc_html__(
175
+							'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
176
+							'event_espresso'
177
+						),
178
+						'RFC3339',
179
+						'ISO8601',
180
+						$original_value
181
+					),
182
+					array(
183
+						'status' => 400,
184
+					)
185
+				);
186
+			}
187
+		} elseif ($field_obj instanceof EE_Boolean_Field) {
188
+			// Interpreted the strings "false", "true", "on", "off" appropriately.
189
+			$new_value = filter_var($original_value, FILTER_VALIDATE_BOOLEAN);
190
+		} else {
191
+			$new_value = $original_value;
192
+		}
193
+		return $new_value;
194
+	}
195
+
196
+
197
+	/**
198
+	 * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
199
+	 * information via details obtained from the host site.
200
+	 *
201
+	 * @param string            $original_timestamp
202
+	 * @param EE_Datetime_Field $datetime_field
203
+	 * @param                   $timezone_string
204
+	 * @return string
205
+	 * @throws DomainException
206
+	 */
207
+	private static function getTimestampWithTimezoneOffset(
208
+		$original_timestamp,
209
+		EE_Datetime_Field $datetime_field,
210
+		$timezone_string
211
+	) {
212
+		// already have timezone information?
213
+		if (preg_match('/Z|(\+|\-)(\d{2}:\d{2})/', $original_timestamp)) {
214
+			// yes, we're ignoring the timezone.
215
+			return $original_timestamp;
216
+		}
217
+		// need to append timezone
218
+		list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
219
+			$datetime_field->get_timezone_offset(
220
+				new \DateTimeZone($timezone_string),
221
+				$original_timestamp
222
+			)
223
+		);
224
+		$offset_string =
225
+			str_pad(
226
+				floor($offset_secs / HOUR_IN_SECONDS),
227
+				2,
228
+				'0',
229
+				STR_PAD_LEFT
230
+			)
231
+			. ':'
232
+			. str_pad(
233
+				($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
234
+				2,
235
+				'0',
236
+				STR_PAD_LEFT
237
+			);
238
+		return $original_timestamp . $offset_sign . $offset_string;
239
+	}
240
+
241
+
242
+	/**
243
+	 * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
244
+	 * think that can happen). If $data is an array, recurses into its keys and values
245
+	 *
246
+	 * @param mixed $data
247
+	 * @throws RestException
248
+	 * @return void
249
+	 */
250
+	public static function throwExceptionIfContainsSerializedData($data)
251
+	{
252
+		if (is_array($data)) {
253
+			foreach ($data as $key => $value) {
254
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
255
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
256
+			}
257
+		} else {
258
+			if (is_serialized($data) || is_object($data)) {
259
+				throw new RestException(
260
+					'serialized_data_submission_prohibited',
261
+					esc_html__(
262
+					// @codingStandardsIgnoreStart
263
+						'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
264
+						// @codingStandardsIgnoreEnd
265
+						'event_espresso'
266
+					)
267
+				);
268
+			}
269
+		}
270
+	}
271
+
272
+
273
+	/**
274
+	 * determines what's going on with them timezone strings
275
+	 *
276
+	 * @param int $timezone_offset
277
+	 * @return array
278
+	 */
279
+	private static function parseTimezoneOffset($timezone_offset)
280
+	{
281
+		$first_char = substr((string) $timezone_offset, 0, 1);
282
+		if ($first_char === '+' || $first_char === '-') {
283
+			$offset_sign = $first_char;
284
+			$offset_secs = substr((string) $timezone_offset, 1);
285
+		} else {
286
+			$offset_sign = '+';
287
+			$offset_secs = $timezone_offset;
288
+		}
289
+		return array($offset_sign, $offset_secs);
290
+	}
291
+
292
+
293
+	/**
294
+	 * Prepares a field's value for display in the API
295
+	 *
296
+	 * @param EE_Model_Field_Base $field_obj
297
+	 * @param mixed               $original_value
298
+	 * @param string              $requested_version
299
+	 * @return mixed
300
+	 */
301
+	public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
302
+	{
303
+		if ($original_value === EE_INF) {
304
+			$new_value = ModelDataTranslator::EE_INF_IN_REST;
305
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
306
+			if (is_string($original_value)) {
307
+				// did they submit a string of a unix timestamp?
308
+				if (is_numeric($original_value)) {
309
+					$datetime_obj = new \DateTime();
310
+					$datetime_obj->setTimestamp((int) $original_value);
311
+				} else {
312
+					// first, check if its a MySQL timestamp in GMT
313
+					$datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
314
+				}
315
+				if (! $datetime_obj instanceof \DateTime) {
316
+					// so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
317
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
318
+				}
319
+				$original_value = $datetime_obj;
320
+			}
321
+			if ($original_value instanceof \DateTime) {
322
+				$new_value = $original_value->format('Y-m-d H:i:s');
323
+			} elseif (is_int($original_value) || is_float($original_value)) {
324
+				$new_value = date('Y-m-d H:i:s', $original_value);
325
+			} elseif ($original_value === null || $original_value === '') {
326
+				$new_value = null;
327
+			} else {
328
+				// so it's not a datetime object, unix timestamp (as string or int),
329
+				// MySQL timestamp, or even a string in the field object's format. So no idea what it is
330
+				throw new \EE_Error(
331
+					sprintf(
332
+						esc_html__(
333
+						// @codingStandardsIgnoreStart
334
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
335
+							// @codingStandardsIgnoreEnd
336
+							'event_espresso'
337
+						),
338
+						$original_value,
339
+						$field_obj->get_name(),
340
+						$field_obj->get_model_name(),
341
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
342
+					)
343
+				);
344
+			}
345
+			if ($new_value !== null) {
346
+				$new_value = mysql_to_rfc3339($new_value);
347
+			}
348
+		} else {
349
+			$new_value = $original_value;
350
+		}
351
+		// are we about to send an object? just don't. We have no good way to represent it in JSON.
352
+		// can't just check using is_object() because that missed PHP incomplete objects
353
+		if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
354
+			$new_value = array(
355
+				'error_code'    => 'php_object_not_return',
356
+				'error_message' => esc_html__(
357
+					'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
358
+					'event_espresso'
359
+				),
360
+			);
361
+		}
362
+		return apply_filters(
363
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
364
+			$new_value,
365
+			$field_obj,
366
+			$original_value,
367
+			$requested_version
368
+		);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Prepares condition-query-parameters (like what's in where and having) from
374
+	 * the format expected in the API to use in the models
375
+	 *
376
+	 * @param array $inputted_query_params_of_this_type
377
+	 * @param EEM_Base $model
378
+	 * @param string $requested_version
379
+	 * @param boolean $writing whether this data will be written to the DB, or if we're just building a query.
380
+	 *                          If we're writing to the DB, we don't expect any operators, or any logic query
381
+	 *                          parameters, and we also won't accept serialized data unless the current user has
382
+	 *                          unfiltered_html.
383
+	 * @return array
384
+	 * @throws DomainException
385
+	 * @throws EE_Error
386
+	 * @throws RestException
387
+	 * @throws InvalidDataTypeException
388
+	 * @throws InvalidInterfaceException
389
+	 * @throws InvalidArgumentException
390
+	 */
391
+	public static function prepareConditionsQueryParamsForModels(
392
+		$inputted_query_params_of_this_type,
393
+		EEM_Base $model,
394
+		$requested_version,
395
+		$writing = false
396
+	) {
397
+		$query_param_for_models = array();
398
+		$context = new RestIncomingQueryParamContext($model, $requested_version, $writing);
399
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
400
+			$query_param_meta = new RestIncomingQueryParamMetadata($query_param_key, $query_param_value, $context);
401
+			if ($query_param_meta->getField() instanceof EE_Model_Field_Base) {
402
+				$translated_value = $query_param_meta->determineConditionsQueryParameterValue();
403
+				if ((isset($query_param_for_models[ $query_param_meta->getQueryParamKey() ]) && $query_param_meta->isGmtField())
404
+					|| $translated_value === null
405
+				) {
406
+					// they have already provided a non-gmt field, ignore the gmt one. That's what WP core
407
+					// currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
408
+					// OR we couldn't create a translated value from their input
409
+					continue;
410
+				}
411
+				$query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $translated_value;
412
+			} else {
413
+				$nested_query_params = $query_param_meta->determineNestedConditionQueryParameters();
414
+				if ($nested_query_params) {
415
+					$query_param_for_models[ $query_param_meta->getQueryParamKey() ] = $nested_query_params;
416
+				}
417
+			}
418
+		}
419
+		return $query_param_for_models;
420
+	}
421
+
422
+	/**
423
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
424
+	 * gmt date field name
425
+	 *
426
+	 * @param string $field_name
427
+	 * @return boolean
428
+	 */
429
+	public static function isGmtDateFieldName($field_name)
430
+	{
431
+		return substr(
432
+			ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
433
+			-4,
434
+			4
435
+		) === '_gmt';
436
+	}
437
+
438
+
439
+	/**
440
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
441
+	 *
442
+	 * @param string $field_name
443
+	 * @return string
444
+	 */
445
+	public static function removeGmtFromFieldName($field_name)
446
+	{
447
+		if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
448
+			return $field_name;
449
+		}
450
+		$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
451
+			$field_name
452
+		);
453
+		$query_param_sans_gmt_and_sans_stars = substr(
454
+			$query_param_sans_stars,
455
+			0,
456
+			strrpos(
457
+				$field_name,
458
+				'_gmt'
459
+			)
460
+		);
461
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
462
+	}
463
+
464
+
465
+	/**
466
+	 * Takes a field name from the REST API and prepares it for the model querying
467
+	 *
468
+	 * @param string $field_name
469
+	 * @return string
470
+	 */
471
+	public static function prepareFieldNameFromJson($field_name)
472
+	{
473
+		if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
474
+			return ModelDataTranslator::removeGmtFromFieldName($field_name);
475
+		}
476
+		return $field_name;
477
+	}
478
+
479
+
480
+	/**
481
+	 * Takes array of field names from REST API and prepares for models
482
+	 *
483
+	 * @param array $field_names
484
+	 * @return array of field names (possibly include model prefixes)
485
+	 */
486
+	public static function prepareFieldNamesFromJson(array $field_names)
487
+	{
488
+		$new_array = array();
489
+		foreach ($field_names as $key => $field_name) {
490
+			$new_array[ $key ] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
491
+		}
492
+		return $new_array;
493
+	}
494
+
495
+
496
+	/**
497
+	 * Takes array where array keys are field names (possibly with model path prefixes)
498
+	 * from the REST API and prepares them for model querying
499
+	 *
500
+	 * @param array $field_names_as_keys
501
+	 * @return array
502
+	 */
503
+	public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
504
+	{
505
+		$new_array = array();
506
+		foreach ($field_names_as_keys as $field_name => $value) {
507
+			$new_array[ ModelDataTranslator::prepareFieldNameFromJson($field_name) ] = $value;
508
+		}
509
+		return $new_array;
510
+	}
511
+
512
+
513
+	/**
514
+	 * Prepares an array of model query params for use in the REST API
515
+	 *
516
+	 * @param array    $model_query_params
517
+	 * @param EEM_Base $model
518
+	 * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
519
+	 *                                     REST API
520
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
521
+	 * @throws EE_Error
522
+	 */
523
+	public static function prepareQueryParamsForRestApi(
524
+		array $model_query_params,
525
+		EEM_Base $model,
526
+		$requested_version = null
527
+	) {
528
+		if ($requested_version === null) {
529
+			$requested_version = EED_Core_Rest_Api::latest_rest_api_version();
530
+		}
531
+		$rest_query_params = $model_query_params;
532
+		if (isset($model_query_params[0])) {
533
+			$rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
534
+				$model_query_params[0],
535
+				$model,
536
+				$requested_version
537
+			);
538
+			unset($rest_query_params[0]);
539
+		}
540
+		if (isset($model_query_params['having'])) {
541
+			$rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
542
+				$model_query_params['having'],
543
+				$model,
544
+				$requested_version
545
+			);
546
+		}
547
+		return apply_filters(
548
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
549
+			$rest_query_params,
550
+			$model_query_params,
551
+			$model,
552
+			$requested_version
553
+		);
554
+	}
555
+
556
+
557
+	/**
558
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
559
+	 *
560
+	 * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
561
+	 *                                                      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
562
+	 * @param EEM_Base $model
563
+	 * @param string   $requested_version                   eg "4.8.36"
564
+	 * @return array ready for use in the rest api query params
565
+	 * @throws EE_Error
566
+	 * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
567
+	 *                                                      (which would be really unusual)
568
+	 */
569
+	public static function prepareConditionsQueryParamsForRestApi(
570
+		$inputted_query_params_of_this_type,
571
+		EEM_Base $model,
572
+		$requested_version
573
+	) {
574
+		$query_param_for_models = array();
575
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
576
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
577
+				ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
578
+				$model
579
+			);
580
+			if ($field instanceof EE_Model_Field_Base) {
581
+				// did they specify an operator?
582
+				if (is_array($query_param_value)) {
583
+					$op = $query_param_value[0];
584
+					$translated_value = array($op);
585
+					if (isset($query_param_value[1])) {
586
+						$value = $query_param_value[1];
587
+						$translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
588
+							$field,
589
+							$value,
590
+							$requested_version
591
+						);
592
+					}
593
+				} else {
594
+					$translated_value = ModelDataTranslator::prepareFieldValueForJson(
595
+						$field,
596
+						$query_param_value,
597
+						$requested_version
598
+					);
599
+				}
600
+				$query_param_for_models[ $query_param_key ] = $translated_value;
601
+			} else {
602
+				// so it's not for a field, assume it's a logic query param key
603
+				$query_param_for_models[ $query_param_key ] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
604
+					$query_param_value,
605
+					$model,
606
+					$requested_version
607
+				);
608
+			}
609
+		}
610
+		return $query_param_for_models;
611
+	}
612
+
613
+
614
+	/**
615
+	 * @param $condition_query_param_key
616
+	 * @return string
617
+	 */
618
+	public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
619
+	{
620
+		$pos_of_star = strpos($condition_query_param_key, '*');
621
+		if ($pos_of_star === false) {
622
+			return $condition_query_param_key;
623
+		} else {
624
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
625
+			return $condition_query_param_sans_star;
626
+		}
627
+	}
628
+
629
+
630
+	/**
631
+	 * Takes the input parameter and finds the model field that it indicates.
632
+	 *
633
+	 * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
634
+	 * @param EEM_Base $model
635
+	 * @return EE_Model_Field_Base
636
+	 * @throws EE_Error
637
+	 */
638
+	public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
639
+	{
640
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
641
+		// which will help us find the database table and column
642
+		$query_param_parts = explode('.', $query_param_name);
643
+		if (empty($query_param_parts)) {
644
+			throw new EE_Error(
645
+				sprintf(
646
+					__(
647
+						'_extract_column_name is empty when trying to extract column and table name from %s',
648
+						'event_espresso'
649
+					),
650
+					$query_param_name
651
+				)
652
+			);
653
+		}
654
+		$number_of_parts = count($query_param_parts);
655
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
656
+		if ($number_of_parts === 1) {
657
+			$field_name = $last_query_param_part;
658
+		} else {// $number_of_parts >= 2
659
+			// the last part is the column name, and there are only 2parts. therefore...
660
+			$field_name = $last_query_param_part;
661
+			$model = \EE_Registry::instance()->load_model($query_param_parts[ $number_of_parts - 2 ]);
662
+		}
663
+		try {
664
+			return $model->field_settings_for($field_name, false);
665
+		} catch (EE_Error $e) {
666
+			return null;
667
+		}
668
+	}
669
+
670
+
671
+	/**
672
+	 * Returns true if $data can be easily represented in JSON.
673
+	 * Basically, objects and resources can't be represented in JSON easily.
674
+	 *
675
+	 * @param mixed $data
676
+	 * @return bool
677
+	 */
678
+	protected static function isRepresentableInJson($data)
679
+	{
680
+		return is_scalar($data)
681
+			   || is_array($data)
682
+			   || is_null($data);
683
+	}
684 684
 }
Please login to merge, or discard this patch.