Completed
Branch master (16095c)
by
unknown
09:17 queued 04:49
created
core/services/container/DependencyInjector.php 2 patches
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -71,12 +71,12 @@  discard block
 block discarded – undo
71 71
     public function getReflectionClass($class_name)
72 72
     {
73 73
         if (
74
-            ! isset($this->reflectors[ $class_name ])
75
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
74
+            ! isset($this->reflectors[$class_name])
75
+            || ! $this->reflectors[$class_name] instanceof ReflectionClass
76 76
         ) {
77
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
77
+            $this->reflectors[$class_name] = new ReflectionClass($class_name);
78 78
         }
79
-        return $this->reflectors[ $class_name ];
79
+        return $this->reflectors[$class_name];
80 80
     }
81 81
 
82 82
 
@@ -91,12 +91,12 @@  discard block
 block discarded – undo
91 91
     protected function getConstructor(ReflectionClass $reflector)
92 92
     {
93 93
         if (
94
-            ! isset($this->constructors[ $reflector->getName() ])
95
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
94
+            ! isset($this->constructors[$reflector->getName()])
95
+            || ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
96 96
         ) {
97
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
97
+            $this->constructors[$reflector->getName()] = $reflector->getConstructor();
98 98
         }
99
-        return $this->constructors[ $reflector->getName() ];
99
+        return $this->constructors[$reflector->getName()];
100 100
     }
101 101
 
102 102
 
@@ -110,10 +110,10 @@  discard block
 block discarded – undo
110 110
      */
111 111
     protected function getParameters(ReflectionMethod $constructor)
112 112
     {
113
-        if (! isset($this->parameters[ $constructor->class ])) {
114
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
113
+        if ( ! isset($this->parameters[$constructor->class])) {
114
+            $this->parameters[$constructor->class] = $constructor->getParameters();
115 115
         }
116
-        return $this->parameters[ $constructor->class ];
116
+        return $this->parameters[$constructor->class];
117 117
     }
118 118
 
119 119
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
         // let's examine the constructor
149 149
         $constructor = $this->getConstructor($reflector);
150 150
         // whu? huh? nothing?
151
-        if (! $constructor) {
151
+        if ( ! $constructor) {
152 152
             return $arguments;
153 153
         }
154 154
         // get constructor parameters
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
         $argument_keys = array_keys($arguments);
162 162
         // now loop thru all of the constructors expected parameters
163 163
         foreach ($params as $index => $param) {
164
-            if (! $param instanceof ReflectionParameter) {
164
+            if ( ! $param instanceof ReflectionParameter) {
165 165
                 continue;
166 166
             }
167 167
             // is this a dependency for a specific class ?
@@ -169,41 +169,41 @@  discard block
 block discarded – undo
169 169
             $param_name = $param->getName() ? $param->getName() : '';
170 170
             if (
171 171
 // param is not a class but is specified in the list of ingredients for this Recipe
172
-                is_string($param_name) && isset($ingredients[ $param_name ])
172
+                is_string($param_name) && isset($ingredients[$param_name])
173 173
             ) {
174 174
                 // attempt to inject the dependency
175
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
175
+                $resolved_parameters[$index] = $ingredients[$param_name];
176 176
             } elseif (
177 177
 // param is specified in the list of ingredients for this Recipe
178
-                isset($ingredients[ $param_class ])
178
+                isset($ingredients[$param_class])
179 179
             ) { // attempt to inject the dependency
180
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
180
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $ingredients[$param_class]);
181 181
             } elseif (
182 182
 // param is not even a class
183 183
                 empty($param_class)
184 184
                 // and something already exists in the incoming arguments for this param
185
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
185
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
186 186
             ) {
187 187
                 // add parameter from incoming arguments
188
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
188
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
189 189
             } elseif (
190 190
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
191 191
                 ! empty($param_class)
192
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
192
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
193
+                && $arguments[$argument_keys[$index]] instanceof $param_class
194 194
             ) {
195 195
                 // add parameter from incoming arguments
196
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
196
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
197 197
             } elseif (
198 198
 // parameter is type hinted as a class, and should be injected
199 199
                 ! empty($param_class)
200 200
             ) {
201 201
                 // attempt to inject the dependency
202
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
202
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $param_class);
203 203
             } elseif ($param->isOptional()) {
204
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
204
+                $resolved_parameters[$index] = $param->getDefaultValue();
205 205
             } else {
206
-                $resolved_parameters[ $index ] = null;
206
+                $resolved_parameters[$index] = null;
207 207
             }
208 208
         }
209 209
         return $resolved_parameters;
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     private function injectDependency(ReflectionClass $reflector, $param_class)
220 220
     {
221 221
         $dependency = $this->coffee_pot->brew($param_class);
222
-        if (! $dependency instanceof $param_class) {
222
+        if ( ! $dependency instanceof $param_class) {
223 223
             throw new UnexpectedValueException(
224 224
                 sprintf(
225 225
                     esc_html__(
Please login to merge, or discard this patch.
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -20,216 +20,216 @@
 block discarded – undo
20 20
  */
21 21
 class DependencyInjector implements InjectorInterface
22 22
 {
23
-    /**
24
-     * @var CoffeePotInterface $coffee_pot
25
-     */
26
-    private $coffee_pot;
27
-
28
-    /**
29
-     * @var EEH_Array $array_helper
30
-     */
31
-    private $array_helper;
32
-
33
-    /**
34
-     * @var ReflectionClass[] $reflectors
35
-     */
36
-    private $reflectors;
37
-
38
-    /**
39
-     * @var ReflectionMethod[] $constructors
40
-     */
41
-    private $constructors;
42
-
43
-    /**
44
-     * @var ReflectionParameter[] $parameters
45
-     */
46
-    private $parameters;
47
-
48
-
49
-    /**
50
-     * DependencyInjector constructor
51
-     *
52
-     * @param CoffeePotInterface $coffee_pot
53
-     * @param EEH_Array          $array_helper
54
-     */
55
-    public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
56
-    {
57
-        $this->coffee_pot = $coffee_pot;
58
-        $this->array_helper = $array_helper;
59
-    }
60
-
61
-
62
-    /**
63
-     * getReflectionClass
64
-     * checks if a ReflectionClass object has already been generated for a class
65
-     * and returns that instead of creating a new one
66
-     *
67
-     * @param string $class_name
68
-     * @return ReflectionClass
69
-     */
70
-    public function getReflectionClass($class_name)
71
-    {
72
-        if (
73
-            ! isset($this->reflectors[ $class_name ])
74
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
75
-        ) {
76
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
77
-        }
78
-        return $this->reflectors[ $class_name ];
79
-    }
80
-
81
-
82
-    /**
83
-     * getConstructor
84
-     * checks if a ReflectionMethod object has already been generated for the class constructor
85
-     * and returns that instead of creating a new one
86
-     *
87
-     * @param ReflectionClass $reflector
88
-     * @return ReflectionMethod
89
-     */
90
-    protected function getConstructor(ReflectionClass $reflector)
91
-    {
92
-        if (
93
-            ! isset($this->constructors[ $reflector->getName() ])
94
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
95
-        ) {
96
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
97
-        }
98
-        return $this->constructors[ $reflector->getName() ];
99
-    }
100
-
101
-
102
-    /**
103
-     * getParameters
104
-     * checks if an array of ReflectionParameter objects has already been generated for the class constructor
105
-     * and returns that instead of creating a new one
106
-     *
107
-     * @param ReflectionMethod $constructor
108
-     * @return ReflectionParameter[]
109
-     */
110
-    protected function getParameters(ReflectionMethod $constructor)
111
-    {
112
-        if (! isset($this->parameters[ $constructor->class ])) {
113
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
114
-        }
115
-        return $this->parameters[ $constructor->class ];
116
-    }
117
-
118
-
119
-    /**
120
-     * resolveDependencies
121
-     * examines the constructor for the requested class to determine
122
-     * if any dependencies exist, and if they can be injected.
123
-     * If so, then those classes will be added to the array of arguments passed to the constructor
124
-     * PLZ NOTE: this is achieved by type hinting the constructor params
125
-     * For example:
126
-     *        if attempting to load a class "Foo" with the following constructor:
127
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
128
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
129
-     *        but only IF they are NOT already present in the incoming arguments array,
130
-     *        and the correct classes can be loaded
131
-     *
132
-     * @param RecipeInterface $recipe
133
-     * @param ReflectionClass $reflector
134
-     * @param array           $arguments
135
-     * @return array
136
-     * @throws UnexpectedValueException
137
-     */
138
-    public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
139
-    {
140
-        // if arguments array is numerically and sequentially indexed, then we want it to remain as is,
141
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
142
-        $arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
143
-            ? $arguments
144
-            : array($arguments);
145
-        $resolved_parameters = array();
146
-        // let's examine the constructor
147
-        // let's examine the constructor
148
-        $constructor = $this->getConstructor($reflector);
149
-        // whu? huh? nothing?
150
-        if (! $constructor) {
151
-            return $arguments;
152
-        }
153
-        // get constructor parameters
154
-        $params = $this->getParameters($constructor);
155
-        if (empty($params)) {
156
-            return $resolved_parameters;
157
-        }
158
-        $ingredients = $recipe->ingredients();
159
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
160
-        $argument_keys = array_keys($arguments);
161
-        // now loop thru all of the constructors expected parameters
162
-        foreach ($params as $index => $param) {
163
-            if (! $param instanceof ReflectionParameter) {
164
-                continue;
165
-            }
166
-            // is this a dependency for a specific class ?
167
-            $param_class = $param->getClass() ? $param->getClass()->name : '';
168
-            $param_name = $param->getName() ? $param->getName() : '';
169
-            if (
23
+	/**
24
+	 * @var CoffeePotInterface $coffee_pot
25
+	 */
26
+	private $coffee_pot;
27
+
28
+	/**
29
+	 * @var EEH_Array $array_helper
30
+	 */
31
+	private $array_helper;
32
+
33
+	/**
34
+	 * @var ReflectionClass[] $reflectors
35
+	 */
36
+	private $reflectors;
37
+
38
+	/**
39
+	 * @var ReflectionMethod[] $constructors
40
+	 */
41
+	private $constructors;
42
+
43
+	/**
44
+	 * @var ReflectionParameter[] $parameters
45
+	 */
46
+	private $parameters;
47
+
48
+
49
+	/**
50
+	 * DependencyInjector constructor
51
+	 *
52
+	 * @param CoffeePotInterface $coffee_pot
53
+	 * @param EEH_Array          $array_helper
54
+	 */
55
+	public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
56
+	{
57
+		$this->coffee_pot = $coffee_pot;
58
+		$this->array_helper = $array_helper;
59
+	}
60
+
61
+
62
+	/**
63
+	 * getReflectionClass
64
+	 * checks if a ReflectionClass object has already been generated for a class
65
+	 * and returns that instead of creating a new one
66
+	 *
67
+	 * @param string $class_name
68
+	 * @return ReflectionClass
69
+	 */
70
+	public function getReflectionClass($class_name)
71
+	{
72
+		if (
73
+			! isset($this->reflectors[ $class_name ])
74
+			|| ! $this->reflectors[ $class_name ] instanceof ReflectionClass
75
+		) {
76
+			$this->reflectors[ $class_name ] = new ReflectionClass($class_name);
77
+		}
78
+		return $this->reflectors[ $class_name ];
79
+	}
80
+
81
+
82
+	/**
83
+	 * getConstructor
84
+	 * checks if a ReflectionMethod object has already been generated for the class constructor
85
+	 * and returns that instead of creating a new one
86
+	 *
87
+	 * @param ReflectionClass $reflector
88
+	 * @return ReflectionMethod
89
+	 */
90
+	protected function getConstructor(ReflectionClass $reflector)
91
+	{
92
+		if (
93
+			! isset($this->constructors[ $reflector->getName() ])
94
+			|| ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
95
+		) {
96
+			$this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
97
+		}
98
+		return $this->constructors[ $reflector->getName() ];
99
+	}
100
+
101
+
102
+	/**
103
+	 * getParameters
104
+	 * checks if an array of ReflectionParameter objects has already been generated for the class constructor
105
+	 * and returns that instead of creating a new one
106
+	 *
107
+	 * @param ReflectionMethod $constructor
108
+	 * @return ReflectionParameter[]
109
+	 */
110
+	protected function getParameters(ReflectionMethod $constructor)
111
+	{
112
+		if (! isset($this->parameters[ $constructor->class ])) {
113
+			$this->parameters[ $constructor->class ] = $constructor->getParameters();
114
+		}
115
+		return $this->parameters[ $constructor->class ];
116
+	}
117
+
118
+
119
+	/**
120
+	 * resolveDependencies
121
+	 * examines the constructor for the requested class to determine
122
+	 * if any dependencies exist, and if they can be injected.
123
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
124
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
125
+	 * For example:
126
+	 *        if attempting to load a class "Foo" with the following constructor:
127
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
128
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
129
+	 *        but only IF they are NOT already present in the incoming arguments array,
130
+	 *        and the correct classes can be loaded
131
+	 *
132
+	 * @param RecipeInterface $recipe
133
+	 * @param ReflectionClass $reflector
134
+	 * @param array           $arguments
135
+	 * @return array
136
+	 * @throws UnexpectedValueException
137
+	 */
138
+	public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
139
+	{
140
+		// if arguments array is numerically and sequentially indexed, then we want it to remain as is,
141
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
142
+		$arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
143
+			? $arguments
144
+			: array($arguments);
145
+		$resolved_parameters = array();
146
+		// let's examine the constructor
147
+		// let's examine the constructor
148
+		$constructor = $this->getConstructor($reflector);
149
+		// whu? huh? nothing?
150
+		if (! $constructor) {
151
+			return $arguments;
152
+		}
153
+		// get constructor parameters
154
+		$params = $this->getParameters($constructor);
155
+		if (empty($params)) {
156
+			return $resolved_parameters;
157
+		}
158
+		$ingredients = $recipe->ingredients();
159
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
160
+		$argument_keys = array_keys($arguments);
161
+		// now loop thru all of the constructors expected parameters
162
+		foreach ($params as $index => $param) {
163
+			if (! $param instanceof ReflectionParameter) {
164
+				continue;
165
+			}
166
+			// is this a dependency for a specific class ?
167
+			$param_class = $param->getClass() ? $param->getClass()->name : '';
168
+			$param_name = $param->getName() ? $param->getName() : '';
169
+			if (
170 170
 // param is not a class but is specified in the list of ingredients for this Recipe
171
-                is_string($param_name) && isset($ingredients[ $param_name ])
172
-            ) {
173
-                // attempt to inject the dependency
174
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
175
-            } elseif (
171
+				is_string($param_name) && isset($ingredients[ $param_name ])
172
+			) {
173
+				// attempt to inject the dependency
174
+				$resolved_parameters[ $index ] = $ingredients[ $param_name ];
175
+			} elseif (
176 176
 // param is specified in the list of ingredients for this Recipe
177
-                isset($ingredients[ $param_class ])
178
-            ) { // attempt to inject the dependency
179
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
180
-            } elseif (
177
+				isset($ingredients[ $param_class ])
178
+			) { // attempt to inject the dependency
179
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
180
+			} elseif (
181 181
 // param is not even a class
182
-                empty($param_class)
183
-                // and something already exists in the incoming arguments for this param
184
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
185
-            ) {
186
-                // add parameter from incoming arguments
187
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
188
-            } elseif (
182
+				empty($param_class)
183
+				// and something already exists in the incoming arguments for this param
184
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
185
+			) {
186
+				// add parameter from incoming arguments
187
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
188
+			} elseif (
189 189
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
190
-                ! empty($param_class)
191
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
192
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
193
-            ) {
194
-                // add parameter from incoming arguments
195
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
196
-            } elseif (
190
+				! empty($param_class)
191
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
192
+				&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
193
+			) {
194
+				// add parameter from incoming arguments
195
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
196
+			} elseif (
197 197
 // parameter is type hinted as a class, and should be injected
198
-                ! empty($param_class)
199
-            ) {
200
-                // attempt to inject the dependency
201
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
202
-            } elseif ($param->isOptional()) {
203
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
204
-            } else {
205
-                $resolved_parameters[ $index ] = null;
206
-            }
207
-        }
208
-        return $resolved_parameters;
209
-    }
210
-
211
-
212
-    /**
213
-     * @param ReflectionClass $reflector
214
-     * @param string          $param_class
215
-     * @return mixed
216
-     * @throws UnexpectedValueException
217
-     */
218
-    private function injectDependency(ReflectionClass $reflector, $param_class)
219
-    {
220
-        $dependency = $this->coffee_pot->brew($param_class);
221
-        if (! $dependency instanceof $param_class) {
222
-            throw new UnexpectedValueException(
223
-                sprintf(
224
-                    esc_html__(
225
-                        'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
226
-                        'event_espresso'
227
-                    ),
228
-                    $param_class,
229
-                    $reflector->getName()
230
-                )
231
-            );
232
-        }
233
-        return $dependency;
234
-    }
198
+				! empty($param_class)
199
+			) {
200
+				// attempt to inject the dependency
201
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
202
+			} elseif ($param->isOptional()) {
203
+				$resolved_parameters[ $index ] = $param->getDefaultValue();
204
+			} else {
205
+				$resolved_parameters[ $index ] = null;
206
+			}
207
+		}
208
+		return $resolved_parameters;
209
+	}
210
+
211
+
212
+	/**
213
+	 * @param ReflectionClass $reflector
214
+	 * @param string          $param_class
215
+	 * @return mixed
216
+	 * @throws UnexpectedValueException
217
+	 */
218
+	private function injectDependency(ReflectionClass $reflector, $param_class)
219
+	{
220
+		$dependency = $this->coffee_pot->brew($param_class);
221
+		if (! $dependency instanceof $param_class) {
222
+			throw new UnexpectedValueException(
223
+				sprintf(
224
+					esc_html__(
225
+						'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
226
+						'event_espresso'
227
+					),
228
+					$param_class,
229
+					$reflector->getName()
230
+				)
231
+			);
232
+		}
233
+		return $dependency;
234
+	}
235 235
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
             $date_or_time,
534 534
             $echo
535 535
         );
536
-        if (! $echo) {
536
+        if ( ! $echo) {
537 537
             return $dtt;
538 538
         }
539 539
         return '';
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
             ' ',
636 636
             $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637 637
         );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
+        return $start !== $end ? $start.$conjunction.$end : $start;
639 639
     }
640 640
 
641 641
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
             ' ',
744 744
             $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745 745
         );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
+        return $start !== $end ? $start.$conjunction.$end : $start;
747 747
     }
748 748
 
749 749
 
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     ) {
789 789
         $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790 790
         $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
791
+        $full_format = $dt_format.$separator.$tm_format;
792 792
         // the range output depends on various conditions
793 793
         switch (true) {
794 794
             // start date timestamp and end date timestamp are the same.
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
         // tickets remaining available for purchase
1030 1030
         // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031 1031
         $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1032
+        if ( ! $consider_tickets) {
1033 1033
             return $dtt_remaining;
1034 1034
         }
1035 1035
         $tickets_remaining = $this->tickets_remaining();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
     {
1054 1054
         $sum = 0;
1055 1055
         $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1056
+        if ( ! empty($tickets)) {
1057 1057
             foreach ($tickets as $ticket) {
1058 1058
                 if ($ticket instanceof EE_Ticket) {
1059 1059
                     // get the actual amount of tickets that can be sold
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
     {
1205 1205
         if ($use_dtt_name) {
1206 1206
             $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1207
+            if ( ! empty($dtt_name)) {
1208 1208
                 return $dtt_name;
1209 1209
             }
1210 1210
         }
@@ -1212,14 +1212,14 @@  discard block
 block discarded – undo
1212 1212
         if (
1213 1213
             date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214 1214
         ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+            $display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
1216 1216
             // next condition is if its the same month but different day
1217 1217
         } else {
1218 1218
             if (
1219 1219
                 date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220 1220
                 && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221 1221
             ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+                $display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
1223 1223
             } else {
1224 1224
                 $display_date = $this->start_date('F j\, Y')
1225 1225
                                 . ' @ '
Please login to merge, or discard this patch.
Indentation   +1552 added lines, -1552 removed lines patch added patch discarded remove patch
@@ -12,1560 +12,1560 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15
-    /**
16
-     * constant used by get_active_status, indicates datetime has no more available spaces
17
-     */
18
-    const sold_out = 'DTS';
19
-
20
-    /**
21
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
-     */
23
-    const active = 'DTA';
24
-
25
-    /**
26
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
-     * expired
28
-     */
29
-    const upcoming = 'DTU';
30
-
31
-    /**
32
-     * Datetime is postponed
33
-     */
34
-    const postponed = 'DTP';
35
-
36
-    /**
37
-     * Datetime is cancelled
38
-     */
39
-    const cancelled = 'DTC';
40
-
41
-    /**
42
-     * constant used by get_active_status, indicates datetime has expired (event is over)
43
-     */
44
-    const expired = 'DTE';
45
-
46
-    /**
47
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
-     */
49
-    const inactive = 'DTI';
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values    incoming values
54
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
-     *                                  and the second value is the time format
57
-     * @return EE_Datetime
58
-     * @throws ReflectionException
59
-     * @throws InvalidArgumentException
60
-     * @throws InvalidInterfaceException
61
-     * @throws InvalidDataTypeException
62
-     * @throws EE_Error
63
-     */
64
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
-    {
66
-        $has_object = parent::_check_for_object(
67
-            $props_n_values,
68
-            __CLASS__,
69
-            $timezone,
70
-            $date_formats
71
-        );
72
-        return $has_object
73
-            ? $has_object
74
-            : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Datetime
83
-     * @throws ReflectionException
84
-     * @throws InvalidArgumentException
85
-     * @throws InvalidInterfaceException
86
-     * @throws InvalidDataTypeException
87
-     * @throws EE_Error
88
-     */
89
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
-    {
91
-        return new self($props_n_values, true, $timezone);
92
-    }
93
-
94
-
95
-    /**
96
-     * @param $name
97
-     * @throws ReflectionException
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidInterfaceException
100
-     * @throws InvalidDataTypeException
101
-     * @throws EE_Error
102
-     */
103
-    public function set_name($name)
104
-    {
105
-        $this->set('DTT_name', $name);
106
-    }
107
-
108
-
109
-    /**
110
-     * @param $description
111
-     * @throws ReflectionException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidInterfaceException
114
-     * @throws InvalidDataTypeException
115
-     * @throws EE_Error
116
-     */
117
-    public function set_description($description)
118
-    {
119
-        $this->set('DTT_description', $description);
120
-    }
121
-
122
-
123
-    /**
124
-     * Set event start date
125
-     * set the start date for an event
126
-     *
127
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
-     * @throws ReflectionException
129
-     * @throws InvalidArgumentException
130
-     * @throws InvalidInterfaceException
131
-     * @throws InvalidDataTypeException
132
-     * @throws EE_Error
133
-     */
134
-    public function set_start_date($date)
135
-    {
136
-        $this->_set_date_for($date, 'DTT_EVT_start');
137
-    }
138
-
139
-
140
-    /**
141
-     * Set event start time
142
-     * set the start time for an event
143
-     *
144
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
-     * @throws ReflectionException
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidInterfaceException
148
-     * @throws InvalidDataTypeException
149
-     * @throws EE_Error
150
-     */
151
-    public function set_start_time($time)
152
-    {
153
-        $this->_set_time_for($time, 'DTT_EVT_start');
154
-    }
155
-
156
-
157
-    /**
158
-     * Set event end date
159
-     * set the end date for an event
160
-     *
161
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
-     * @throws ReflectionException
163
-     * @throws InvalidArgumentException
164
-     * @throws InvalidInterfaceException
165
-     * @throws InvalidDataTypeException
166
-     * @throws EE_Error
167
-     */
168
-    public function set_end_date($date)
169
-    {
170
-        $this->_set_date_for($date, 'DTT_EVT_end');
171
-    }
172
-
173
-
174
-    /**
175
-     * Set event end time
176
-     * set the end time for an event
177
-     *
178
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
-     * @throws ReflectionException
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidInterfaceException
182
-     * @throws InvalidDataTypeException
183
-     * @throws EE_Error
184
-     */
185
-    public function set_end_time($time)
186
-    {
187
-        $this->_set_time_for($time, 'DTT_EVT_end');
188
-    }
189
-
190
-
191
-    /**
192
-     * Set registration limit
193
-     * set the maximum number of attendees that can be registered for this datetime slot
194
-     *
195
-     * @param int|float $reg_limit
196
-     * @throws ReflectionException
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidInterfaceException
199
-     * @throws InvalidDataTypeException
200
-     * @throws EE_Error
201
-     */
202
-    public function set_reg_limit($reg_limit)
203
-    {
204
-        $this->set('DTT_reg_limit', $reg_limit);
205
-    }
206
-
207
-
208
-    /**
209
-     * get the number of tickets sold for this datetime slot
210
-     *
211
-     * @return mixed int on success, FALSE on fail
212
-     * @throws ReflectionException
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidInterfaceException
215
-     * @throws InvalidDataTypeException
216
-     * @throws EE_Error
217
-     */
218
-    public function sold()
219
-    {
220
-        return $this->get_raw('DTT_sold');
221
-    }
222
-
223
-
224
-    /**
225
-     * @param int $sold
226
-     * @throws ReflectionException
227
-     * @throws InvalidArgumentException
228
-     * @throws InvalidInterfaceException
229
-     * @throws InvalidDataTypeException
230
-     * @throws EE_Error
231
-     */
232
-    public function set_sold($sold)
233
-    {
234
-        // sold can not go below zero
235
-        $sold = max(0, $sold);
236
-        $this->set('DTT_sold', $sold);
237
-    }
238
-
239
-
240
-    /**
241
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
-     *
244
-     * @param int $qty
245
-     * @param boolean $also_decrease_reserved
246
-     * @return boolean indicating success
247
-     * @throws ReflectionException
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidInterfaceException
250
-     * @throws InvalidDataTypeException
251
-     * @throws EE_Error
252
-     */
253
-    public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
-    {
255
-        $qty = absint($qty);
256
-        if ($also_decrease_reserved) {
257
-            $success = $this->adjustNumericFieldsInDb(
258
-                [
259
-                    'DTT_reserved' => $qty * -1,
260
-                    'DTT_sold' => $qty
261
-                ]
262
-            );
263
-        } else {
264
-            $success = $this->adjustNumericFieldsInDb(
265
-                [
266
-                    'DTT_sold' => $qty
267
-                ]
268
-            );
269
-        }
270
-
271
-        do_action(
272
-            'AHEE__EE_Datetime__increase_sold',
273
-            $this,
274
-            $qty,
275
-            $this->sold(),
276
-            $success
277
-        );
278
-        return $success;
279
-    }
280
-
281
-
282
-    /**
283
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
-     * to save afterwards.)
285
-     *
286
-     * @param int $qty
287
-     * @return boolean indicating success
288
-     * @throws ReflectionException
289
-     * @throws InvalidArgumentException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidDataTypeException
292
-     * @throws EE_Error
293
-     */
294
-    public function decreaseSold(int $qty = 1): bool
295
-    {
296
-        $qty = absint($qty);
297
-        $success = $this->adjustNumericFieldsInDb(
298
-            [
299
-                'DTT_sold' => $qty * -1
300
-            ]
301
-        );
302
-        do_action(
303
-            'AHEE__EE_Datetime__decrease_sold',
304
-            $this,
305
-            $qty,
306
-            $this->sold(),
307
-            $success
308
-        );
309
-        return $success;
310
-    }
311
-
312
-
313
-    /**
314
-     * Gets qty of reserved tickets for this datetime
315
-     *
316
-     * @return int
317
-     * @throws ReflectionException
318
-     * @throws InvalidArgumentException
319
-     * @throws InvalidInterfaceException
320
-     * @throws InvalidDataTypeException
321
-     * @throws EE_Error
322
-     */
323
-    public function reserved(): int
324
-    {
325
-        return $this->get_raw('DTT_reserved');
326
-    }
327
-
328
-
329
-    /**
330
-     * Sets qty of reserved tickets for this datetime
331
-     *
332
-     * @param int $reserved
333
-     * @throws ReflectionException
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidDataTypeException
337
-     * @throws EE_Error
338
-     */
339
-    public function set_reserved(int $reserved)
340
-    {
341
-        // reserved can not go below zero
342
-        $reserved = max(0, $reserved);
343
-        $this->set('DTT_reserved', $reserved);
344
-    }
345
-
346
-
347
-    /**
348
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
-     *
350
-     * @param int $qty
351
-     * @return boolean indicating success
352
-     * @throws ReflectionException
353
-     * @throws InvalidArgumentException
354
-     * @throws InvalidInterfaceException
355
-     * @throws InvalidDataTypeException
356
-     * @throws EE_Error
357
-     */
358
-    public function increaseReserved(int $qty = 1): bool
359
-    {
360
-        $qty = absint($qty);
361
-        $success = $this->incrementFieldConditionallyInDb(
362
-            'DTT_reserved',
363
-            'DTT_sold',
364
-            'DTT_reg_limit',
365
-            $qty
366
-        );
367
-        do_action(
368
-            'AHEE__EE_Datetime__increase_reserved',
369
-            $this,
370
-            $qty,
371
-            $this->reserved(),
372
-            $success
373
-        );
374
-        return $success;
375
-    }
376
-
377
-
378
-    /**
379
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
-     *
381
-     * @param int $qty
382
-     * @return boolean indicating success
383
-     * @throws ReflectionException
384
-     * @throws InvalidArgumentException
385
-     * @throws InvalidInterfaceException
386
-     * @throws InvalidDataTypeException
387
-     * @throws EE_Error
388
-     */
389
-    public function decreaseReserved(int $qty = 1): bool
390
-    {
391
-        $qty = absint($qty);
392
-        $success = $this->adjustNumericFieldsInDb(
393
-            [
394
-                'DTT_reserved' => $qty * -1
395
-            ]
396
-        );
397
-        do_action(
398
-            'AHEE__EE_Datetime__decrease_reserved',
399
-            $this,
400
-            $qty,
401
-            $this->reserved(),
402
-            $success
403
-        );
404
-        return $success;
405
-    }
406
-
407
-
408
-    /**
409
-     * total sold and reserved tickets
410
-     *
411
-     * @return int
412
-     * @throws ReflectionException
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidInterfaceException
415
-     * @throws InvalidDataTypeException
416
-     * @throws EE_Error
417
-     */
418
-    public function sold_and_reserved(): int
419
-    {
420
-        return $this->sold() + $this->reserved();
421
-    }
422
-
423
-
424
-    /**
425
-     * returns the datetime name
426
-     *
427
-     * @return string
428
-     * @throws ReflectionException
429
-     * @throws InvalidArgumentException
430
-     * @throws InvalidInterfaceException
431
-     * @throws InvalidDataTypeException
432
-     * @throws EE_Error
433
-     */
434
-    public function name(): string
435
-    {
436
-        return $this->get('DTT_name');
437
-    }
438
-
439
-
440
-    /**
441
-     * returns the datetime description
442
-     *
443
-     * @return string
444
-     * @throws ReflectionException
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidInterfaceException
447
-     * @throws InvalidDataTypeException
448
-     * @throws EE_Error
449
-     */
450
-    public function description(): string
451
-    {
452
-        return $this->get('DTT_description');
453
-    }
454
-
455
-
456
-    /**
457
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
-     *
459
-     * @return boolean  TRUE if is primary, FALSE if not.
460
-     * @throws ReflectionException
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     */
466
-    public function is_primary(): bool
467
-    {
468
-        return $this->get('DTT_is_primary');
469
-    }
470
-
471
-
472
-    /**
473
-     * This helper simply returns the order for the datetime
474
-     *
475
-     * @return int  The order of the datetime for this event.
476
-     * @throws ReflectionException
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidInterfaceException
479
-     * @throws InvalidDataTypeException
480
-     * @throws EE_Error
481
-     */
482
-    public function order(): int
483
-    {
484
-        return $this->get('DTT_order');
485
-    }
486
-
487
-
488
-    /**
489
-     * This helper simply returns the parent id for the datetime
490
-     *
491
-     * @return int
492
-     * @throws ReflectionException
493
-     * @throws InvalidArgumentException
494
-     * @throws InvalidInterfaceException
495
-     * @throws InvalidDataTypeException
496
-     * @throws EE_Error
497
-     */
498
-    public function parent(): int
499
-    {
500
-        return $this->get('DTT_parent');
501
-    }
502
-
503
-
504
-    /**
505
-     * show date and/or time
506
-     *
507
-     * @param string $date_or_time    whether to display a date or time or both
508
-     * @param string $start_or_end    whether to display start or end datetimes
509
-     * @param string $dt_frmt
510
-     * @param string $tm_frmt
511
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
-     *                                otherwise we use the standard formats)
513
-     * @return string|bool  string on success, FALSE on fail
514
-     * @throws ReflectionException
515
-     * @throws InvalidArgumentException
516
-     * @throws InvalidInterfaceException
517
-     * @throws InvalidDataTypeException
518
-     * @throws EE_Error
519
-     */
520
-    private function _show_datetime(
521
-        $date_or_time = null,
522
-        $start_or_end = 'start',
523
-        $dt_frmt = '',
524
-        $tm_frmt = '',
525
-        $echo = false
526
-    ) {
527
-        $field_name = "DTT_EVT_{$start_or_end}";
528
-        $dtt = $this->_get_datetime(
529
-            $field_name,
530
-            $dt_frmt,
531
-            $tm_frmt,
532
-            $date_or_time,
533
-            $echo
534
-        );
535
-        if (! $echo) {
536
-            return $dtt;
537
-        }
538
-        return '';
539
-    }
540
-
541
-
542
-    /**
543
-     * get event start date.  Provide either the date format, or NULL to re-use the
544
-     * last-used format, or '' to use the default date format
545
-     *
546
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
-     * @return mixed            string on success, FALSE on fail
548
-     * @throws ReflectionException
549
-     * @throws InvalidArgumentException
550
-     * @throws InvalidInterfaceException
551
-     * @throws InvalidDataTypeException
552
-     * @throws EE_Error
553
-     */
554
-    public function start_date($dt_frmt = '')
555
-    {
556
-        return $this->_show_datetime('D', 'start', $dt_frmt);
557
-    }
558
-
559
-
560
-    /**
561
-     * Echoes start_date()
562
-     *
563
-     * @param string $dt_frmt
564
-     * @throws ReflectionException
565
-     * @throws InvalidArgumentException
566
-     * @throws InvalidInterfaceException
567
-     * @throws InvalidDataTypeException
568
-     * @throws EE_Error
569
-     */
570
-    public function e_start_date($dt_frmt = '')
571
-    {
572
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
-    }
574
-
575
-
576
-    /**
577
-     * get end date. Provide either the date format, or NULL to re-use the
578
-     * last-used format, or '' to use the default date format
579
-     *
580
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
-     * @return mixed            string on success, FALSE on fail
582
-     * @throws ReflectionException
583
-     * @throws InvalidArgumentException
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     */
588
-    public function end_date($dt_frmt = '')
589
-    {
590
-        return $this->_show_datetime('D', 'end', $dt_frmt);
591
-    }
592
-
593
-
594
-    /**
595
-     * Echoes the end date. See end_date()
596
-     *
597
-     * @param string $dt_frmt
598
-     * @throws ReflectionException
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidInterfaceException
601
-     * @throws InvalidDataTypeException
602
-     * @throws EE_Error
603
-     */
604
-    public function e_end_date($dt_frmt = '')
605
-    {
606
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
-    }
608
-
609
-
610
-    /**
611
-     * get date_range - meaning the start AND end date
612
-     *
613
-     * @access public
614
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
615
-     * @param string $conjunction conjunction junction what's your function ?
616
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
-     * @return mixed              string on success, FALSE on fail
618
-     * @throws ReflectionException
619
-     * @throws InvalidArgumentException
620
-     * @throws InvalidInterfaceException
621
-     * @throws InvalidDataTypeException
622
-     * @throws EE_Error
623
-     */
624
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
625
-    {
626
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
-        $start = str_replace(
628
-            ' ',
629
-            ' ',
630
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
-        );
632
-        $end = str_replace(
633
-            ' ',
634
-            ' ',
635
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
-        );
637
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
-    }
639
-
640
-
641
-    /**
642
-     * @param string $dt_frmt
643
-     * @param string $conjunction
644
-     * @throws ReflectionException
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
-    {
652
-        echo esc_html($this->date_range($dt_frmt, $conjunction));
653
-    }
654
-
655
-
656
-    /**
657
-     * get start time
658
-     *
659
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
-     * @return mixed        string on success, FALSE on fail
661
-     * @throws ReflectionException
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     */
667
-    public function start_time($tm_format = '')
668
-    {
669
-        return $this->_show_datetime('T', 'start', null, $tm_format);
670
-    }
671
-
672
-
673
-    /**
674
-     * @param string $tm_format
675
-     * @throws ReflectionException
676
-     * @throws InvalidArgumentException
677
-     * @throws InvalidInterfaceException
678
-     * @throws InvalidDataTypeException
679
-     * @throws EE_Error
680
-     */
681
-    public function e_start_time($tm_format = '')
682
-    {
683
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
684
-    }
685
-
686
-
687
-    /**
688
-     * get end time
689
-     *
690
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
691
-     * @return mixed                string on success, FALSE on fail
692
-     * @throws ReflectionException
693
-     * @throws InvalidArgumentException
694
-     * @throws InvalidInterfaceException
695
-     * @throws InvalidDataTypeException
696
-     * @throws EE_Error
697
-     */
698
-    public function end_time($tm_format = '')
699
-    {
700
-        return $this->_show_datetime('T', 'end', null, $tm_format);
701
-    }
702
-
703
-
704
-    /**
705
-     * @param string $tm_format
706
-     * @throws ReflectionException
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidInterfaceException
709
-     * @throws InvalidDataTypeException
710
-     * @throws EE_Error
711
-     */
712
-    public function e_end_time($tm_format = '')
713
-    {
714
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
715
-    }
716
-
717
-
718
-    /**
719
-     * get time_range
720
-     *
721
-     * @access public
722
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
-     * @param string $conjunction conjunction junction what's your function ?
724
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
-     * @return mixed              string on success, FALSE on fail
726
-     * @throws ReflectionException
727
-     * @throws InvalidArgumentException
728
-     * @throws InvalidInterfaceException
729
-     * @throws InvalidDataTypeException
730
-     * @throws EE_Error
731
-     */
732
-    public function time_range($tm_format = '', $conjunction = ' - ')
733
-    {
734
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
-        $start = str_replace(
736
-            ' ',
737
-            ' ',
738
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
-        );
740
-        $end = str_replace(
741
-            ' ',
742
-            ' ',
743
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
-        );
745
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
-    }
747
-
748
-
749
-    /**
750
-     * @param string $tm_format
751
-     * @param string $conjunction
752
-     * @throws ReflectionException
753
-     * @throws InvalidArgumentException
754
-     * @throws InvalidInterfaceException
755
-     * @throws InvalidDataTypeException
756
-     * @throws EE_Error
757
-     */
758
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
759
-    {
760
-        echo esc_html($this->time_range($tm_format, $conjunction));
761
-    }
762
-
763
-
764
-    /**
765
-     * This returns a range representation of the date and times.
766
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
-     * Also, the return value is localized.
768
-     *
769
-     * @param string $dt_format
770
-     * @param string $tm_format
771
-     * @param string $conjunction used between two different dates or times.
772
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
-     * @param string $separator   used between the date and time formats.
774
-     *                            ex: Dec 1, 2016{$separator}2pm
775
-     * @return string
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    public function date_and_time_range(
783
-        $dt_format = '',
784
-        $tm_format = '',
785
-        $conjunction = ' - ',
786
-        $separator = ' '
787
-    ) {
788
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
-        $full_format = $dt_format . $separator . $tm_format;
791
-        // the range output depends on various conditions
792
-        switch (true) {
793
-            // start date timestamp and end date timestamp are the same.
794
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
-                break;
797
-            // start and end date are the same but times are different
798
-            case ($this->start_date() === $this->end_date()):
799
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
-                          . $conjunction
801
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
-                break;
803
-            // all other conditions
804
-            default:
805
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
-                          . $conjunction
807
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
-                break;
809
-        }
810
-        return $output;
811
-    }
812
-
813
-
814
-    /**
815
-     * This echos the results of date and time range.
816
-     *
817
-     * @see date_and_time_range() for more details on purpose.
818
-     * @param string $dt_format
819
-     * @param string $tm_format
820
-     * @param string $conjunction
821
-     * @return void
822
-     * @throws ReflectionException
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidInterfaceException
825
-     * @throws InvalidDataTypeException
826
-     * @throws EE_Error
827
-     */
828
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
-    {
830
-        echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
-    }
832
-
833
-
834
-    /**
835
-     * get start date and start time
836
-     *
837
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
-     * @return    mixed    string on success, FALSE on fail
840
-     * @throws ReflectionException
841
-     * @throws InvalidArgumentException
842
-     * @throws InvalidInterfaceException
843
-     * @throws InvalidDataTypeException
844
-     * @throws EE_Error
845
-     */
846
-    public function start_date_and_time($dt_format = '', $tm_format = '')
847
-    {
848
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
-    }
850
-
851
-
852
-    /**
853
-     * @param string $dt_frmt
854
-     * @param string $tm_format
855
-     * @throws ReflectionException
856
-     * @throws InvalidArgumentException
857
-     * @throws InvalidInterfaceException
858
-     * @throws InvalidDataTypeException
859
-     * @throws EE_Error
860
-     */
861
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
-    {
863
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
-    }
865
-
866
-
867
-    /**
868
-     * Shows the length of the event (start to end time).
869
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
870
-     * By default, rounds up. (So if you use 'days', and then event
871
-     * only occurs for 1 hour, it will return 1 day).
872
-     *
873
-     * @param string $units 'seconds','minutes','hours','days'
874
-     * @param bool   $round_up
875
-     * @return float|int|mixed
876
-     * @throws ReflectionException
877
-     * @throws InvalidArgumentException
878
-     * @throws InvalidInterfaceException
879
-     * @throws InvalidDataTypeException
880
-     * @throws EE_Error
881
-     */
882
-    public function length($units = 'seconds', $round_up = false)
883
-    {
884
-        $start = $this->get_raw('DTT_EVT_start');
885
-        $end = $this->get_raw('DTT_EVT_end');
886
-        $length_in_units = $end - $start;
887
-        switch ($units) {
888
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
889
-            /** @noinspection PhpMissingBreakStatementInspection */
890
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
-            case 'days':
892
-                $length_in_units /= 24;
893
-            /** @noinspection PhpMissingBreakStatementInspection */
894
-            case 'hours':
895
-                // fall through is intentional
896
-                $length_in_units /= 60;
897
-            /** @noinspection PhpMissingBreakStatementInspection */
898
-            case 'minutes':
899
-                // fall through is intentional
900
-                $length_in_units /= 60;
901
-            case 'seconds':
902
-            default:
903
-                $length_in_units = ceil($length_in_units);
904
-        }
905
-        // phpcs:enable
906
-        if ($round_up) {
907
-            $length_in_units = max($length_in_units, 1);
908
-        }
909
-        return $length_in_units;
910
-    }
911
-
912
-
913
-    /**
914
-     *        get end date and time
915
-     *
916
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
-     * @return    mixed                string on success, FALSE on fail
919
-     * @throws ReflectionException
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidInterfaceException
922
-     * @throws InvalidDataTypeException
923
-     * @throws EE_Error
924
-     */
925
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
-    {
927
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
-    }
929
-
930
-
931
-    /**
932
-     * @param string $dt_frmt
933
-     * @param string $tm_format
934
-     * @throws ReflectionException
935
-     * @throws InvalidArgumentException
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidDataTypeException
938
-     * @throws EE_Error
939
-     */
940
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
-    {
942
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
-    }
944
-
945
-
946
-    /**
947
-     *        get start timestamp
948
-     *
949
-     * @return        int
950
-     * @throws ReflectionException
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidInterfaceException
953
-     * @throws InvalidDataTypeException
954
-     * @throws EE_Error
955
-     */
956
-    public function start()
957
-    {
958
-        return $this->get_raw('DTT_EVT_start');
959
-    }
960
-
961
-
962
-    /**
963
-     *        get end timestamp
964
-     *
965
-     * @return        int
966
-     * @throws ReflectionException
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidInterfaceException
969
-     * @throws InvalidDataTypeException
970
-     * @throws EE_Error
971
-     */
972
-    public function end()
973
-    {
974
-        return $this->get_raw('DTT_EVT_end');
975
-    }
976
-
977
-
978
-    /**
979
-     *    get the registration limit for this datetime slot
980
-     *
981
-     * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
-     * @throws ReflectionException
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidInterfaceException
985
-     * @throws InvalidDataTypeException
986
-     * @throws EE_Error
987
-     */
988
-    public function reg_limit()
989
-    {
990
-        return $this->get_raw('DTT_reg_limit');
991
-    }
992
-
993
-
994
-    /**
995
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
-     *
997
-     * @return boolean
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     */
1004
-    public function sold_out()
1005
-    {
1006
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
-    }
1008
-
1009
-
1010
-    /**
1011
-     * return the total number of spaces remaining at this venue.
1012
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
-     *
1014
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
-     *                               Because if all tickets attached to this datetime have no spaces left,
1016
-     *                               then this datetime IS effectively sold out.
1017
-     *                               However, there are cases where we just want to know the spaces
1018
-     *                               remaining for this particular datetime, hence the flag.
1019
-     * @return int|float
1020
-     * @throws ReflectionException
1021
-     * @throws InvalidArgumentException
1022
-     * @throws InvalidInterfaceException
1023
-     * @throws InvalidDataTypeException
1024
-     * @throws EE_Error
1025
-     */
1026
-    public function spaces_remaining($consider_tickets = false)
1027
-    {
1028
-        // tickets remaining available for purchase
1029
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
-        if (! $consider_tickets) {
1032
-            return $dtt_remaining;
1033
-        }
1034
-        $tickets_remaining = $this->tickets_remaining();
1035
-        return min($dtt_remaining, $tickets_remaining);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Counts the total tickets available
1041
-     * (from all the different types of tickets which are available for this datetime).
1042
-     *
1043
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
-     * @return int
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidArgumentException
1047
-     * @throws InvalidInterfaceException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws EE_Error
1050
-     */
1051
-    public function tickets_remaining($query_params = array())
1052
-    {
1053
-        $sum = 0;
1054
-        $tickets = $this->tickets($query_params);
1055
-        if (! empty($tickets)) {
1056
-            foreach ($tickets as $ticket) {
1057
-                if ($ticket instanceof EE_Ticket) {
1058
-                    // get the actual amount of tickets that can be sold
1059
-                    $qty = $ticket->qty('saleable');
1060
-                    if ($qty === EE_INF) {
1061
-                        return EE_INF;
1062
-                    }
1063
-                    // no negative ticket quantities plz
1064
-                    if ($qty > 0) {
1065
-                        $sum += $qty;
1066
-                    }
1067
-                }
1068
-            }
1069
-        }
1070
-        return $sum;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1076
-     * before any were sold
1077
-     *
1078
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
-     * @return int
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function sum_tickets_initially_available($query_params = array())
1087
-    {
1088
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
-     * that is available for this datetime).
1096
-     *
1097
-     * @return int
1098
-     * @throws ReflectionException
1099
-     * @throws InvalidArgumentException
1100
-     * @throws InvalidInterfaceException
1101
-     * @throws InvalidDataTypeException
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function total_tickets_available_at_this_datetime()
1105
-    {
1106
-        return $this->spaces_remaining(true);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * This simply compares the internal dtt for the given string with NOW
1112
-     * and determines if the date is upcoming or not.
1113
-     *
1114
-     * @access public
1115
-     * @return boolean
1116
-     * @throws ReflectionException
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidInterfaceException
1119
-     * @throws InvalidDataTypeException
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function is_upcoming()
1123
-    {
1124
-        return ($this->get_raw('DTT_EVT_start') > time());
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * This simply compares the internal datetime for the given string with NOW
1130
-     * and returns if the date is active (i.e. start and end time)
1131
-     *
1132
-     * @return boolean
1133
-     * @throws ReflectionException
1134
-     * @throws InvalidArgumentException
1135
-     * @throws InvalidInterfaceException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function is_active()
1140
-    {
1141
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * This simply compares the internal dtt for the given string with NOW
1147
-     * and determines if the date is expired or not.
1148
-     *
1149
-     * @return boolean
1150
-     * @throws ReflectionException
1151
-     * @throws InvalidArgumentException
1152
-     * @throws InvalidInterfaceException
1153
-     * @throws InvalidDataTypeException
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function is_expired()
1157
-    {
1158
-        return ($this->get_raw('DTT_EVT_end') < time());
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * This returns the active status for whether an event is active, upcoming, or expired
1164
-     *
1165
-     * @return int return value will be one of the EE_Datetime status constants.
1166
-     * @throws ReflectionException
1167
-     * @throws InvalidArgumentException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws InvalidDataTypeException
1170
-     * @throws EE_Error
1171
-     */
1172
-    public function get_active_status()
1173
-    {
1174
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
-            return EE_Datetime::sold_out;
1177
-        }
1178
-        if ($this->is_expired()) {
1179
-            return EE_Datetime::expired;
1180
-        }
1181
-        if ($this->is_upcoming()) {
1182
-            return EE_Datetime::upcoming;
1183
-        }
1184
-        if ($this->is_active()) {
1185
-            return EE_Datetime::active;
1186
-        }
1187
-        return null;
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
-     *
1194
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
-     * @return string
1196
-     * @throws ReflectionException
1197
-     * @throws InvalidArgumentException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function get_dtt_display_name($use_dtt_name = false)
1203
-    {
1204
-        if ($use_dtt_name) {
1205
-            $dtt_name = $this->name();
1206
-            if (! empty($dtt_name)) {
1207
-                return $dtt_name;
1208
-            }
1209
-        }
1210
-        // first condition is to see if the months are different
1211
-        if (
1212
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
-        ) {
1214
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
-            // next condition is if its the same month but different day
1216
-        } else {
1217
-            if (
1218
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
-            ) {
1221
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
-            } else {
1223
-                $display_date = $this->start_date('F j\, Y')
1224
-                                . ' @ '
1225
-                                . $this->start_date('g:i a')
1226
-                                . ' - '
1227
-                                . $this->end_date('g:i a');
1228
-            }
1229
-        }
1230
-        return $display_date;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     * Gets all the tickets for this datetime
1236
-     *
1237
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
-     * @return EE_Base_Class[]|EE_Ticket[]
1239
-     * @throws ReflectionException
1240
-     * @throws InvalidArgumentException
1241
-     * @throws InvalidInterfaceException
1242
-     * @throws InvalidDataTypeException
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function tickets($query_params = array())
1246
-    {
1247
-        return $this->get_many_related('Ticket', $query_params);
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * Gets all the ticket types currently available for purchase
1253
-     *
1254
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
-     * @return EE_Ticket[]
1256
-     * @throws ReflectionException
1257
-     * @throws InvalidArgumentException
1258
-     * @throws InvalidInterfaceException
1259
-     * @throws InvalidDataTypeException
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function ticket_types_available_for_purchase($query_params = array())
1263
-    {
1264
-        // first check if datetime is valid
1265
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
-            return array();
1267
-        }
1268
-        if (empty($query_params)) {
1269
-            $query_params = array(
1270
-                array(
1271
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
-                    'TKT_deleted'    => false,
1274
-                ),
1275
-            );
1276
-        }
1277
-        return $this->tickets($query_params);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * @return EE_Base_Class|EE_Event
1283
-     * @throws ReflectionException
1284
-     * @throws InvalidArgumentException
1285
-     * @throws InvalidInterfaceException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws EE_Error
1288
-     */
1289
-    public function event()
1290
-    {
1291
-        return $this->get_first_related('Event');
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
-     * (via the tickets).
1298
-     *
1299
-     * @return int
1300
-     * @throws ReflectionException
1301
-     * @throws InvalidArgumentException
1302
-     * @throws InvalidInterfaceException
1303
-     * @throws InvalidDataTypeException
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function update_sold()
1307
-    {
1308
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
-            array(
1310
-                array(
1311
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1312
-                    'REG_deleted'            => 0,
1313
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
-                ),
1315
-            )
1316
-        );
1317
-        $this->set_sold($count_regs_for_this_datetime);
1318
-        $this->save();
1319
-        return $count_regs_for_this_datetime;
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Adds a venue to this event
1325
-     *
1326
-     * @param int|EE_Venue /int $venue_id_or_obj
1327
-     * @return EE_Base_Class|EE_Venue
1328
-     * @throws EE_Error
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function add_venue($venue_id_or_obj): EE_Venue
1332
-    {
1333
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Removes a venue from the event
1339
-     *
1340
-     * @param EE_Venue /int $venue_id_or_obj
1341
-     * @return EE_Base_Class|EE_Venue
1342
-     * @throws EE_Error
1343
-     * @throws ReflectionException
1344
-     */
1345
-    public function remove_venue($venue_id_or_obj): EE_Venue
1346
-    {
1347
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Gets the venue related to the event. May provide additional $query_params if desired
1354
-     *
1355
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
-     * @return int
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function venue_ID(array $query_params = []): int
1361
-    {
1362
-        $venue = $this->get_first_related('Venue', $query_params);
1363
-        return $venue instanceof EE_Venue
1364
-            ? $venue->ID()
1365
-            : 0;
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Gets the venue related to the event. May provide additional $query_params if desired
1371
-     *
1372
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
-     * @return EE_Base_Class|EE_Venue
1374
-     * @throws EE_Error
1375
-     * @throws ReflectionException
1376
-     */
1377
-    public function venue(array $query_params = [])
1378
-    {
1379
-        return $this->get_first_related('Venue', $query_params);
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
-     * @param string                   $relationName
1386
-     * @param array                    $extra_join_model_fields_n_values
1387
-     * @param string|null              $cache_id
1388
-     * @return EE_Base_Class
1389
-     * @throws EE_Error
1390
-     * @throws ReflectionException
1391
-     * @since   5.0.0.p
1392
-     */
1393
-    public function _add_relation_to(
1394
-        $otherObjectModelObjectOrID,
1395
-        $relationName,
1396
-        $extra_join_model_fields_n_values = [],
1397
-        $cache_id = null
1398
-    ) {
1399
-        // if we're adding a new relation to a ticket
1400
-        if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
-            /** @var EE_Ticket $ticket */
1402
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
-            $this->increaseSold($ticket->sold(), false);
1404
-            $this->increaseReserved($ticket->reserved());
1405
-            $this->save();
1406
-            $otherObjectModelObjectOrID = $ticket;
1407
-        }
1408
-        return parent::_add_relation_to(
1409
-            $otherObjectModelObjectOrID,
1410
-            $relationName,
1411
-            $extra_join_model_fields_n_values,
1412
-            $cache_id
1413
-        );
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
-     * @param string                   $relationName
1420
-     * @param array                    $where_query
1421
-     * @return bool|EE_Base_Class|null
1422
-     * @throws EE_Error
1423
-     * @throws ReflectionException
1424
-     * @since   5.0.0.p
1425
-     */
1426
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
-    {
1428
-        if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
-            /** @var EE_Ticket $ticket */
1430
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
-            $this->decreaseSold($ticket->sold());
1432
-            $this->decreaseReserved($ticket->reserved());
1433
-            $this->save();
1434
-            $otherObjectModelObjectOrID = $ticket;
1435
-        }
1436
-        return parent::_remove_relation_to(
1437
-            $otherObjectModelObjectOrID,
1438
-            $relationName,
1439
-            $where_query
1440
-        );
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Removes ALL the related things for the $relationName.
1446
-     *
1447
-     * @param string $relationName
1448
-     * @param array  $where_query_params
1449
-     * @return EE_Base_Class
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
-     */
1457
-    public function _remove_relations($relationName, $where_query_params = [])
1458
-    {
1459
-        if ($relationName === 'Ticket') {
1460
-            $tickets = $this->tickets();
1461
-            foreach ($tickets as $ticket) {
1462
-                $this->decreaseSold($ticket->sold());
1463
-                $this->decreaseReserved($ticket->reserved());
1464
-                $this->save();
1465
-            }
1466
-        }
1467
-        return parent::_remove_relations($relationName, $where_query_params);
1468
-    }
1469
-
1470
-
1471
-    /*******************************************************************
15
+	/**
16
+	 * constant used by get_active_status, indicates datetime has no more available spaces
17
+	 */
18
+	const sold_out = 'DTS';
19
+
20
+	/**
21
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
+	 */
23
+	const active = 'DTA';
24
+
25
+	/**
26
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
+	 * expired
28
+	 */
29
+	const upcoming = 'DTU';
30
+
31
+	/**
32
+	 * Datetime is postponed
33
+	 */
34
+	const postponed = 'DTP';
35
+
36
+	/**
37
+	 * Datetime is cancelled
38
+	 */
39
+	const cancelled = 'DTC';
40
+
41
+	/**
42
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
43
+	 */
44
+	const expired = 'DTE';
45
+
46
+	/**
47
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
+	 */
49
+	const inactive = 'DTI';
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values    incoming values
54
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
+	 *                                  and the second value is the time format
57
+	 * @return EE_Datetime
58
+	 * @throws ReflectionException
59
+	 * @throws InvalidArgumentException
60
+	 * @throws InvalidInterfaceException
61
+	 * @throws InvalidDataTypeException
62
+	 * @throws EE_Error
63
+	 */
64
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
+	{
66
+		$has_object = parent::_check_for_object(
67
+			$props_n_values,
68
+			__CLASS__,
69
+			$timezone,
70
+			$date_formats
71
+		);
72
+		return $has_object
73
+			? $has_object
74
+			: new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Datetime
83
+	 * @throws ReflectionException
84
+	 * @throws InvalidArgumentException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws EE_Error
88
+	 */
89
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
+	{
91
+		return new self($props_n_values, true, $timezone);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param $name
97
+	 * @throws ReflectionException
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidInterfaceException
100
+	 * @throws InvalidDataTypeException
101
+	 * @throws EE_Error
102
+	 */
103
+	public function set_name($name)
104
+	{
105
+		$this->set('DTT_name', $name);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param $description
111
+	 * @throws ReflectionException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws InvalidDataTypeException
115
+	 * @throws EE_Error
116
+	 */
117
+	public function set_description($description)
118
+	{
119
+		$this->set('DTT_description', $description);
120
+	}
121
+
122
+
123
+	/**
124
+	 * Set event start date
125
+	 * set the start date for an event
126
+	 *
127
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
+	 * @throws ReflectionException
129
+	 * @throws InvalidArgumentException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws EE_Error
133
+	 */
134
+	public function set_start_date($date)
135
+	{
136
+		$this->_set_date_for($date, 'DTT_EVT_start');
137
+	}
138
+
139
+
140
+	/**
141
+	 * Set event start time
142
+	 * set the start time for an event
143
+	 *
144
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
+	 * @throws ReflectionException
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidInterfaceException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws EE_Error
150
+	 */
151
+	public function set_start_time($time)
152
+	{
153
+		$this->_set_time_for($time, 'DTT_EVT_start');
154
+	}
155
+
156
+
157
+	/**
158
+	 * Set event end date
159
+	 * set the end date for an event
160
+	 *
161
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
+	 * @throws ReflectionException
163
+	 * @throws InvalidArgumentException
164
+	 * @throws InvalidInterfaceException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws EE_Error
167
+	 */
168
+	public function set_end_date($date)
169
+	{
170
+		$this->_set_date_for($date, 'DTT_EVT_end');
171
+	}
172
+
173
+
174
+	/**
175
+	 * Set event end time
176
+	 * set the end time for an event
177
+	 *
178
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
+	 * @throws ReflectionException
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidInterfaceException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws EE_Error
184
+	 */
185
+	public function set_end_time($time)
186
+	{
187
+		$this->_set_time_for($time, 'DTT_EVT_end');
188
+	}
189
+
190
+
191
+	/**
192
+	 * Set registration limit
193
+	 * set the maximum number of attendees that can be registered for this datetime slot
194
+	 *
195
+	 * @param int|float $reg_limit
196
+	 * @throws ReflectionException
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidInterfaceException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws EE_Error
201
+	 */
202
+	public function set_reg_limit($reg_limit)
203
+	{
204
+		$this->set('DTT_reg_limit', $reg_limit);
205
+	}
206
+
207
+
208
+	/**
209
+	 * get the number of tickets sold for this datetime slot
210
+	 *
211
+	 * @return mixed int on success, FALSE on fail
212
+	 * @throws ReflectionException
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidInterfaceException
215
+	 * @throws InvalidDataTypeException
216
+	 * @throws EE_Error
217
+	 */
218
+	public function sold()
219
+	{
220
+		return $this->get_raw('DTT_sold');
221
+	}
222
+
223
+
224
+	/**
225
+	 * @param int $sold
226
+	 * @throws ReflectionException
227
+	 * @throws InvalidArgumentException
228
+	 * @throws InvalidInterfaceException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws EE_Error
231
+	 */
232
+	public function set_sold($sold)
233
+	{
234
+		// sold can not go below zero
235
+		$sold = max(0, $sold);
236
+		$this->set('DTT_sold', $sold);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
+	 *
244
+	 * @param int $qty
245
+	 * @param boolean $also_decrease_reserved
246
+	 * @return boolean indicating success
247
+	 * @throws ReflectionException
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws EE_Error
252
+	 */
253
+	public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
+	{
255
+		$qty = absint($qty);
256
+		if ($also_decrease_reserved) {
257
+			$success = $this->adjustNumericFieldsInDb(
258
+				[
259
+					'DTT_reserved' => $qty * -1,
260
+					'DTT_sold' => $qty
261
+				]
262
+			);
263
+		} else {
264
+			$success = $this->adjustNumericFieldsInDb(
265
+				[
266
+					'DTT_sold' => $qty
267
+				]
268
+			);
269
+		}
270
+
271
+		do_action(
272
+			'AHEE__EE_Datetime__increase_sold',
273
+			$this,
274
+			$qty,
275
+			$this->sold(),
276
+			$success
277
+		);
278
+		return $success;
279
+	}
280
+
281
+
282
+	/**
283
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
+	 * to save afterwards.)
285
+	 *
286
+	 * @param int $qty
287
+	 * @return boolean indicating success
288
+	 * @throws ReflectionException
289
+	 * @throws InvalidArgumentException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws EE_Error
293
+	 */
294
+	public function decreaseSold(int $qty = 1): bool
295
+	{
296
+		$qty = absint($qty);
297
+		$success = $this->adjustNumericFieldsInDb(
298
+			[
299
+				'DTT_sold' => $qty * -1
300
+			]
301
+		);
302
+		do_action(
303
+			'AHEE__EE_Datetime__decrease_sold',
304
+			$this,
305
+			$qty,
306
+			$this->sold(),
307
+			$success
308
+		);
309
+		return $success;
310
+	}
311
+
312
+
313
+	/**
314
+	 * Gets qty of reserved tickets for this datetime
315
+	 *
316
+	 * @return int
317
+	 * @throws ReflectionException
318
+	 * @throws InvalidArgumentException
319
+	 * @throws InvalidInterfaceException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws EE_Error
322
+	 */
323
+	public function reserved(): int
324
+	{
325
+		return $this->get_raw('DTT_reserved');
326
+	}
327
+
328
+
329
+	/**
330
+	 * Sets qty of reserved tickets for this datetime
331
+	 *
332
+	 * @param int $reserved
333
+	 * @throws ReflectionException
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws EE_Error
338
+	 */
339
+	public function set_reserved(int $reserved)
340
+	{
341
+		// reserved can not go below zero
342
+		$reserved = max(0, $reserved);
343
+		$this->set('DTT_reserved', $reserved);
344
+	}
345
+
346
+
347
+	/**
348
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
+	 *
350
+	 * @param int $qty
351
+	 * @return boolean indicating success
352
+	 * @throws ReflectionException
353
+	 * @throws InvalidArgumentException
354
+	 * @throws InvalidInterfaceException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws EE_Error
357
+	 */
358
+	public function increaseReserved(int $qty = 1): bool
359
+	{
360
+		$qty = absint($qty);
361
+		$success = $this->incrementFieldConditionallyInDb(
362
+			'DTT_reserved',
363
+			'DTT_sold',
364
+			'DTT_reg_limit',
365
+			$qty
366
+		);
367
+		do_action(
368
+			'AHEE__EE_Datetime__increase_reserved',
369
+			$this,
370
+			$qty,
371
+			$this->reserved(),
372
+			$success
373
+		);
374
+		return $success;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
+	 *
381
+	 * @param int $qty
382
+	 * @return boolean indicating success
383
+	 * @throws ReflectionException
384
+	 * @throws InvalidArgumentException
385
+	 * @throws InvalidInterfaceException
386
+	 * @throws InvalidDataTypeException
387
+	 * @throws EE_Error
388
+	 */
389
+	public function decreaseReserved(int $qty = 1): bool
390
+	{
391
+		$qty = absint($qty);
392
+		$success = $this->adjustNumericFieldsInDb(
393
+			[
394
+				'DTT_reserved' => $qty * -1
395
+			]
396
+		);
397
+		do_action(
398
+			'AHEE__EE_Datetime__decrease_reserved',
399
+			$this,
400
+			$qty,
401
+			$this->reserved(),
402
+			$success
403
+		);
404
+		return $success;
405
+	}
406
+
407
+
408
+	/**
409
+	 * total sold and reserved tickets
410
+	 *
411
+	 * @return int
412
+	 * @throws ReflectionException
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidInterfaceException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws EE_Error
417
+	 */
418
+	public function sold_and_reserved(): int
419
+	{
420
+		return $this->sold() + $this->reserved();
421
+	}
422
+
423
+
424
+	/**
425
+	 * returns the datetime name
426
+	 *
427
+	 * @return string
428
+	 * @throws ReflectionException
429
+	 * @throws InvalidArgumentException
430
+	 * @throws InvalidInterfaceException
431
+	 * @throws InvalidDataTypeException
432
+	 * @throws EE_Error
433
+	 */
434
+	public function name(): string
435
+	{
436
+		return $this->get('DTT_name');
437
+	}
438
+
439
+
440
+	/**
441
+	 * returns the datetime description
442
+	 *
443
+	 * @return string
444
+	 * @throws ReflectionException
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidInterfaceException
447
+	 * @throws InvalidDataTypeException
448
+	 * @throws EE_Error
449
+	 */
450
+	public function description(): string
451
+	{
452
+		return $this->get('DTT_description');
453
+	}
454
+
455
+
456
+	/**
457
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
+	 *
459
+	 * @return boolean  TRUE if is primary, FALSE if not.
460
+	 * @throws ReflectionException
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 */
466
+	public function is_primary(): bool
467
+	{
468
+		return $this->get('DTT_is_primary');
469
+	}
470
+
471
+
472
+	/**
473
+	 * This helper simply returns the order for the datetime
474
+	 *
475
+	 * @return int  The order of the datetime for this event.
476
+	 * @throws ReflectionException
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidInterfaceException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws EE_Error
481
+	 */
482
+	public function order(): int
483
+	{
484
+		return $this->get('DTT_order');
485
+	}
486
+
487
+
488
+	/**
489
+	 * This helper simply returns the parent id for the datetime
490
+	 *
491
+	 * @return int
492
+	 * @throws ReflectionException
493
+	 * @throws InvalidArgumentException
494
+	 * @throws InvalidInterfaceException
495
+	 * @throws InvalidDataTypeException
496
+	 * @throws EE_Error
497
+	 */
498
+	public function parent(): int
499
+	{
500
+		return $this->get('DTT_parent');
501
+	}
502
+
503
+
504
+	/**
505
+	 * show date and/or time
506
+	 *
507
+	 * @param string $date_or_time    whether to display a date or time or both
508
+	 * @param string $start_or_end    whether to display start or end datetimes
509
+	 * @param string $dt_frmt
510
+	 * @param string $tm_frmt
511
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
+	 *                                otherwise we use the standard formats)
513
+	 * @return string|bool  string on success, FALSE on fail
514
+	 * @throws ReflectionException
515
+	 * @throws InvalidArgumentException
516
+	 * @throws InvalidInterfaceException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws EE_Error
519
+	 */
520
+	private function _show_datetime(
521
+		$date_or_time = null,
522
+		$start_or_end = 'start',
523
+		$dt_frmt = '',
524
+		$tm_frmt = '',
525
+		$echo = false
526
+	) {
527
+		$field_name = "DTT_EVT_{$start_or_end}";
528
+		$dtt = $this->_get_datetime(
529
+			$field_name,
530
+			$dt_frmt,
531
+			$tm_frmt,
532
+			$date_or_time,
533
+			$echo
534
+		);
535
+		if (! $echo) {
536
+			return $dtt;
537
+		}
538
+		return '';
539
+	}
540
+
541
+
542
+	/**
543
+	 * get event start date.  Provide either the date format, or NULL to re-use the
544
+	 * last-used format, or '' to use the default date format
545
+	 *
546
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
+	 * @return mixed            string on success, FALSE on fail
548
+	 * @throws ReflectionException
549
+	 * @throws InvalidArgumentException
550
+	 * @throws InvalidInterfaceException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws EE_Error
553
+	 */
554
+	public function start_date($dt_frmt = '')
555
+	{
556
+		return $this->_show_datetime('D', 'start', $dt_frmt);
557
+	}
558
+
559
+
560
+	/**
561
+	 * Echoes start_date()
562
+	 *
563
+	 * @param string $dt_frmt
564
+	 * @throws ReflectionException
565
+	 * @throws InvalidArgumentException
566
+	 * @throws InvalidInterfaceException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws EE_Error
569
+	 */
570
+	public function e_start_date($dt_frmt = '')
571
+	{
572
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
+	}
574
+
575
+
576
+	/**
577
+	 * get end date. Provide either the date format, or NULL to re-use the
578
+	 * last-used format, or '' to use the default date format
579
+	 *
580
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
+	 * @return mixed            string on success, FALSE on fail
582
+	 * @throws ReflectionException
583
+	 * @throws InvalidArgumentException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 */
588
+	public function end_date($dt_frmt = '')
589
+	{
590
+		return $this->_show_datetime('D', 'end', $dt_frmt);
591
+	}
592
+
593
+
594
+	/**
595
+	 * Echoes the end date. See end_date()
596
+	 *
597
+	 * @param string $dt_frmt
598
+	 * @throws ReflectionException
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws InvalidDataTypeException
602
+	 * @throws EE_Error
603
+	 */
604
+	public function e_end_date($dt_frmt = '')
605
+	{
606
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
+	}
608
+
609
+
610
+	/**
611
+	 * get date_range - meaning the start AND end date
612
+	 *
613
+	 * @access public
614
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
615
+	 * @param string $conjunction conjunction junction what's your function ?
616
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
+	 * @return mixed              string on success, FALSE on fail
618
+	 * @throws ReflectionException
619
+	 * @throws InvalidArgumentException
620
+	 * @throws InvalidInterfaceException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws EE_Error
623
+	 */
624
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
625
+	{
626
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
+		$start = str_replace(
628
+			' ',
629
+			'&nbsp;',
630
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
+		);
632
+		$end = str_replace(
633
+			' ',
634
+			'&nbsp;',
635
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
+		);
637
+		return $start !== $end ? $start . $conjunction . $end : $start;
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param string $dt_frmt
643
+	 * @param string $conjunction
644
+	 * @throws ReflectionException
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
+	{
652
+		echo esc_html($this->date_range($dt_frmt, $conjunction));
653
+	}
654
+
655
+
656
+	/**
657
+	 * get start time
658
+	 *
659
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
+	 * @return mixed        string on success, FALSE on fail
661
+	 * @throws ReflectionException
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 */
667
+	public function start_time($tm_format = '')
668
+	{
669
+		return $this->_show_datetime('T', 'start', null, $tm_format);
670
+	}
671
+
672
+
673
+	/**
674
+	 * @param string $tm_format
675
+	 * @throws ReflectionException
676
+	 * @throws InvalidArgumentException
677
+	 * @throws InvalidInterfaceException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws EE_Error
680
+	 */
681
+	public function e_start_time($tm_format = '')
682
+	{
683
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
684
+	}
685
+
686
+
687
+	/**
688
+	 * get end time
689
+	 *
690
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
691
+	 * @return mixed                string on success, FALSE on fail
692
+	 * @throws ReflectionException
693
+	 * @throws InvalidArgumentException
694
+	 * @throws InvalidInterfaceException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws EE_Error
697
+	 */
698
+	public function end_time($tm_format = '')
699
+	{
700
+		return $this->_show_datetime('T', 'end', null, $tm_format);
701
+	}
702
+
703
+
704
+	/**
705
+	 * @param string $tm_format
706
+	 * @throws ReflectionException
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidInterfaceException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws EE_Error
711
+	 */
712
+	public function e_end_time($tm_format = '')
713
+	{
714
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
715
+	}
716
+
717
+
718
+	/**
719
+	 * get time_range
720
+	 *
721
+	 * @access public
722
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
+	 * @param string $conjunction conjunction junction what's your function ?
724
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
+	 * @return mixed              string on success, FALSE on fail
726
+	 * @throws ReflectionException
727
+	 * @throws InvalidArgumentException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws InvalidDataTypeException
730
+	 * @throws EE_Error
731
+	 */
732
+	public function time_range($tm_format = '', $conjunction = ' - ')
733
+	{
734
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
+		$start = str_replace(
736
+			' ',
737
+			'&nbsp;',
738
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
+		);
740
+		$end = str_replace(
741
+			' ',
742
+			'&nbsp;',
743
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
+		);
745
+		return $start !== $end ? $start . $conjunction . $end : $start;
746
+	}
747
+
748
+
749
+	/**
750
+	 * @param string $tm_format
751
+	 * @param string $conjunction
752
+	 * @throws ReflectionException
753
+	 * @throws InvalidArgumentException
754
+	 * @throws InvalidInterfaceException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws EE_Error
757
+	 */
758
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
759
+	{
760
+		echo esc_html($this->time_range($tm_format, $conjunction));
761
+	}
762
+
763
+
764
+	/**
765
+	 * This returns a range representation of the date and times.
766
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
+	 * Also, the return value is localized.
768
+	 *
769
+	 * @param string $dt_format
770
+	 * @param string $tm_format
771
+	 * @param string $conjunction used between two different dates or times.
772
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
+	 * @param string $separator   used between the date and time formats.
774
+	 *                            ex: Dec 1, 2016{$separator}2pm
775
+	 * @return string
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	public function date_and_time_range(
783
+		$dt_format = '',
784
+		$tm_format = '',
785
+		$conjunction = ' - ',
786
+		$separator = ' '
787
+	) {
788
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
+		$full_format = $dt_format . $separator . $tm_format;
791
+		// the range output depends on various conditions
792
+		switch (true) {
793
+			// start date timestamp and end date timestamp are the same.
794
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
+				break;
797
+			// start and end date are the same but times are different
798
+			case ($this->start_date() === $this->end_date()):
799
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
+						  . $conjunction
801
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
+				break;
803
+			// all other conditions
804
+			default:
805
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
+						  . $conjunction
807
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
+				break;
809
+		}
810
+		return $output;
811
+	}
812
+
813
+
814
+	/**
815
+	 * This echos the results of date and time range.
816
+	 *
817
+	 * @see date_and_time_range() for more details on purpose.
818
+	 * @param string $dt_format
819
+	 * @param string $tm_format
820
+	 * @param string $conjunction
821
+	 * @return void
822
+	 * @throws ReflectionException
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidInterfaceException
825
+	 * @throws InvalidDataTypeException
826
+	 * @throws EE_Error
827
+	 */
828
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
+	{
830
+		echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
+	}
832
+
833
+
834
+	/**
835
+	 * get start date and start time
836
+	 *
837
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
+	 * @return    mixed    string on success, FALSE on fail
840
+	 * @throws ReflectionException
841
+	 * @throws InvalidArgumentException
842
+	 * @throws InvalidInterfaceException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws EE_Error
845
+	 */
846
+	public function start_date_and_time($dt_format = '', $tm_format = '')
847
+	{
848
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
+	}
850
+
851
+
852
+	/**
853
+	 * @param string $dt_frmt
854
+	 * @param string $tm_format
855
+	 * @throws ReflectionException
856
+	 * @throws InvalidArgumentException
857
+	 * @throws InvalidInterfaceException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws EE_Error
860
+	 */
861
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
+	{
863
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
+	}
865
+
866
+
867
+	/**
868
+	 * Shows the length of the event (start to end time).
869
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
870
+	 * By default, rounds up. (So if you use 'days', and then event
871
+	 * only occurs for 1 hour, it will return 1 day).
872
+	 *
873
+	 * @param string $units 'seconds','minutes','hours','days'
874
+	 * @param bool   $round_up
875
+	 * @return float|int|mixed
876
+	 * @throws ReflectionException
877
+	 * @throws InvalidArgumentException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws EE_Error
881
+	 */
882
+	public function length($units = 'seconds', $round_up = false)
883
+	{
884
+		$start = $this->get_raw('DTT_EVT_start');
885
+		$end = $this->get_raw('DTT_EVT_end');
886
+		$length_in_units = $end - $start;
887
+		switch ($units) {
888
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
889
+			/** @noinspection PhpMissingBreakStatementInspection */
890
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
+			case 'days':
892
+				$length_in_units /= 24;
893
+			/** @noinspection PhpMissingBreakStatementInspection */
894
+			case 'hours':
895
+				// fall through is intentional
896
+				$length_in_units /= 60;
897
+			/** @noinspection PhpMissingBreakStatementInspection */
898
+			case 'minutes':
899
+				// fall through is intentional
900
+				$length_in_units /= 60;
901
+			case 'seconds':
902
+			default:
903
+				$length_in_units = ceil($length_in_units);
904
+		}
905
+		// phpcs:enable
906
+		if ($round_up) {
907
+			$length_in_units = max($length_in_units, 1);
908
+		}
909
+		return $length_in_units;
910
+	}
911
+
912
+
913
+	/**
914
+	 *        get end date and time
915
+	 *
916
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
+	 * @return    mixed                string on success, FALSE on fail
919
+	 * @throws ReflectionException
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidInterfaceException
922
+	 * @throws InvalidDataTypeException
923
+	 * @throws EE_Error
924
+	 */
925
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
+	{
927
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
+	}
929
+
930
+
931
+	/**
932
+	 * @param string $dt_frmt
933
+	 * @param string $tm_format
934
+	 * @throws ReflectionException
935
+	 * @throws InvalidArgumentException
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws EE_Error
939
+	 */
940
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
+	{
942
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
+	}
944
+
945
+
946
+	/**
947
+	 *        get start timestamp
948
+	 *
949
+	 * @return        int
950
+	 * @throws ReflectionException
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidInterfaceException
953
+	 * @throws InvalidDataTypeException
954
+	 * @throws EE_Error
955
+	 */
956
+	public function start()
957
+	{
958
+		return $this->get_raw('DTT_EVT_start');
959
+	}
960
+
961
+
962
+	/**
963
+	 *        get end timestamp
964
+	 *
965
+	 * @return        int
966
+	 * @throws ReflectionException
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidInterfaceException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws EE_Error
971
+	 */
972
+	public function end()
973
+	{
974
+		return $this->get_raw('DTT_EVT_end');
975
+	}
976
+
977
+
978
+	/**
979
+	 *    get the registration limit for this datetime slot
980
+	 *
981
+	 * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
+	 * @throws ReflectionException
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidInterfaceException
985
+	 * @throws InvalidDataTypeException
986
+	 * @throws EE_Error
987
+	 */
988
+	public function reg_limit()
989
+	{
990
+		return $this->get_raw('DTT_reg_limit');
991
+	}
992
+
993
+
994
+	/**
995
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
+	 *
997
+	 * @return boolean
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 */
1004
+	public function sold_out()
1005
+	{
1006
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
+	}
1008
+
1009
+
1010
+	/**
1011
+	 * return the total number of spaces remaining at this venue.
1012
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
+	 *
1014
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1016
+	 *                               then this datetime IS effectively sold out.
1017
+	 *                               However, there are cases where we just want to know the spaces
1018
+	 *                               remaining for this particular datetime, hence the flag.
1019
+	 * @return int|float
1020
+	 * @throws ReflectionException
1021
+	 * @throws InvalidArgumentException
1022
+	 * @throws InvalidInterfaceException
1023
+	 * @throws InvalidDataTypeException
1024
+	 * @throws EE_Error
1025
+	 */
1026
+	public function spaces_remaining($consider_tickets = false)
1027
+	{
1028
+		// tickets remaining available for purchase
1029
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
+		if (! $consider_tickets) {
1032
+			return $dtt_remaining;
1033
+		}
1034
+		$tickets_remaining = $this->tickets_remaining();
1035
+		return min($dtt_remaining, $tickets_remaining);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Counts the total tickets available
1041
+	 * (from all the different types of tickets which are available for this datetime).
1042
+	 *
1043
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
+	 * @return int
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws EE_Error
1050
+	 */
1051
+	public function tickets_remaining($query_params = array())
1052
+	{
1053
+		$sum = 0;
1054
+		$tickets = $this->tickets($query_params);
1055
+		if (! empty($tickets)) {
1056
+			foreach ($tickets as $ticket) {
1057
+				if ($ticket instanceof EE_Ticket) {
1058
+					// get the actual amount of tickets that can be sold
1059
+					$qty = $ticket->qty('saleable');
1060
+					if ($qty === EE_INF) {
1061
+						return EE_INF;
1062
+					}
1063
+					// no negative ticket quantities plz
1064
+					if ($qty > 0) {
1065
+						$sum += $qty;
1066
+					}
1067
+				}
1068
+			}
1069
+		}
1070
+		return $sum;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1076
+	 * before any were sold
1077
+	 *
1078
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
+	 * @return int
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function sum_tickets_initially_available($query_params = array())
1087
+	{
1088
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
+	 * that is available for this datetime).
1096
+	 *
1097
+	 * @return int
1098
+	 * @throws ReflectionException
1099
+	 * @throws InvalidArgumentException
1100
+	 * @throws InvalidInterfaceException
1101
+	 * @throws InvalidDataTypeException
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function total_tickets_available_at_this_datetime()
1105
+	{
1106
+		return $this->spaces_remaining(true);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * This simply compares the internal dtt for the given string with NOW
1112
+	 * and determines if the date is upcoming or not.
1113
+	 *
1114
+	 * @access public
1115
+	 * @return boolean
1116
+	 * @throws ReflectionException
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidInterfaceException
1119
+	 * @throws InvalidDataTypeException
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function is_upcoming()
1123
+	{
1124
+		return ($this->get_raw('DTT_EVT_start') > time());
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * This simply compares the internal datetime for the given string with NOW
1130
+	 * and returns if the date is active (i.e. start and end time)
1131
+	 *
1132
+	 * @return boolean
1133
+	 * @throws ReflectionException
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws InvalidInterfaceException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function is_active()
1140
+	{
1141
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * This simply compares the internal dtt for the given string with NOW
1147
+	 * and determines if the date is expired or not.
1148
+	 *
1149
+	 * @return boolean
1150
+	 * @throws ReflectionException
1151
+	 * @throws InvalidArgumentException
1152
+	 * @throws InvalidInterfaceException
1153
+	 * @throws InvalidDataTypeException
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function is_expired()
1157
+	{
1158
+		return ($this->get_raw('DTT_EVT_end') < time());
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * This returns the active status for whether an event is active, upcoming, or expired
1164
+	 *
1165
+	 * @return int return value will be one of the EE_Datetime status constants.
1166
+	 * @throws ReflectionException
1167
+	 * @throws InvalidArgumentException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws InvalidDataTypeException
1170
+	 * @throws EE_Error
1171
+	 */
1172
+	public function get_active_status()
1173
+	{
1174
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
+			return EE_Datetime::sold_out;
1177
+		}
1178
+		if ($this->is_expired()) {
1179
+			return EE_Datetime::expired;
1180
+		}
1181
+		if ($this->is_upcoming()) {
1182
+			return EE_Datetime::upcoming;
1183
+		}
1184
+		if ($this->is_active()) {
1185
+			return EE_Datetime::active;
1186
+		}
1187
+		return null;
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
+	 *
1194
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
+	 * @return string
1196
+	 * @throws ReflectionException
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function get_dtt_display_name($use_dtt_name = false)
1203
+	{
1204
+		if ($use_dtt_name) {
1205
+			$dtt_name = $this->name();
1206
+			if (! empty($dtt_name)) {
1207
+				return $dtt_name;
1208
+			}
1209
+		}
1210
+		// first condition is to see if the months are different
1211
+		if (
1212
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
+		) {
1214
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+			// next condition is if its the same month but different day
1216
+		} else {
1217
+			if (
1218
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
+			) {
1221
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+			} else {
1223
+				$display_date = $this->start_date('F j\, Y')
1224
+								. ' @ '
1225
+								. $this->start_date('g:i a')
1226
+								. ' - '
1227
+								. $this->end_date('g:i a');
1228
+			}
1229
+		}
1230
+		return $display_date;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 * Gets all the tickets for this datetime
1236
+	 *
1237
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
+	 * @return EE_Base_Class[]|EE_Ticket[]
1239
+	 * @throws ReflectionException
1240
+	 * @throws InvalidArgumentException
1241
+	 * @throws InvalidInterfaceException
1242
+	 * @throws InvalidDataTypeException
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function tickets($query_params = array())
1246
+	{
1247
+		return $this->get_many_related('Ticket', $query_params);
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * Gets all the ticket types currently available for purchase
1253
+	 *
1254
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
+	 * @return EE_Ticket[]
1256
+	 * @throws ReflectionException
1257
+	 * @throws InvalidArgumentException
1258
+	 * @throws InvalidInterfaceException
1259
+	 * @throws InvalidDataTypeException
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function ticket_types_available_for_purchase($query_params = array())
1263
+	{
1264
+		// first check if datetime is valid
1265
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
+			return array();
1267
+		}
1268
+		if (empty($query_params)) {
1269
+			$query_params = array(
1270
+				array(
1271
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
+					'TKT_deleted'    => false,
1274
+				),
1275
+			);
1276
+		}
1277
+		return $this->tickets($query_params);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * @return EE_Base_Class|EE_Event
1283
+	 * @throws ReflectionException
1284
+	 * @throws InvalidArgumentException
1285
+	 * @throws InvalidInterfaceException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws EE_Error
1288
+	 */
1289
+	public function event()
1290
+	{
1291
+		return $this->get_first_related('Event');
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
+	 * (via the tickets).
1298
+	 *
1299
+	 * @return int
1300
+	 * @throws ReflectionException
1301
+	 * @throws InvalidArgumentException
1302
+	 * @throws InvalidInterfaceException
1303
+	 * @throws InvalidDataTypeException
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function update_sold()
1307
+	{
1308
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
+			array(
1310
+				array(
1311
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1312
+					'REG_deleted'            => 0,
1313
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
+				),
1315
+			)
1316
+		);
1317
+		$this->set_sold($count_regs_for_this_datetime);
1318
+		$this->save();
1319
+		return $count_regs_for_this_datetime;
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Adds a venue to this event
1325
+	 *
1326
+	 * @param int|EE_Venue /int $venue_id_or_obj
1327
+	 * @return EE_Base_Class|EE_Venue
1328
+	 * @throws EE_Error
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function add_venue($venue_id_or_obj): EE_Venue
1332
+	{
1333
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Removes a venue from the event
1339
+	 *
1340
+	 * @param EE_Venue /int $venue_id_or_obj
1341
+	 * @return EE_Base_Class|EE_Venue
1342
+	 * @throws EE_Error
1343
+	 * @throws ReflectionException
1344
+	 */
1345
+	public function remove_venue($venue_id_or_obj): EE_Venue
1346
+	{
1347
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1354
+	 *
1355
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
+	 * @return int
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function venue_ID(array $query_params = []): int
1361
+	{
1362
+		$venue = $this->get_first_related('Venue', $query_params);
1363
+		return $venue instanceof EE_Venue
1364
+			? $venue->ID()
1365
+			: 0;
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1371
+	 *
1372
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
+	 * @return EE_Base_Class|EE_Venue
1374
+	 * @throws EE_Error
1375
+	 * @throws ReflectionException
1376
+	 */
1377
+	public function venue(array $query_params = [])
1378
+	{
1379
+		return $this->get_first_related('Venue', $query_params);
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
+	 * @param string                   $relationName
1386
+	 * @param array                    $extra_join_model_fields_n_values
1387
+	 * @param string|null              $cache_id
1388
+	 * @return EE_Base_Class
1389
+	 * @throws EE_Error
1390
+	 * @throws ReflectionException
1391
+	 * @since   5.0.0.p
1392
+	 */
1393
+	public function _add_relation_to(
1394
+		$otherObjectModelObjectOrID,
1395
+		$relationName,
1396
+		$extra_join_model_fields_n_values = [],
1397
+		$cache_id = null
1398
+	) {
1399
+		// if we're adding a new relation to a ticket
1400
+		if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
+			/** @var EE_Ticket $ticket */
1402
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
+			$this->increaseSold($ticket->sold(), false);
1404
+			$this->increaseReserved($ticket->reserved());
1405
+			$this->save();
1406
+			$otherObjectModelObjectOrID = $ticket;
1407
+		}
1408
+		return parent::_add_relation_to(
1409
+			$otherObjectModelObjectOrID,
1410
+			$relationName,
1411
+			$extra_join_model_fields_n_values,
1412
+			$cache_id
1413
+		);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
+	 * @param string                   $relationName
1420
+	 * @param array                    $where_query
1421
+	 * @return bool|EE_Base_Class|null
1422
+	 * @throws EE_Error
1423
+	 * @throws ReflectionException
1424
+	 * @since   5.0.0.p
1425
+	 */
1426
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
+	{
1428
+		if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
+			/** @var EE_Ticket $ticket */
1430
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
+			$this->decreaseSold($ticket->sold());
1432
+			$this->decreaseReserved($ticket->reserved());
1433
+			$this->save();
1434
+			$otherObjectModelObjectOrID = $ticket;
1435
+		}
1436
+		return parent::_remove_relation_to(
1437
+			$otherObjectModelObjectOrID,
1438
+			$relationName,
1439
+			$where_query
1440
+		);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Removes ALL the related things for the $relationName.
1446
+	 *
1447
+	 * @param string $relationName
1448
+	 * @param array  $where_query_params
1449
+	 * @return EE_Base_Class
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
+	 */
1457
+	public function _remove_relations($relationName, $where_query_params = [])
1458
+	{
1459
+		if ($relationName === 'Ticket') {
1460
+			$tickets = $this->tickets();
1461
+			foreach ($tickets as $ticket) {
1462
+				$this->decreaseSold($ticket->sold());
1463
+				$this->decreaseReserved($ticket->reserved());
1464
+				$this->save();
1465
+			}
1466
+		}
1467
+		return parent::_remove_relations($relationName, $where_query_params);
1468
+	}
1469
+
1470
+
1471
+	/*******************************************************************
1472 1472
      ***********************  DEPRECATED METHODS  **********************
1473 1473
      *******************************************************************/
1474 1474
 
1475 1475
 
1476
-    /**
1477
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
-     *
1479
-     * @deprecated 4.9.80.p
1480
-     * @param int $qty
1481
-     * @return boolean
1482
-     * @throws ReflectionException
1483
-     * @throws InvalidArgumentException
1484
-     * @throws InvalidInterfaceException
1485
-     * @throws InvalidDataTypeException
1486
-     * @throws EE_Error
1487
-     */
1488
-    public function increase_sold($qty = 1)
1489
-    {
1490
-        EE_Error::doing_it_wrong(
1491
-            __FUNCTION__,
1492
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
-            '4.9.80.p',
1494
-            '5.0.0.p'
1495
-        );
1496
-        return $this->increaseSold($qty);
1497
-    }
1498
-
1499
-
1500
-    /**
1501
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
-     * to save afterwards.)
1503
-     *
1504
-     * @deprecated 4.9.80.p
1505
-     * @param int $qty
1506
-     * @return boolean
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    public function decrease_sold($qty = 1)
1514
-    {
1515
-        EE_Error::doing_it_wrong(
1516
-            __FUNCTION__,
1517
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
-            '4.9.80.p',
1519
-            '5.0.0.p'
1520
-        );
1521
-        return $this->decreaseSold($qty);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
-     *
1528
-     * @deprecated 4.9.80.p
1529
-     * @param int $qty
1530
-     * @return boolean indicating success
1531
-     * @throws ReflectionException
1532
-     * @throws InvalidArgumentException
1533
-     * @throws InvalidInterfaceException
1534
-     * @throws InvalidDataTypeException
1535
-     * @throws EE_Error
1536
-     */
1537
-    public function increase_reserved($qty = 1)
1538
-    {
1539
-        EE_Error::doing_it_wrong(
1540
-            __FUNCTION__,
1541
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
-            '4.9.80.p',
1543
-            '5.0.0.p'
1544
-        );
1545
-        return $this->increaseReserved($qty);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
-     *
1552
-     * @deprecated 4.9.80.p
1553
-     * @param int $qty
1554
-     * @return boolean
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    public function decrease_reserved($qty = 1)
1562
-    {
1563
-        EE_Error::doing_it_wrong(
1564
-            __FUNCTION__,
1565
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
-            '4.9.80.p',
1567
-            '5.0.0.p'
1568
-        );
1569
-        return $this->decreaseReserved($qty);
1570
-    }
1476
+	/**
1477
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
+	 *
1479
+	 * @deprecated 4.9.80.p
1480
+	 * @param int $qty
1481
+	 * @return boolean
1482
+	 * @throws ReflectionException
1483
+	 * @throws InvalidArgumentException
1484
+	 * @throws InvalidInterfaceException
1485
+	 * @throws InvalidDataTypeException
1486
+	 * @throws EE_Error
1487
+	 */
1488
+	public function increase_sold($qty = 1)
1489
+	{
1490
+		EE_Error::doing_it_wrong(
1491
+			__FUNCTION__,
1492
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
+			'4.9.80.p',
1494
+			'5.0.0.p'
1495
+		);
1496
+		return $this->increaseSold($qty);
1497
+	}
1498
+
1499
+
1500
+	/**
1501
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
+	 * to save afterwards.)
1503
+	 *
1504
+	 * @deprecated 4.9.80.p
1505
+	 * @param int $qty
1506
+	 * @return boolean
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	public function decrease_sold($qty = 1)
1514
+	{
1515
+		EE_Error::doing_it_wrong(
1516
+			__FUNCTION__,
1517
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
+			'4.9.80.p',
1519
+			'5.0.0.p'
1520
+		);
1521
+		return $this->decreaseSold($qty);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
+	 *
1528
+	 * @deprecated 4.9.80.p
1529
+	 * @param int $qty
1530
+	 * @return boolean indicating success
1531
+	 * @throws ReflectionException
1532
+	 * @throws InvalidArgumentException
1533
+	 * @throws InvalidInterfaceException
1534
+	 * @throws InvalidDataTypeException
1535
+	 * @throws EE_Error
1536
+	 */
1537
+	public function increase_reserved($qty = 1)
1538
+	{
1539
+		EE_Error::doing_it_wrong(
1540
+			__FUNCTION__,
1541
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
+			'4.9.80.p',
1543
+			'5.0.0.p'
1544
+		);
1545
+		return $this->increaseReserved($qty);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
+	 *
1552
+	 * @deprecated 4.9.80.p
1553
+	 * @param int $qty
1554
+	 * @return boolean
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	public function decrease_reserved($qty = 1)
1562
+	{
1563
+		EE_Error::doing_it_wrong(
1564
+			__FUNCTION__,
1565
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
+			'4.9.80.p',
1567
+			'5.0.0.p'
1568
+		);
1569
+		return $this->decreaseReserved($qty);
1570
+	}
1571 1571
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_Data_Migration_Script_Base.core.php 2 patches
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
     public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
136 136
     {
137 137
         $this->_migration_stages = (array) apply_filters(
138
-            'FHEE__' . get_class($this) . '__construct__migration_stages',
138
+            'FHEE__'.get_class($this).'__construct__migration_stages',
139 139
             $this->_migration_stages
140 140
         );
141 141
         foreach ($this->_migration_stages as $migration_stage) {
@@ -170,10 +170,10 @@  discard block
 block discarded – undo
170 170
     public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171 171
     {
172 172
         // make sure it has the needed keys
173
-        if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
174
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
173
+        if ( ! isset($this->_mappings[$old_table]) || ! isset($this->_mappings[$old_table][$new_table])) {
174
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
175 175
         }
176
-        $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
176
+        $this->_mappings[$old_table][$new_table][$old_pk] = $new_pk;
177 177
     }
178 178
 
179 179
 
@@ -189,14 +189,14 @@  discard block
 block discarded – undo
189 189
     public function get_mapping_new_pk($old_table, $old_pk, $new_table)
190 190
     {
191 191
         if (
192
-            ! isset($this->_mappings[ $old_table ]) ||
193
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
192
+            ! isset($this->_mappings[$old_table]) ||
193
+            ! isset($this->_mappings[$old_table][$new_table])
194 194
         ) {
195 195
             // try fetching the option
196
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
196
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
197 197
         }
198
-        return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
199
-            ? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
198
+        return isset($this->_mappings[$old_table][$new_table][$old_pk])
199
+            ? $this->_mappings[$old_table][$new_table][$old_pk] : null;
200 200
     }
201 201
 
202 202
 
@@ -212,16 +212,16 @@  discard block
 block discarded – undo
212 212
     public function get_mapping_old_pk($old_table, $new_table, $new_pk)
213 213
     {
214 214
         if (
215
-            ! isset($this->_mappings[ $old_table ]) ||
216
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
215
+            ! isset($this->_mappings[$old_table]) ||
216
+            ! isset($this->_mappings[$old_table][$new_table])
217 217
         ) {
218 218
             // try fetching the option
219
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
219
+            $this->_mappings[$old_table][$new_table] = $this->_get_mapping_option($old_table, $new_table);
220 220
         }
221
-        if (isset($this->_mappings[ $old_table ][ $new_table ])) {
222
-            $new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
223
-            if (isset($new_pk_to_old_pk[ $new_pk ])) {
224
-                return $new_pk_to_old_pk[ $new_pk ];
221
+        if (isset($this->_mappings[$old_table][$new_table])) {
222
+            $new_pk_to_old_pk = array_flip($this->_mappings[$old_table][$new_table]);
223
+            if (isset($new_pk_to_old_pk[$new_pk])) {
224
+                return $new_pk_to_old_pk[$new_pk];
225 225
             }
226 226
         }
227 227
         return null;
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
         $new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
272 272
         $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
273 273
         return substr(
274
-            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
274
+            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix.$migrates_to ['slug'].'_'.$migrates_to['version'].'_'.$old_table_name_sans_wp.'_'.$new_table_name_sans_wp,
275 275
             0,
276 276
             64
277 277
         );
@@ -343,12 +343,12 @@  discard block
 block discarded – undo
343 343
                         $num_records_to_migrate_limit - $num_records_actually_migrated
344 344
                     );
345 345
                     $num_records_actually_migrated += $records_migrated_during_stage;
346
-                    $records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
346
+                    $records_migrated_per_stage[$stage->pretty_name()] = $records_migrated_during_stage;
347 347
                 } catch (Exception $e) {
348 348
                     // yes if we catch an exception here, we consider that migration stage borked.
349 349
                     $stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
350 350
                     $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
351
-                    $stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
351
+                    $stage->add_error($e->getMessage().". Stack-trace:".$e->getTraceAsString());
352 352
                     throw $e;
353 353
                 }
354 354
                 // check that the migration stage didn't mark itself as having a fatal error
@@ -421,8 +421,8 @@  discard block
 block discarded – undo
421 421
     private function _maybe_do_schema_changes($before = true)
422 422
     {
423 423
         // so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
424
-        $property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
425
-        if (! $this->{$property_name}) {
424
+        $property_name = '_schema_changes_'.($before ? 'before' : 'after').'_migration_ran';
425
+        if ( ! $this->{$property_name}) {
426 426
             try {
427 427
                 ob_start();
428 428
                 if ($before) {
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
         try {
660 660
             EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
661 661
         } catch (EE_Error $e) {
662
-            $message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
662
+            $message = $e->getMessage().'<br>Stack Trace:'.$e->getTraceAsString();
663 663
             $this->add_error($message);
664 664
             $this->_feedback_message .= $message;
665 665
         }
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
     public function get_errors()
706 706
     {
707 707
         $all_errors = $this->_errors;
708
-        if (! is_array($all_errors)) {
708
+        if ( ! is_array($all_errors)) {
709 709
             $all_errors = array();
710 710
         }
711 711
         foreach ($this->stages() as $stage) {
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
      */
740 740
     protected function stages()
741 741
     {
742
-        $stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
742
+        $stages = apply_filters('FHEE__'.get_class($this).'__stages', $this->_migration_stages);
743 743
         ksort($stages);
744 744
         return $stages;
745 745
     }
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         $properties = parent::properties_as_array();
769 769
         $properties['_migration_stages'] = array();
770 770
         foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
771
-            $properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
771
+            $properties['_migration_stages'][$migration_stage_priority] = $migration_stage_class->properties_as_array(
772 772
             );
773 773
         }
774 774
         unset($properties['_mappings']);
Please login to merge, or discard this patch.
Indentation   +914 added lines, -914 removed lines patch added patch discarded remove patch
@@ -14,918 +14,918 @@
 block discarded – undo
14 14
  */
15 15
 abstract class EE_Data_Migration_Script_Base extends EE_Data_Migration_Class_Base
16 16
 {
17
-    /**
18
-     * Set by client code to indicate this DMS is being ran as part of a proper migration,
19
-     * instead of being used to merely setup (or verify) the database structure.
20
-     * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
21
-     * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
22
-     *
23
-     * @var boolean
24
-     */
25
-    protected $_migrating = true;
26
-
27
-    /**
28
-     * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
29
-     *
30
-     * @var EE_Data_Migration_Script_Stage[] $migration_functions
31
-     */
32
-    protected $_migration_stages = array();
33
-
34
-    /**
35
-     * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
36
-     *
37
-     * @var boolean
38
-     */
39
-    protected $_schema_changes_before_migration_ran = null;
40
-
41
-    /**
42
-     * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected $_schema_changes_after_migration_ran = null;
47
-
48
-    /**
49
-     * String which describes what's currently happening in this migration
50
-     *
51
-     * @var string
52
-     */
53
-    protected $_feedback_message;
54
-
55
-    /**
56
-     * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
57
-     * correspond to earlier execution
58
-     *
59
-     * @var int
60
-     */
61
-    protected $_priority = 5;
62
-
63
-    /**
64
-     * Multi-dimensional array that defines the mapping from OLD table Primary Keys
65
-     * to NEW table Primary Keys.
66
-     * Top-level array keys are OLD table names (minus the "wp_" part),
67
-     * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
68
-     * 3rd-level array keys are the OLD table primary keys
69
-     * and 3rd-level array values are the NEW table primary keys
70
-     *
71
-     * @var array
72
-     */
73
-    protected $_mappings = array();
74
-
75
-    /**
76
-     * @var EE_Data_Migration_Script_Base
77
-     */
78
-    protected $previous_dms;
79
-
80
-
81
-    /**
82
-     * Returns whether or not this data migration script can operate on the given version of the database.
83
-     * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
84
-     * it's passed a string like '3.1.38B', it should return true.
85
-     * If this DMS is to migrate data from an EE3 addon, you will probably want to use
86
-     * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
87
-     * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
88
-     * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
89
-     * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
90
-     * to run this DMS).
91
-     * If this DMS migrates data from a previous version of this EE4 addon, just
92
-     * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
93
-     * If this DMS should never migrate data, because it's only used to define the initial
94
-     * database state, just return FALSE (and core's activation process will take care
95
-     * of calling its schema_changes_before_migration() and
96
-     * schema_changes_after_migration() for you. )
97
-     *
98
-     * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
99
-     * @return boolean
100
-     */
101
-    abstract public function can_migrate_from_version($current_database_state_of);
102
-
103
-
104
-    /**
105
-     * Performs database schema changes that need to occur BEFORE the data is migrated.
106
-     * Eg, if we were going to change user passwords from plaintext to encoded versions
107
-     * during this migration, this would probably add a new column called something like
108
-     * "encoded_password".
109
-     *
110
-     * @return boolean of success
111
-     */
112
-    abstract public function schema_changes_before_migration();
113
-
114
-
115
-    /**
116
-     * Performs the database schema changes that need to occur AFTER the data has been migrated.
117
-     * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
118
-     * from plaintext to encoded versions, and we had added a column called "encoded_password",
119
-     * this function would probably remove the old column "password" (which still holds the plaintext password)
120
-     * and possibly rename "encoded_password" to "password"
121
-     *
122
-     * @return boolean of success
123
-     */
124
-    abstract public function schema_changes_after_migration();
125
-
126
-
127
-    /**
128
-     * All children of this must call parent::__construct()
129
-     * at the end of their constructor or suffer the consequences!
130
-     *
131
-     * @param TableManager  $table_manager
132
-     * @param TableAnalysis $table_analysis
133
-     */
134
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
135
-    {
136
-        $this->_migration_stages = (array) apply_filters(
137
-            'FHEE__' . get_class($this) . '__construct__migration_stages',
138
-            $this->_migration_stages
139
-        );
140
-        foreach ($this->_migration_stages as $migration_stage) {
141
-            if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
142
-                $migration_stage->_construct_finalize($this);
143
-            }
144
-        }
145
-        parent::__construct($table_manager, $table_analysis);
146
-    }
147
-
148
-
149
-    /**
150
-     * Place to add hooks and filters for tweaking the migrations page, in order
151
-     * to customize it
152
-     */
153
-    public function migration_page_hooks()
154
-    {
155
-        // by default none are added because we normally like the default look of the migration page
156
-    }
157
-
158
-
159
-    /**
160
-     * Sets the mapping from old table primary keys to new table primary keys.
161
-     * This mapping is automatically persisted as a property on the migration
162
-     *
163
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
164
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
165
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
166
-     * @param int|string $new_pk    eg posts.ID
167
-     * @return void
168
-     * @throws EE_Error
169
-     */
170
-    public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171
-    {
172
-        // make sure it has the needed keys
173
-        if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
174
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
175
-        }
176
-        $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
177
-    }
178
-
179
-
180
-    /**
181
-     * Gets the new primary key, if provided with the OLD table and the primary key
182
-     * of an item in the old table, and the new table
183
-     *
184
-     * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
185
-     * @param int|string $old_pk    old primary key. Eg events_detail.id's value
186
-     * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
187
-     * @return mixed the primary key on the new table
188
-     * @throws EE_Error
189
-     */
190
-    public function get_mapping_new_pk($old_table, $old_pk, $new_table)
191
-    {
192
-        if (
193
-            ! isset($this->_mappings[ $old_table ]) ||
194
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
195
-        ) {
196
-            // try fetching the option
197
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
198
-        }
199
-        return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
200
-            ? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
201
-    }
202
-
203
-
204
-    /**
205
-     * Gets the old primary key, if provided with the OLD table,
206
-     * and the new table and the primary key of an item in the new table
207
-     *
208
-     * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
209
-     * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
210
-     * @param mixed  $new_pk
211
-     * @return mixed
212
-     * @throws EE_Error
213
-     */
214
-    public function get_mapping_old_pk($old_table, $new_table, $new_pk)
215
-    {
216
-        if (
217
-            ! isset($this->_mappings[ $old_table ]) ||
218
-            ! isset($this->_mappings[ $old_table ][ $new_table ])
219
-        ) {
220
-            // try fetching the option
221
-            $this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
222
-        }
223
-        if (isset($this->_mappings[ $old_table ][ $new_table ])) {
224
-            $new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
225
-            if (isset($new_pk_to_old_pk[ $new_pk ])) {
226
-                return $new_pk_to_old_pk[ $new_pk ];
227
-            }
228
-        }
229
-        return null;
230
-    }
231
-
232
-
233
-    /**
234
-     * Gets the mapping array option specified by the table names
235
-     *
236
-     * @param string $old_table_name
237
-     * @param string $new_table_name
238
-     * @return array
239
-     * @throws EE_Error
240
-     */
241
-    protected function _get_mapping_option($old_table_name, $new_table_name)
242
-    {
243
-        return get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
244
-    }
245
-
246
-
247
-    /**
248
-     * Updates the mapping option specified by the table names with the array provided
249
-     *
250
-     * @param string $old_table_name
251
-     * @param string $new_table_name
252
-     * @param array  $mapping_array
253
-     * @return boolean success of updating option
254
-     * @throws EE_Error
255
-     */
256
-    protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
257
-    {
258
-        $success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
259
-        return $success;
260
-    }
261
-
262
-
263
-    /**
264
-     * Gets the option name for this script to map from $old_table_name to $new_table_name
265
-     *
266
-     * @param string $old_table_name
267
-     * @param string $new_table_name
268
-     * @return string
269
-     * @throws EE_Error
270
-     */
271
-    protected function _get_mapping_option_name($old_table_name, $new_table_name)
272
-    {
273
-        global $wpdb;
274
-        $old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
275
-        $new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
276
-        $migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
277
-        return substr(
278
-            EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
279
-            0,
280
-            64
281
-        );
282
-    }
283
-
284
-
285
-    /**
286
-     * Counts all the records that will be migrated during this data migration.
287
-     * For example, if we were changing old user passwords from plaintext to encoded versions,
288
-     * this would be a count of all users who have passwords. If we were going to also split
289
-     * attendee records into transactions, registrations, and attendee records, this would include
290
-     * the count of all attendees currently in existence in the DB (ie, users + attendees).
291
-     * If you can't determine how many records there are to migrate, just provide a guess: this
292
-     * number will only be used in calculating the percent complete. If you estimate there to be
293
-     * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
294
-     * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
295
-     *
296
-     * @return int
297
-     */
298
-    protected function _count_records_to_migrate()
299
-    {
300
-        $count = 0;
301
-        foreach ($this->stages() as $stage) {
302
-            $count += $stage->count_records_to_migrate();
303
-        }
304
-        return $count;
305
-    }
306
-
307
-
308
-    /**
309
-     * Returns the number of records updated so far. Usually this is easiest to do
310
-     * by just setting a transient and updating it after each migration_step
311
-     *
312
-     * @return int
313
-     */
314
-    public function count_records_migrated()
315
-    {
316
-        $count = 0;
317
-        foreach ($this->stages() as $stage) {
318
-            $count += $stage->count_records_migrated();
319
-        }
320
-        $this->_records_migrated = $count;
321
-        return $count;
322
-    }
323
-
324
-
325
-    /**
326
-     * @param int $num_records_to_migrate_limit
327
-     * @return int
328
-     * @throws EE_Error
329
-     * @throws Exception
330
-     */
331
-    public function migration_step($num_records_to_migrate_limit)
332
-    {
333
-        // reset the feedback message
334
-        $this->_feedback_message = '';
335
-        // if we haven't yet done the 1st schema changes, do them now. buffer any output
336
-        $this->_maybe_do_schema_changes(true);
337
-
338
-        $num_records_actually_migrated = 0;
339
-        $records_migrated_per_stage = array();
340
-        // setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
341
-        $stage = null;
342
-        // get the next stage that isn't complete
343
-        foreach ($this->stages() as $stage) {
344
-            if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
345
-                try {
346
-                    $records_migrated_during_stage = $stage->migration_step(
347
-                        $num_records_to_migrate_limit - $num_records_actually_migrated
348
-                    );
349
-                    $num_records_actually_migrated += $records_migrated_during_stage;
350
-                    $records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
351
-                } catch (Exception $e) {
352
-                    // yes if we catch an exception here, we consider that migration stage borked.
353
-                    $stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
354
-                    $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
355
-                    $stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
356
-                    throw $e;
357
-                }
358
-                // check that the migration stage didn't mark itself as having a fatal error
359
-                if ($stage->is_broken()) {
360
-                    $this->set_broken();
361
-                    throw new EE_Error($stage->get_last_error());
362
-                }
363
-            }
364
-            // once we've migrated all the number we intended to (possibly from different stages), stop migrating
365
-            // or if we had a fatal error
366
-            // or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
367
-            if (
368
-                $num_records_actually_migrated >= $num_records_to_migrate_limit
369
-                || $stage->is_broken()
370
-                || $stage->has_more_to_do()
371
-            ) {
372
-                break;
373
-            }
374
-        }
375
-        // check if we're all done this data migration...
376
-        // which is indicated by being done early AND the last stage claims to be done
377
-        if ($stage == null) {
378
-            // this migration script apparently has NO stages... which is super weird, but whatever
379
-            $this->set_completed();
380
-            $this->_maybe_do_schema_changes(false);
381
-        } elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
382
-            // apparently we're done, because we couldn't migrate the number we intended to
383
-            $this->set_completed();
384
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
385
-            // do schema changes for after the migration now
386
-            // first double-check we haven't already done this
387
-            $this->_maybe_do_schema_changes(false);
388
-        } else {
389
-            // update feedback message, keeping in mind that we show them with the most recent at the top
390
-            $this->_update_feedback_message(array_reverse($records_migrated_per_stage));
391
-        }
392
-        return $num_records_actually_migrated;
393
-    }
394
-
395
-
396
-    /**
397
-     * Updates the feedback message according to what was done during this migration stage.
398
-     *
399
-     * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
400
-     *                                          migrated from that stage
401
-     * @return void
402
-     */
403
-    private function _update_feedback_message($records_migrated_per_stage)
404
-    {
405
-        $feedback_message_array = array();
406
-        foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
407
-            $feedback_message_array[] = sprintf(
408
-                esc_html__("Migrated %d records successfully during %s", "event_espresso"),
409
-                $num_records_migrated,
410
-                $migration_stage_name
411
-            );
412
-        }
413
-        $this->_feedback_message .= implode("<br>", $feedback_message_array);
414
-    }
415
-
416
-
417
-    /**
418
-     * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
419
-     * (if $before==false). Buffers their outputs and stores them on the class.
420
-     *
421
-     * @param boolean $before
422
-     * @throws Exception
423
-     * @return void
424
-     */
425
-    private function _maybe_do_schema_changes($before = true)
426
-    {
427
-        // so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
428
-        $property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
429
-        if (! $this->{$property_name}) {
430
-            try {
431
-                ob_start();
432
-                if ($before) {
433
-                    $this->schema_changes_before_migration();
434
-                } else {
435
-                    $this->schema_changes_after_migration();
436
-                }
437
-                $output = ob_get_contents();
438
-                ob_end_clean();
439
-            } catch (Exception $e) {
440
-                $this->set_status(EE_Data_Migration_Manager::status_fatal_error);
441
-                throw $e;
442
-            }
443
-            // record that we've done these schema changes
444
-            $this->{$property_name} = true;
445
-            // if there were any warnings etc, record them as non-fatal errors
446
-            if ($output) {
447
-                // there were some warnings
448
-                $this->_errors[] = $output;
449
-            }
450
-        }
451
-    }
452
-
453
-
454
-    /**
455
-     * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
456
-     * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
457
-     * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
458
-     * or
459
-     * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
460
-     * not
461
-     * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
462
-     * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
463
-     * should be nuked.
464
-     *
465
-     * Just for a bit of context, the migration script's db_schema_changes_* methods
466
-     * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
467
-     * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
468
-     * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
469
-     * be dropped), and during a migration when we're moving the DB to the state of the migration script
470
-     *
471
-     * @param string $table_name
472
-     * @param string $table_definition_sql
473
-     * @param string $engine_string
474
-     * @throws EE_Error
475
-     * @throws ReflectionException
476
-     */
477
-    protected function _table_is_new_in_this_version(
478
-        $table_name,
479
-        $table_definition_sql,
480
-        $engine_string = 'ENGINE=InnoDB '
481
-    ) {
482
-        $this->_create_table_and_catch_errors(
483
-            $table_name,
484
-            $table_definition_sql,
485
-            $engine_string,
486
-            $this->_pre_existing_table_should_be_dropped(true)
487
-        );
488
-    }
489
-
490
-
491
-    /**
492
-     * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
493
-     * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
494
-     * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
495
-     * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
496
-     * _table_should_exist_previously.
497
-     * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
498
-     * table shouldn't exist).
499
-     *
500
-     * @param string $table_name
501
-     * @param string $table_definition_sql
502
-     * @param string $engine_string
503
-     * @throws EE_Error
504
-     * @throws ReflectionException
505
-     */
506
-    protected function _table_is_changed_in_this_version(
507
-        $table_name,
508
-        $table_definition_sql,
509
-        $engine_string = 'ENGINE=MyISAM'
510
-    ) {
511
-        $this->_create_table_and_catch_errors(
512
-            $table_name,
513
-            $table_definition_sql,
514
-            $engine_string,
515
-            $this->_pre_existing_table_should_be_dropped(false)
516
-        );
517
-    }
518
-
519
-
520
-    /**
521
-     * _old_table_exists
522
-     * returns TRUE if the requested table exists in the current database
523
-     *
524
-     * @param string $table_name
525
-     * @return boolean
526
-     * @throws EE_Error
527
-     */
528
-    protected function _old_table_exists($table_name)
529
-    {
530
-        return $this->_get_table_analysis()->tableExists($table_name);
531
-    }
532
-
533
-
534
-    /**
535
-     * _delete_table_if_empty
536
-     * returns TRUE if the requested table was empty and successfully empty
537
-     *
538
-     * @param string $table_name
539
-     * @return boolean
540
-     * @throws EE_Error
541
-     * @throws ReflectionException
542
-     */
543
-    protected function _delete_table_if_empty($table_name)
544
-    {
545
-        return EEH_Activation::delete_db_table_if_empty($table_name);
546
-    }
547
-
548
-
549
-    /**
550
-     * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
551
-     * as these are significantly more efficient or explicit.
552
-     * Please see description of _table_is_new_in_this_version. This function will only set
553
-     * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
554
-     * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
555
-     * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
556
-     * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
557
-     * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
558
-     * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
559
-     * because apparently it hasn't changed since the previous one, right?
560
-     *
561
-     * @param string $table_name
562
-     * @param string $table_definition_sql
563
-     * @param string $engine_string
564
-     * @throws EE_Error
565
-     * @throws ReflectionException
566
-     */
567
-    protected function _table_should_exist_previously(
568
-        $table_name,
569
-        $table_definition_sql,
570
-        $engine_string = 'ENGINE=MyISAM'
571
-    ) {
572
-        $this->_create_table_and_catch_errors(
573
-            $table_name,
574
-            $table_definition_sql,
575
-            $engine_string,
576
-            $this->_pre_existing_table_should_be_dropped(false)
577
-        );
578
-    }
579
-
580
-
581
-    /**
582
-     * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
583
-     * a migration, we skip checking this table's structure in the database and just assume it's correct.
584
-     * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
585
-     * but important for multisite where migrations can take a very long time otherwise).
586
-     * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
587
-     * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
588
-     * shouldn't exist).
589
-     *
590
-     * @param string $table_name
591
-     * @param string $table_definition_sql
592
-     * @param string $engine_string
593
-     * @throws EE_Error
594
-     * @throws ReflectionException
595
-     */
596
-    protected function _table_has_not_changed_since_previous(
597
-        $table_name,
598
-        $table_definition_sql,
599
-        $engine_string = 'ENGINE=MyISAM'
600
-    ) {
601
-        if ($this->_currently_migrating()) {
602
-            // if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
603
-            return;
604
-        }
605
-        $this->_create_table_and_catch_errors(
606
-            $table_name,
607
-            $table_definition_sql,
608
-            $engine_string,
609
-            $this->_pre_existing_table_should_be_dropped(false)
610
-        );
611
-    }
612
-
613
-    /**
614
-     * Returns whether or not this migration script is being used as part of an actual migration
615
-     *
616
-     * @return boolean
617
-     */
618
-    protected function _currently_migrating()
619
-    {
620
-        // we want to know if we are currently performing a migration. We could just believe what was set on the _migrating property, but let's double-check (ie the script should apply and we should be in MM)
621
-        return $this->_migrating &&
622
-               $this->can_migrate_from_version(
623
-                   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
624
-               ) &&
625
-               EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
626
-    }
627
-
628
-
629
-    /**
630
-     * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
631
-     * and the plugin's request type.
632
-     * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
633
-     * shouldn't exist no matter what).
634
-     *
635
-     * @param boolean $table_is_new
636
-     * @return boolean
637
-     * @throws EE_Error
638
-     */
639
-    protected function _pre_existing_table_should_be_dropped($table_is_new)
640
-    {
641
-        if ($table_is_new) {
642
-            if (
643
-                $this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
644
-                || $this->_currently_migrating()
645
-            ) {
646
-                return true;
647
-            } else {
648
-                return false;
649
-            }
650
-        } else {
651
-            if (
652
-                in_array(
653
-                    $this->_get_req_type_for_plugin_corresponding_to_this_dms(),
654
-                    array(EE_System::req_type_new_activation)
655
-                )
656
-            ) {
657
-                return true;
658
-            } else {
659
-                return false;
660
-            }
661
-        }
662
-    }
663
-
664
-
665
-    /**
666
-     * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
667
-     *
668
-     * @param string  $table_name
669
-     * @param string  $table_definition_sql
670
-     * @param string  $engine_string
671
-     * @param boolean $drop_pre_existing_tables
672
-     * @throws ReflectionException
673
-     */
674
-    private function _create_table_and_catch_errors(
675
-        $table_name,
676
-        $table_definition_sql,
677
-        $engine_string = 'ENGINE=MyISAM',
678
-        $drop_pre_existing_tables = false
679
-    ) {
680
-        try {
681
-            EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
682
-        } catch (EE_Error $e) {
683
-            $message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
684
-            $this->add_error($message);
685
-            $this->_feedback_message .= $message;
686
-        }
687
-    }
688
-
689
-
690
-    /**
691
-     * Gets the request type for the plugin (core or addon) that corresponds to this DMS
692
-     *
693
-     * @return int one of EE_System::_req_type_* constants
694
-     * @throws EE_Error
695
-     */
696
-    private function _get_req_type_for_plugin_corresponding_to_this_dms()
697
-    {
698
-        if ($this->slug() == 'Core') {
699
-            return EE_System::instance()->detect_req_type();
700
-        } else {// it must be for an addon
701
-            $addon_name = $this->slug();
702
-            if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
703
-                return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
704
-            } else {
705
-                throw new EE_Error(
706
-                    sprintf(
707
-                        esc_html__(
708
-                            "The DMS slug '%s' should correspond to the addon's name, which should also be '%s', but no such addon was registered. These are the registered addons' names: %s",
709
-                            "event_espresso"
710
-                        ),
711
-                        $this->slug(),
712
-                        $addon_name,
713
-                        implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
714
-                    )
715
-                );
716
-            }
717
-        }
718
-    }
719
-
720
-
721
-    /**
722
-     * returns an array of strings describing errors by all the script's stages
723
-     *
724
-     * @return array
725
-     */
726
-    public function get_errors()
727
-    {
728
-        $all_errors = $this->_errors;
729
-        if (! is_array($all_errors)) {
730
-            $all_errors = array();
731
-        }
732
-        foreach ($this->stages() as $stage) {
733
-            $all_errors = array_merge($stage->get_errors(), $all_errors);
734
-        }
735
-        return $all_errors;
736
-    }
737
-
738
-
739
-    /**
740
-     * Indicates whether or not this migration script should continue
741
-     *
742
-     * @return boolean
743
-     */
744
-    public function can_continue()
745
-    {
746
-        return in_array(
747
-            $this->get_status(),
748
-            EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
749
-        );
750
-    }
751
-
752
-
753
-    /**
754
-     * Gets all the data migration stages associated with this script. Note:
755
-     * addons can filter this list to add their own stages, and because the list is
756
-     * numerically-indexed, they can insert their stage wherever they like and it will
757
-     * get ordered by the indexes
758
-     *
759
-     * @return EE_Data_Migration_Script_Stage[]
760
-     */
761
-    protected function stages()
762
-    {
763
-        $stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
764
-        ksort($stages);
765
-        return $stages;
766
-    }
767
-
768
-
769
-    /**
770
-     * Gets a string which should describe what's going on currently with this migration, which
771
-     * can be displayed to the user
772
-     *
773
-     * @return string
774
-     */
775
-    public function get_feedback_message()
776
-    {
777
-        return $this->_feedback_message;
778
-    }
779
-
780
-
781
-    /**
782
-     * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
783
-     * properties to the DB. However, we don't want to use __sleep() because its quite
784
-     * possible that this class is defined when it goes to sleep, but NOT available when it
785
-     * awakes (eg, this class is part of an addon that is deactivated at some point).
786
-     */
787
-    public function properties_as_array()
788
-    {
789
-        $properties = parent::properties_as_array();
790
-        $properties['_migration_stages'] = array();
791
-        foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
792
-            $properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
793
-            );
794
-        }
795
-        unset($properties['_mappings']);
796
-        unset($properties['previous_dms']);
797
-
798
-        foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
799
-            foreach ($mapping_to_new_table as $new_table_name => $mapping) {
800
-                $this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
801
-            }
802
-        }
803
-        return $properties;
804
-    }
805
-
806
-
807
-    /**
808
-     * Sets all of the properties of this script stage to match what's in the array, which is assumed
809
-     * to have been made from the properties_as_array() function.
810
-     *
811
-     * @param array $array_of_properties like what's produced from properties_as_array() method
812
-     * @return void
813
-     */
814
-    public function instantiate_from_array_of_properties($array_of_properties)
815
-    {
816
-        $stages_properties_arrays = $array_of_properties['_migration_stages'];
817
-        unset($array_of_properties['_migration_stages']);
818
-        unset($array_of_properties['class']);
819
-        foreach ($array_of_properties as $property_name => $property_value) {
820
-            $this->{$property_name} = $property_value;
821
-        }
822
-        // _migration_stages are already instantiated, but have only default data
823
-        foreach ($this->_migration_stages as $stage) {
824
-            $stage_data = $this->_find_migration_stage_data_with_classname(
825
-                get_class($stage),
826
-                $stages_properties_arrays
827
-            );
828
-            // SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
829
-            // an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
830
-            if ($stage_data) {
831
-                $stage->instantiate_from_array_of_properties($stage_data);
832
-            }
833
-        }
834
-    }
835
-
836
-
837
-    /**
838
-     * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
839
-     * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
840
-     * for the given classname
841
-     *
842
-     * @param string $classname
843
-     * @param array  $migration_stage_data_arrays
844
-     * @return null
845
-     */
846
-    private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
847
-    {
848
-        foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
849
-            if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
850
-                return $migration_stage_data_array;
851
-            }
852
-        }
853
-        return null;
854
-    }
855
-
856
-
857
-    /**
858
-     * Returns the version that this script migrates to, based on the script's name.
859
-     * Cannot be overwritten because lots of code needs to know which version a script
860
-     * migrates to knowing only its name.
861
-     *
862
-     * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
863
-     * that will be updated to. Eg array('Core','4.1.0')
864
-     * @throws EE_Error
865
-     */
866
-    final public function migrates_to_version()
867
-    {
868
-        return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
869
-    }
870
-
871
-
872
-    /**
873
-     * Gets this addon's slug as it would appear in the current_db_state wp option,
874
-     * and if this migration script is for an addon, it SHOULD match the addon's slug
875
-     * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
876
-     * Or 'Core' for core (non-addon).
877
-     *
878
-     * @return string
879
-     * @throws EE_Error
880
-     */
881
-    public function slug()
882
-    {
883
-        $migrates_to_version_info = $this->migrates_to_version();
884
-        // the slug is the first part of the array
885
-        return $migrates_to_version_info['slug'];
886
-    }
887
-
888
-
889
-    /**
890
-     * Returns the script's priority relative to DMSs from other addons. However, when
891
-     * two DMSs from the same addon/core apply, this is ignored (and instead the version that
892
-     * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
893
-     * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
894
-     * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
895
-     * the database up so it can run), then you can set "A" to priority 3 or something.
896
-     *
897
-     * @return int
898
-     */
899
-    public function priority()
900
-    {
901
-        return $this->_priority;
902
-    }
903
-
904
-
905
-    /**
906
-     * Sets whether or not this DMS is being ran as part of a migration, instead of
907
-     * just being used to setup (or verify) the current database structure matches
908
-     * what the latest DMS indicates it should be
909
-     *
910
-     * @param boolean $migrating
911
-     * @return void
912
-     */
913
-    public function set_migrating($migrating = true)
914
-    {
915
-        $this->_migrating = $migrating;
916
-    }
917
-
918
-    /**
919
-     * Marks that we think this migration class can continue to migrate
920
-     */
921
-    public function reattempt()
922
-    {
923
-        parent::reattempt();
924
-        // also, we want to reattempt any stages that were marked as borked
925
-        foreach ($this->stages() as $stage) {
926
-            if ($stage->is_broken()) {
927
-                $stage->reattempt();
928
-            }
929
-        }
930
-    }
17
+	/**
18
+	 * Set by client code to indicate this DMS is being ran as part of a proper migration,
19
+	 * instead of being used to merely setup (or verify) the database structure.
20
+	 * Defaults to TRUE, so client code that's NOT using this DMS as part of a proper migration
21
+	 * should call EE_Data_Migration_Script_Base::set_migrating( FALSE )
22
+	 *
23
+	 * @var boolean
24
+	 */
25
+	protected $_migrating = true;
26
+
27
+	/**
28
+	 * numerically-indexed array where each value is EE_Data_Migration_Script_Stage object
29
+	 *
30
+	 * @var EE_Data_Migration_Script_Stage[] $migration_functions
31
+	 */
32
+	protected $_migration_stages = array();
33
+
34
+	/**
35
+	 * Indicates we've already ran the schema changes that needed to happen BEFORE the data migration
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	protected $_schema_changes_before_migration_ran = null;
40
+
41
+	/**
42
+	 * Indicates we've already ran the schema changes that needed to happen AFTER the data migration
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected $_schema_changes_after_migration_ran = null;
47
+
48
+	/**
49
+	 * String which describes what's currently happening in this migration
50
+	 *
51
+	 * @var string
52
+	 */
53
+	protected $_feedback_message;
54
+
55
+	/**
56
+	 * Indicates the script's priority. Like wp's add_action and add_filter, lower numbers
57
+	 * correspond to earlier execution
58
+	 *
59
+	 * @var int
60
+	 */
61
+	protected $_priority = 5;
62
+
63
+	/**
64
+	 * Multi-dimensional array that defines the mapping from OLD table Primary Keys
65
+	 * to NEW table Primary Keys.
66
+	 * Top-level array keys are OLD table names (minus the "wp_" part),
67
+	 * 2nd-level array keys are NEW table names (again, minus the "wp_" part),
68
+	 * 3rd-level array keys are the OLD table primary keys
69
+	 * and 3rd-level array values are the NEW table primary keys
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $_mappings = array();
74
+
75
+	/**
76
+	 * @var EE_Data_Migration_Script_Base
77
+	 */
78
+	protected $previous_dms;
79
+
80
+
81
+	/**
82
+	 * Returns whether or not this data migration script can operate on the given version of the database.
83
+	 * Eg, if this migration script can migrate from 3.1.26 or higher (but not anything after 4.0.0), and
84
+	 * it's passed a string like '3.1.38B', it should return true.
85
+	 * If this DMS is to migrate data from an EE3 addon, you will probably want to use
86
+	 * EventEspresso\core\services\database\TableAnalysis::tableExists() to check for old EE3 tables, and
87
+	 * EE_Data_Migration_Manager::get_migration_ran() to check that core was already
88
+	 * migrated from EE3 to EE4 (ie, this DMS probably relies on some migration data generated
89
+	 * during the Core 4.1.0 DMS. If core didn't run that DMS, you probably don't want
90
+	 * to run this DMS).
91
+	 * If this DMS migrates data from a previous version of this EE4 addon, just
92
+	 * comparing $current_database_state_of[ $this->slug() ] will probably suffice.
93
+	 * If this DMS should never migrate data, because it's only used to define the initial
94
+	 * database state, just return FALSE (and core's activation process will take care
95
+	 * of calling its schema_changes_before_migration() and
96
+	 * schema_changes_after_migration() for you. )
97
+	 *
98
+	 * @param array $current_database_state_of keys are EE plugin slugs (eg 'Core', 'Calendar', 'Mailchimp', etc)
99
+	 * @return boolean
100
+	 */
101
+	abstract public function can_migrate_from_version($current_database_state_of);
102
+
103
+
104
+	/**
105
+	 * Performs database schema changes that need to occur BEFORE the data is migrated.
106
+	 * Eg, if we were going to change user passwords from plaintext to encoded versions
107
+	 * during this migration, this would probably add a new column called something like
108
+	 * "encoded_password".
109
+	 *
110
+	 * @return boolean of success
111
+	 */
112
+	abstract public function schema_changes_before_migration();
113
+
114
+
115
+	/**
116
+	 * Performs the database schema changes that need to occur AFTER the data has been migrated.
117
+	 * Usually this will mean we'll be removing old columns. Eg, if we were changing passwords
118
+	 * from plaintext to encoded versions, and we had added a column called "encoded_password",
119
+	 * this function would probably remove the old column "password" (which still holds the plaintext password)
120
+	 * and possibly rename "encoded_password" to "password"
121
+	 *
122
+	 * @return boolean of success
123
+	 */
124
+	abstract public function schema_changes_after_migration();
125
+
126
+
127
+	/**
128
+	 * All children of this must call parent::__construct()
129
+	 * at the end of their constructor or suffer the consequences!
130
+	 *
131
+	 * @param TableManager  $table_manager
132
+	 * @param TableAnalysis $table_analysis
133
+	 */
134
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
135
+	{
136
+		$this->_migration_stages = (array) apply_filters(
137
+			'FHEE__' . get_class($this) . '__construct__migration_stages',
138
+			$this->_migration_stages
139
+		);
140
+		foreach ($this->_migration_stages as $migration_stage) {
141
+			if ($migration_stage instanceof EE_Data_Migration_Script_Stage) {
142
+				$migration_stage->_construct_finalize($this);
143
+			}
144
+		}
145
+		parent::__construct($table_manager, $table_analysis);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Place to add hooks and filters for tweaking the migrations page, in order
151
+	 * to customize it
152
+	 */
153
+	public function migration_page_hooks()
154
+	{
155
+		// by default none are added because we normally like the default look of the migration page
156
+	}
157
+
158
+
159
+	/**
160
+	 * Sets the mapping from old table primary keys to new table primary keys.
161
+	 * This mapping is automatically persisted as a property on the migration
162
+	 *
163
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
164
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
165
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
166
+	 * @param int|string $new_pk    eg posts.ID
167
+	 * @return void
168
+	 * @throws EE_Error
169
+	 */
170
+	public function set_mapping($old_table, $old_pk, $new_table, $new_pk)
171
+	{
172
+		// make sure it has the needed keys
173
+		if (! isset($this->_mappings[ $old_table ]) || ! isset($this->_mappings[ $old_table ][ $new_table ])) {
174
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
175
+		}
176
+		$this->_mappings[ $old_table ][ $new_table ][ $old_pk ] = $new_pk;
177
+	}
178
+
179
+
180
+	/**
181
+	 * Gets the new primary key, if provided with the OLD table and the primary key
182
+	 * of an item in the old table, and the new table
183
+	 *
184
+	 * @param string     $old_table with wpdb prefix (wp_). Eg: wp_events_detail
185
+	 * @param int|string $old_pk    old primary key. Eg events_detail.id's value
186
+	 * @param string     $new_table with wpdb prefix (wp_). Eg: wp_posts
187
+	 * @return mixed the primary key on the new table
188
+	 * @throws EE_Error
189
+	 */
190
+	public function get_mapping_new_pk($old_table, $old_pk, $new_table)
191
+	{
192
+		if (
193
+			! isset($this->_mappings[ $old_table ]) ||
194
+			! isset($this->_mappings[ $old_table ][ $new_table ])
195
+		) {
196
+			// try fetching the option
197
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
198
+		}
199
+		return isset($this->_mappings[ $old_table ][ $new_table ][ $old_pk ])
200
+			? $this->_mappings[ $old_table ][ $new_table ][ $old_pk ] : null;
201
+	}
202
+
203
+
204
+	/**
205
+	 * Gets the old primary key, if provided with the OLD table,
206
+	 * and the new table and the primary key of an item in the new table
207
+	 *
208
+	 * @param string $old_table with wpdb prefix (wp_). Eg: wp_events_detail
209
+	 * @param string $new_table with wpdb prefix (wp_). Eg: wp_posts
210
+	 * @param mixed  $new_pk
211
+	 * @return mixed
212
+	 * @throws EE_Error
213
+	 */
214
+	public function get_mapping_old_pk($old_table, $new_table, $new_pk)
215
+	{
216
+		if (
217
+			! isset($this->_mappings[ $old_table ]) ||
218
+			! isset($this->_mappings[ $old_table ][ $new_table ])
219
+		) {
220
+			// try fetching the option
221
+			$this->_mappings[ $old_table ][ $new_table ] = $this->_get_mapping_option($old_table, $new_table);
222
+		}
223
+		if (isset($this->_mappings[ $old_table ][ $new_table ])) {
224
+			$new_pk_to_old_pk = array_flip($this->_mappings[ $old_table ][ $new_table ]);
225
+			if (isset($new_pk_to_old_pk[ $new_pk ])) {
226
+				return $new_pk_to_old_pk[ $new_pk ];
227
+			}
228
+		}
229
+		return null;
230
+	}
231
+
232
+
233
+	/**
234
+	 * Gets the mapping array option specified by the table names
235
+	 *
236
+	 * @param string $old_table_name
237
+	 * @param string $new_table_name
238
+	 * @return array
239
+	 * @throws EE_Error
240
+	 */
241
+	protected function _get_mapping_option($old_table_name, $new_table_name)
242
+	{
243
+		return get_option($this->_get_mapping_option_name($old_table_name, $new_table_name), array());
244
+	}
245
+
246
+
247
+	/**
248
+	 * Updates the mapping option specified by the table names with the array provided
249
+	 *
250
+	 * @param string $old_table_name
251
+	 * @param string $new_table_name
252
+	 * @param array  $mapping_array
253
+	 * @return boolean success of updating option
254
+	 * @throws EE_Error
255
+	 */
256
+	protected function _set_mapping_option($old_table_name, $new_table_name, $mapping_array)
257
+	{
258
+		$success = update_option($this->_get_mapping_option_name($old_table_name, $new_table_name), $mapping_array, false);
259
+		return $success;
260
+	}
261
+
262
+
263
+	/**
264
+	 * Gets the option name for this script to map from $old_table_name to $new_table_name
265
+	 *
266
+	 * @param string $old_table_name
267
+	 * @param string $new_table_name
268
+	 * @return string
269
+	 * @throws EE_Error
270
+	 */
271
+	protected function _get_mapping_option_name($old_table_name, $new_table_name)
272
+	{
273
+		global $wpdb;
274
+		$old_table_name_sans_wp = str_replace($wpdb->prefix, "", $old_table_name);
275
+		$new_table_name_sans_wp = str_replace($wpdb->prefix, "", $new_table_name);
276
+		$migrates_to = EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
277
+		return substr(
278
+			EE_Data_Migration_Manager::data_migration_script_mapping_option_prefix . $migrates_to ['slug'] . '_' . $migrates_to['version'] . '_' . $old_table_name_sans_wp . '_' . $new_table_name_sans_wp,
279
+			0,
280
+			64
281
+		);
282
+	}
283
+
284
+
285
+	/**
286
+	 * Counts all the records that will be migrated during this data migration.
287
+	 * For example, if we were changing old user passwords from plaintext to encoded versions,
288
+	 * this would be a count of all users who have passwords. If we were going to also split
289
+	 * attendee records into transactions, registrations, and attendee records, this would include
290
+	 * the count of all attendees currently in existence in the DB (ie, users + attendees).
291
+	 * If you can't determine how many records there are to migrate, just provide a guess: this
292
+	 * number will only be used in calculating the percent complete. If you estimate there to be
293
+	 * 100 records to migrate, and it turns out there's 120, we'll just show the migration as being at
294
+	 * 99% until the function "migration_step" returns EE_Data_Migration_Script_Base::status_complete.
295
+	 *
296
+	 * @return int
297
+	 */
298
+	protected function _count_records_to_migrate()
299
+	{
300
+		$count = 0;
301
+		foreach ($this->stages() as $stage) {
302
+			$count += $stage->count_records_to_migrate();
303
+		}
304
+		return $count;
305
+	}
306
+
307
+
308
+	/**
309
+	 * Returns the number of records updated so far. Usually this is easiest to do
310
+	 * by just setting a transient and updating it after each migration_step
311
+	 *
312
+	 * @return int
313
+	 */
314
+	public function count_records_migrated()
315
+	{
316
+		$count = 0;
317
+		foreach ($this->stages() as $stage) {
318
+			$count += $stage->count_records_migrated();
319
+		}
320
+		$this->_records_migrated = $count;
321
+		return $count;
322
+	}
323
+
324
+
325
+	/**
326
+	 * @param int $num_records_to_migrate_limit
327
+	 * @return int
328
+	 * @throws EE_Error
329
+	 * @throws Exception
330
+	 */
331
+	public function migration_step($num_records_to_migrate_limit)
332
+	{
333
+		// reset the feedback message
334
+		$this->_feedback_message = '';
335
+		// if we haven't yet done the 1st schema changes, do them now. buffer any output
336
+		$this->_maybe_do_schema_changes(true);
337
+
338
+		$num_records_actually_migrated = 0;
339
+		$records_migrated_per_stage = array();
340
+		// setup the 'stage' variable, which should hold the last run stage of the migration  (or none at all if nothing runs)
341
+		$stage = null;
342
+		// get the next stage that isn't complete
343
+		foreach ($this->stages() as $stage) {
344
+			if ($stage->get_status() == EE_Data_Migration_Manager::status_continue) {
345
+				try {
346
+					$records_migrated_during_stage = $stage->migration_step(
347
+						$num_records_to_migrate_limit - $num_records_actually_migrated
348
+					);
349
+					$num_records_actually_migrated += $records_migrated_during_stage;
350
+					$records_migrated_per_stage[ $stage->pretty_name() ] = $records_migrated_during_stage;
351
+				} catch (Exception $e) {
352
+					// yes if we catch an exception here, we consider that migration stage borked.
353
+					$stage->set_status(EE_Data_Migration_Manager::status_fatal_error);
354
+					$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
355
+					$stage->add_error($e->getMessage() . ". Stack-trace:" . $e->getTraceAsString());
356
+					throw $e;
357
+				}
358
+				// check that the migration stage didn't mark itself as having a fatal error
359
+				if ($stage->is_broken()) {
360
+					$this->set_broken();
361
+					throw new EE_Error($stage->get_last_error());
362
+				}
363
+			}
364
+			// once we've migrated all the number we intended to (possibly from different stages), stop migrating
365
+			// or if we had a fatal error
366
+			// or if the current script stopped early- its not done, but it's done all it thinks we should do on this step
367
+			if (
368
+				$num_records_actually_migrated >= $num_records_to_migrate_limit
369
+				|| $stage->is_broken()
370
+				|| $stage->has_more_to_do()
371
+			) {
372
+				break;
373
+			}
374
+		}
375
+		// check if we're all done this data migration...
376
+		// which is indicated by being done early AND the last stage claims to be done
377
+		if ($stage == null) {
378
+			// this migration script apparently has NO stages... which is super weird, but whatever
379
+			$this->set_completed();
380
+			$this->_maybe_do_schema_changes(false);
381
+		} elseif ($num_records_actually_migrated < $num_records_to_migrate_limit && ! $stage->has_more_to_do()) {
382
+			// apparently we're done, because we couldn't migrate the number we intended to
383
+			$this->set_completed();
384
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
385
+			// do schema changes for after the migration now
386
+			// first double-check we haven't already done this
387
+			$this->_maybe_do_schema_changes(false);
388
+		} else {
389
+			// update feedback message, keeping in mind that we show them with the most recent at the top
390
+			$this->_update_feedback_message(array_reverse($records_migrated_per_stage));
391
+		}
392
+		return $num_records_actually_migrated;
393
+	}
394
+
395
+
396
+	/**
397
+	 * Updates the feedback message according to what was done during this migration stage.
398
+	 *
399
+	 * @param array $records_migrated_per_stage KEYS are pretty names for each stage; values are the count of records
400
+	 *                                          migrated from that stage
401
+	 * @return void
402
+	 */
403
+	private function _update_feedback_message($records_migrated_per_stage)
404
+	{
405
+		$feedback_message_array = array();
406
+		foreach ($records_migrated_per_stage as $migration_stage_name => $num_records_migrated) {
407
+			$feedback_message_array[] = sprintf(
408
+				esc_html__("Migrated %d records successfully during %s", "event_espresso"),
409
+				$num_records_migrated,
410
+				$migration_stage_name
411
+			);
412
+		}
413
+		$this->_feedback_message .= implode("<br>", $feedback_message_array);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Calls either schema_changes_before_migration() (if $before==true) or schema_changes_after_migration
419
+	 * (if $before==false). Buffers their outputs and stores them on the class.
420
+	 *
421
+	 * @param boolean $before
422
+	 * @throws Exception
423
+	 * @return void
424
+	 */
425
+	private function _maybe_do_schema_changes($before = true)
426
+	{
427
+		// so this property will be either _schema_changes_after_migration_ran or _schema_changes_before_migration_ran
428
+		$property_name = '_schema_changes_' . ($before ? 'before' : 'after') . '_migration_ran';
429
+		if (! $this->{$property_name}) {
430
+			try {
431
+				ob_start();
432
+				if ($before) {
433
+					$this->schema_changes_before_migration();
434
+				} else {
435
+					$this->schema_changes_after_migration();
436
+				}
437
+				$output = ob_get_contents();
438
+				ob_end_clean();
439
+			} catch (Exception $e) {
440
+				$this->set_status(EE_Data_Migration_Manager::status_fatal_error);
441
+				throw $e;
442
+			}
443
+			// record that we've done these schema changes
444
+			$this->{$property_name} = true;
445
+			// if there were any warnings etc, record them as non-fatal errors
446
+			if ($output) {
447
+				// there were some warnings
448
+				$this->_errors[] = $output;
449
+			}
450
+		}
451
+	}
452
+
453
+
454
+	/**
455
+	 * Wrapper for EEH_Activation::create_table. However, takes into account the request type when
456
+	 * deciding what to pass for its 4th arg, $drop_pre_existing_tables. Using this function, instead
457
+	 * of _table_should_exist_previously, indicates that this table should be new to the EE version being migrated to
458
+	 * or
459
+	 * activated currently. If this is a brand new activation or a migration, and we're indicating this table should
460
+	 * not
461
+	 * previously exist, then we want to set $drop_pre_existing_tables to TRUE (ie, we shouldn't discover that this
462
+	 * table exists in the DB in EEH_Activation::create_table- if it DOES exist, something's wrong and the old table
463
+	 * should be nuked.
464
+	 *
465
+	 * Just for a bit of context, the migration script's db_schema_changes_* methods
466
+	 * are called basically in 3 cases: on brand new activation of EE4 (ie no previous version of EE existed and the
467
+	 * plugin is being activated and we want to add all the brand new tables), upon reactivation of EE4 (it was
468
+	 * deactivated and then reactivated, in which case we want to just verify the DB structure is ok) that table should
469
+	 * be dropped), and during a migration when we're moving the DB to the state of the migration script
470
+	 *
471
+	 * @param string $table_name
472
+	 * @param string $table_definition_sql
473
+	 * @param string $engine_string
474
+	 * @throws EE_Error
475
+	 * @throws ReflectionException
476
+	 */
477
+	protected function _table_is_new_in_this_version(
478
+		$table_name,
479
+		$table_definition_sql,
480
+		$engine_string = 'ENGINE=InnoDB '
481
+	) {
482
+		$this->_create_table_and_catch_errors(
483
+			$table_name,
484
+			$table_definition_sql,
485
+			$engine_string,
486
+			$this->_pre_existing_table_should_be_dropped(true)
487
+		);
488
+	}
489
+
490
+
491
+	/**
492
+	 * Like _table_is_new_in_this_version and _table_should_exist_previously, this function verifies the given table
493
+	 * exists. But we understand that this table has CHANGED in this version since the previous version. So it's not
494
+	 * completely new, but it's different. So we need to treat it like a new table in terms of verifying it's schema is
495
+	 * correct on activations, migrations, upgrades; but if it exists when it shouldn't, we need to be as lenient as
496
+	 * _table_should_exist_previously.
497
+	 * 8656]{Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the
498
+	 * table shouldn't exist).
499
+	 *
500
+	 * @param string $table_name
501
+	 * @param string $table_definition_sql
502
+	 * @param string $engine_string
503
+	 * @throws EE_Error
504
+	 * @throws ReflectionException
505
+	 */
506
+	protected function _table_is_changed_in_this_version(
507
+		$table_name,
508
+		$table_definition_sql,
509
+		$engine_string = 'ENGINE=MyISAM'
510
+	) {
511
+		$this->_create_table_and_catch_errors(
512
+			$table_name,
513
+			$table_definition_sql,
514
+			$engine_string,
515
+			$this->_pre_existing_table_should_be_dropped(false)
516
+		);
517
+	}
518
+
519
+
520
+	/**
521
+	 * _old_table_exists
522
+	 * returns TRUE if the requested table exists in the current database
523
+	 *
524
+	 * @param string $table_name
525
+	 * @return boolean
526
+	 * @throws EE_Error
527
+	 */
528
+	protected function _old_table_exists($table_name)
529
+	{
530
+		return $this->_get_table_analysis()->tableExists($table_name);
531
+	}
532
+
533
+
534
+	/**
535
+	 * _delete_table_if_empty
536
+	 * returns TRUE if the requested table was empty and successfully empty
537
+	 *
538
+	 * @param string $table_name
539
+	 * @return boolean
540
+	 * @throws EE_Error
541
+	 * @throws ReflectionException
542
+	 */
543
+	protected function _delete_table_if_empty($table_name)
544
+	{
545
+		return EEH_Activation::delete_db_table_if_empty($table_name);
546
+	}
547
+
548
+
549
+	/**
550
+	 * It is preferred to use _table_has_not_changed_since_previous or _table_is_changed_in_this_version
551
+	 * as these are significantly more efficient or explicit.
552
+	 * Please see description of _table_is_new_in_this_version. This function will only set
553
+	 * EEH_Activation::create_table's $drop_pre_existing_tables to TRUE if it's a brand
554
+	 * new activation. ie, a more accurate name for this method would be "_table_added_previously_by_this_plugin"
555
+	 * because the table will be cleared out if this is a new activation (ie, if its a new activation, it actually
556
+	 * should exist previously). Otherwise, we'll always set $drop_pre_existing_tables to FALSE because the table
557
+	 * should have existed. Note, if the table is being MODIFIED in this version being activated or migrated to, then
558
+	 * you want _table_is_changed_in_this_version NOT this one. We don't check this table's structure during migrations
559
+	 * because apparently it hasn't changed since the previous one, right?
560
+	 *
561
+	 * @param string $table_name
562
+	 * @param string $table_definition_sql
563
+	 * @param string $engine_string
564
+	 * @throws EE_Error
565
+	 * @throws ReflectionException
566
+	 */
567
+	protected function _table_should_exist_previously(
568
+		$table_name,
569
+		$table_definition_sql,
570
+		$engine_string = 'ENGINE=MyISAM'
571
+	) {
572
+		$this->_create_table_and_catch_errors(
573
+			$table_name,
574
+			$table_definition_sql,
575
+			$engine_string,
576
+			$this->_pre_existing_table_should_be_dropped(false)
577
+		);
578
+	}
579
+
580
+
581
+	/**
582
+	 * Exactly the same as _table_should_exist_previously(), except if this migration script is currently doing
583
+	 * a migration, we skip checking this table's structure in the database and just assume it's correct.
584
+	 * So this is useful only to improve efficiency when doing migrations (not a big deal for single site installs,
585
+	 * but important for multisite where migrations can take a very long time otherwise).
586
+	 * If the table is known to have changed since previous version, use _table_is_changed_in_this_version().
587
+	 * Assumes only this plugin could have added this table (ie, if its a new activation of this plugin, the table
588
+	 * shouldn't exist).
589
+	 *
590
+	 * @param string $table_name
591
+	 * @param string $table_definition_sql
592
+	 * @param string $engine_string
593
+	 * @throws EE_Error
594
+	 * @throws ReflectionException
595
+	 */
596
+	protected function _table_has_not_changed_since_previous(
597
+		$table_name,
598
+		$table_definition_sql,
599
+		$engine_string = 'ENGINE=MyISAM'
600
+	) {
601
+		if ($this->_currently_migrating()) {
602
+			// if we're doing a migration, and this table apparently already exists, then we don't need do anything right?
603
+			return;
604
+		}
605
+		$this->_create_table_and_catch_errors(
606
+			$table_name,
607
+			$table_definition_sql,
608
+			$engine_string,
609
+			$this->_pre_existing_table_should_be_dropped(false)
610
+		);
611
+	}
612
+
613
+	/**
614
+	 * Returns whether or not this migration script is being used as part of an actual migration
615
+	 *
616
+	 * @return boolean
617
+	 */
618
+	protected function _currently_migrating()
619
+	{
620
+		// we want to know if we are currently performing a migration. We could just believe what was set on the _migrating property, but let's double-check (ie the script should apply and we should be in MM)
621
+		return $this->_migrating &&
622
+			   $this->can_migrate_from_version(
623
+				   EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set()
624
+			   ) &&
625
+			   EE_Maintenance_Mode::instance()->real_level() == EE_Maintenance_Mode::level_2_complete_maintenance;
626
+	}
627
+
628
+
629
+	/**
630
+	 * Determines if a table should be dropped, based on whether it's reported to be new in $table_is_new,
631
+	 * and the plugin's request type.
632
+	 * Assumes only this plugin could have added the table (ie, if its a new activation of this plugin, the table
633
+	 * shouldn't exist no matter what).
634
+	 *
635
+	 * @param boolean $table_is_new
636
+	 * @return boolean
637
+	 * @throws EE_Error
638
+	 */
639
+	protected function _pre_existing_table_should_be_dropped($table_is_new)
640
+	{
641
+		if ($table_is_new) {
642
+			if (
643
+				$this->_get_req_type_for_plugin_corresponding_to_this_dms() == EE_System::req_type_new_activation
644
+				|| $this->_currently_migrating()
645
+			) {
646
+				return true;
647
+			} else {
648
+				return false;
649
+			}
650
+		} else {
651
+			if (
652
+				in_array(
653
+					$this->_get_req_type_for_plugin_corresponding_to_this_dms(),
654
+					array(EE_System::req_type_new_activation)
655
+				)
656
+			) {
657
+				return true;
658
+			} else {
659
+				return false;
660
+			}
661
+		}
662
+	}
663
+
664
+
665
+	/**
666
+	 * Just wraps EEH_Activation::create_table, but catches any errors it may throw and adds them as errors on the DMS
667
+	 *
668
+	 * @param string  $table_name
669
+	 * @param string  $table_definition_sql
670
+	 * @param string  $engine_string
671
+	 * @param boolean $drop_pre_existing_tables
672
+	 * @throws ReflectionException
673
+	 */
674
+	private function _create_table_and_catch_errors(
675
+		$table_name,
676
+		$table_definition_sql,
677
+		$engine_string = 'ENGINE=MyISAM',
678
+		$drop_pre_existing_tables = false
679
+	) {
680
+		try {
681
+			EEH_Activation::create_table($table_name, $table_definition_sql, $engine_string, $drop_pre_existing_tables);
682
+		} catch (EE_Error $e) {
683
+			$message = $e->getMessage() . '<br>Stack Trace:' . $e->getTraceAsString();
684
+			$this->add_error($message);
685
+			$this->_feedback_message .= $message;
686
+		}
687
+	}
688
+
689
+
690
+	/**
691
+	 * Gets the request type for the plugin (core or addon) that corresponds to this DMS
692
+	 *
693
+	 * @return int one of EE_System::_req_type_* constants
694
+	 * @throws EE_Error
695
+	 */
696
+	private function _get_req_type_for_plugin_corresponding_to_this_dms()
697
+	{
698
+		if ($this->slug() == 'Core') {
699
+			return EE_System::instance()->detect_req_type();
700
+		} else {// it must be for an addon
701
+			$addon_name = $this->slug();
702
+			if (EE_Registry::instance()->get_addon_by_name($addon_name)) {
703
+				return EE_Registry::instance()->get_addon_by_name($addon_name)->detect_req_type();
704
+			} else {
705
+				throw new EE_Error(
706
+					sprintf(
707
+						esc_html__(
708
+							"The DMS slug '%s' should correspond to the addon's name, which should also be '%s', but no such addon was registered. These are the registered addons' names: %s",
709
+							"event_espresso"
710
+						),
711
+						$this->slug(),
712
+						$addon_name,
713
+						implode(",", array_keys(EE_Registry::instance()->get_addons_by_name()))
714
+					)
715
+				);
716
+			}
717
+		}
718
+	}
719
+
720
+
721
+	/**
722
+	 * returns an array of strings describing errors by all the script's stages
723
+	 *
724
+	 * @return array
725
+	 */
726
+	public function get_errors()
727
+	{
728
+		$all_errors = $this->_errors;
729
+		if (! is_array($all_errors)) {
730
+			$all_errors = array();
731
+		}
732
+		foreach ($this->stages() as $stage) {
733
+			$all_errors = array_merge($stage->get_errors(), $all_errors);
734
+		}
735
+		return $all_errors;
736
+	}
737
+
738
+
739
+	/**
740
+	 * Indicates whether or not this migration script should continue
741
+	 *
742
+	 * @return boolean
743
+	 */
744
+	public function can_continue()
745
+	{
746
+		return in_array(
747
+			$this->get_status(),
748
+			EE_Data_Migration_Manager::instance()->stati_that_indicate_to_continue_single_migration_script
749
+		);
750
+	}
751
+
752
+
753
+	/**
754
+	 * Gets all the data migration stages associated with this script. Note:
755
+	 * addons can filter this list to add their own stages, and because the list is
756
+	 * numerically-indexed, they can insert their stage wherever they like and it will
757
+	 * get ordered by the indexes
758
+	 *
759
+	 * @return EE_Data_Migration_Script_Stage[]
760
+	 */
761
+	protected function stages()
762
+	{
763
+		$stages = apply_filters('FHEE__' . get_class($this) . '__stages', $this->_migration_stages);
764
+		ksort($stages);
765
+		return $stages;
766
+	}
767
+
768
+
769
+	/**
770
+	 * Gets a string which should describe what's going on currently with this migration, which
771
+	 * can be displayed to the user
772
+	 *
773
+	 * @return string
774
+	 */
775
+	public function get_feedback_message()
776
+	{
777
+		return $this->_feedback_message;
778
+	}
779
+
780
+
781
+	/**
782
+	 * A lot like "__sleep()" magic method in purpose, this is meant for persisting this class'
783
+	 * properties to the DB. However, we don't want to use __sleep() because its quite
784
+	 * possible that this class is defined when it goes to sleep, but NOT available when it
785
+	 * awakes (eg, this class is part of an addon that is deactivated at some point).
786
+	 */
787
+	public function properties_as_array()
788
+	{
789
+		$properties = parent::properties_as_array();
790
+		$properties['_migration_stages'] = array();
791
+		foreach ($this->_migration_stages as $migration_stage_priority => $migration_stage_class) {
792
+			$properties['_migration_stages'][ $migration_stage_priority ] = $migration_stage_class->properties_as_array(
793
+			);
794
+		}
795
+		unset($properties['_mappings']);
796
+		unset($properties['previous_dms']);
797
+
798
+		foreach ($this->_mappings as $old_table_name => $mapping_to_new_table) {
799
+			foreach ($mapping_to_new_table as $new_table_name => $mapping) {
800
+				$this->_set_mapping_option($old_table_name, $new_table_name, $mapping);
801
+			}
802
+		}
803
+		return $properties;
804
+	}
805
+
806
+
807
+	/**
808
+	 * Sets all of the properties of this script stage to match what's in the array, which is assumed
809
+	 * to have been made from the properties_as_array() function.
810
+	 *
811
+	 * @param array $array_of_properties like what's produced from properties_as_array() method
812
+	 * @return void
813
+	 */
814
+	public function instantiate_from_array_of_properties($array_of_properties)
815
+	{
816
+		$stages_properties_arrays = $array_of_properties['_migration_stages'];
817
+		unset($array_of_properties['_migration_stages']);
818
+		unset($array_of_properties['class']);
819
+		foreach ($array_of_properties as $property_name => $property_value) {
820
+			$this->{$property_name} = $property_value;
821
+		}
822
+		// _migration_stages are already instantiated, but have only default data
823
+		foreach ($this->_migration_stages as $stage) {
824
+			$stage_data = $this->_find_migration_stage_data_with_classname(
825
+				get_class($stage),
826
+				$stages_properties_arrays
827
+			);
828
+			// SO, if we found the stage data that was saved, use it. Otherwise, I guess the stage is new? (maybe added by
829
+			// an addon? Unlikely... not sure why it wouldn't exist, but if it doesn't just treat it like it was never started yet)
830
+			if ($stage_data) {
831
+				$stage->instantiate_from_array_of_properties($stage_data);
832
+			}
833
+		}
834
+	}
835
+
836
+
837
+	/**
838
+	 * Gets the migration data from the array $migration_stage_data_arrays (which is an array of arrays, each of which
839
+	 * is pretty well identical to EE_Data_Migration_Stage objects except all their properties are array indexes)
840
+	 * for the given classname
841
+	 *
842
+	 * @param string $classname
843
+	 * @param array  $migration_stage_data_arrays
844
+	 * @return null
845
+	 */
846
+	private function _find_migration_stage_data_with_classname($classname, $migration_stage_data_arrays)
847
+	{
848
+		foreach ($migration_stage_data_arrays as $migration_stage_data_array) {
849
+			if (isset($migration_stage_data_array['class']) && $migration_stage_data_array['class'] == $classname) {
850
+				return $migration_stage_data_array;
851
+			}
852
+		}
853
+		return null;
854
+	}
855
+
856
+
857
+	/**
858
+	 * Returns the version that this script migrates to, based on the script's name.
859
+	 * Cannot be overwritten because lots of code needs to know which version a script
860
+	 * migrates to knowing only its name.
861
+	 *
862
+	 * @return array where the first key is the plugin's slug, the 2nd is the version of that plugin
863
+	 * that will be updated to. Eg array('Core','4.1.0')
864
+	 * @throws EE_Error
865
+	 */
866
+	final public function migrates_to_version()
867
+	{
868
+		return EE_Data_Migration_Manager::instance()->script_migrates_to_version(get_class($this));
869
+	}
870
+
871
+
872
+	/**
873
+	 * Gets this addon's slug as it would appear in the current_db_state wp option,
874
+	 * and if this migration script is for an addon, it SHOULD match the addon's slug
875
+	 * (and also the addon's classname, minus the 'EE_' prefix.). Eg, 'Calendar' for the EE_Calendar addon.
876
+	 * Or 'Core' for core (non-addon).
877
+	 *
878
+	 * @return string
879
+	 * @throws EE_Error
880
+	 */
881
+	public function slug()
882
+	{
883
+		$migrates_to_version_info = $this->migrates_to_version();
884
+		// the slug is the first part of the array
885
+		return $migrates_to_version_info['slug'];
886
+	}
887
+
888
+
889
+	/**
890
+	 * Returns the script's priority relative to DMSs from other addons. However, when
891
+	 * two DMSs from the same addon/core apply, this is ignored (and instead the version that
892
+	 * the script migrates to is used to determine which to run first). The default is 5, but all core DMSs
893
+	 * normally have priority 10. (So if you want a DMS "A" to run before DMS "B", both of which are from addons,
894
+	 * and both of which CAN run at the same time (ie, "B" doesn't depend on "A" to set
895
+	 * the database up so it can run), then you can set "A" to priority 3 or something.
896
+	 *
897
+	 * @return int
898
+	 */
899
+	public function priority()
900
+	{
901
+		return $this->_priority;
902
+	}
903
+
904
+
905
+	/**
906
+	 * Sets whether or not this DMS is being ran as part of a migration, instead of
907
+	 * just being used to setup (or verify) the current database structure matches
908
+	 * what the latest DMS indicates it should be
909
+	 *
910
+	 * @param boolean $migrating
911
+	 * @return void
912
+	 */
913
+	public function set_migrating($migrating = true)
914
+	{
915
+		$this->_migrating = $migrating;
916
+	}
917
+
918
+	/**
919
+	 * Marks that we think this migration class can continue to migrate
920
+	 */
921
+	public function reattempt()
922
+	{
923
+		parent::reattempt();
924
+		// also, we want to reattempt any stages that were marked as borked
925
+		foreach ($this->stages() as $stage) {
926
+			if ($stage->is_broken()) {
927
+				$stage->reattempt();
928
+			}
929
+		}
930
+	}
931 931
 }
Please login to merge, or discard this patch.
data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_shortcodes.dmsstage.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
     {
19 19
         $new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
20 20
         global $wpdb;
21
-        $wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
21
+        $wpdb->query($wpdb->prepare("UPDATE ".$this->_old_table." SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
22 22
     }
23 23
 
24 24
     /**
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
     public function _count_records_to_migrate()
49 49
     {
50 50
         global $wpdb;
51
-        $count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
51
+        $count = $wpdb->get_var("SELECT COUNT(id) FROM ".$this->_old_table.$this->_sql_to_only_select_non_drafts());
52 52
         return $count;
53 53
     }
54 54
 
Please login to merge, or discard this patch.
Indentation   +47 added lines, -48 removed lines patch added patch discarded remove patch
@@ -2,58 +2,57 @@
 block discarded – undo
2 2
 
3 3
 /**
4 4
  * Goes through all the posts and pages, and converts old shortcodes to new ones
5
-
6
-*/
5
+ */
7 6
 
8 7
 class EE_DMS_4_1_0_shortcodes extends EE_Data_Migration_Script_Stage
9 8
 {
10
-    public function __construct()
11
-    {
12
-        global $wpdb;
13
-        $this->_pretty_name = esc_html__("Shortcodes", "event_espresso");
14
-        $this->_old_table = $wpdb->posts;
15
-        parent::__construct();
16
-    }
17
-    protected function _migrate_old_row($old_row)
18
-    {
19
-        $new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
20
-        global $wpdb;
21
-        $wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
22
-    }
9
+	public function __construct()
10
+	{
11
+		global $wpdb;
12
+		$this->_pretty_name = esc_html__("Shortcodes", "event_espresso");
13
+		$this->_old_table = $wpdb->posts;
14
+		parent::__construct();
15
+	}
16
+	protected function _migrate_old_row($old_row)
17
+	{
18
+		$new_post_content = $this->_change_event_list_shortcode($old_row['post_content']);
19
+		global $wpdb;
20
+		$wpdb->query($wpdb->prepare("UPDATE " . $this->_old_table . " SET post_content=%s WHERE ID=%d", $new_post_content, $old_row['ID']));
21
+	}
23 22
 
24
-    /**
25
-     * replaces [EVENT_LIST... with [ESPRESSO_EVENTS...]
26
-     * @param string $old_content
27
-     */
28
-    private function _change_event_list_shortcode($old_content)
29
-    {
30
-        return str_replace("[EVENT_LIST", "[ESPRESSO_EVENTS", $old_content);
31
-    }
23
+	/**
24
+	 * replaces [EVENT_LIST... with [ESPRESSO_EVENTS...]
25
+	 * @param string $old_content
26
+	 */
27
+	private function _change_event_list_shortcode($old_content)
28
+	{
29
+		return str_replace("[EVENT_LIST", "[ESPRESSO_EVENTS", $old_content);
30
+	}
32 31
 
33
-    public function _migration_step($num_items = 50)
34
-    {
35
-        global $wpdb;
36
-        $start_at_record = $this->count_records_migrated();
37
-        $rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->_old_table {$this->_sql_to_only_select_non_drafts()} LIMIT %d,%d", $start_at_record, $num_items), ARRAY_A);
38
-        $items_actually_migrated = 0;
39
-        foreach ($rows as $old_row) {
40
-            $this->_migrate_old_row($old_row);
41
-            $items_actually_migrated++;
42
-        }
43
-        if ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate()) {
44
-            $this->set_completed();
45
-        }
46
-        return $items_actually_migrated;
47
-    }
48
-    public function _count_records_to_migrate()
49
-    {
50
-        global $wpdb;
51
-        $count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
52
-        return $count;
53
-    }
32
+	public function _migration_step($num_items = 50)
33
+	{
34
+		global $wpdb;
35
+		$start_at_record = $this->count_records_migrated();
36
+		$rows = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->_old_table {$this->_sql_to_only_select_non_drafts()} LIMIT %d,%d", $start_at_record, $num_items), ARRAY_A);
37
+		$items_actually_migrated = 0;
38
+		foreach ($rows as $old_row) {
39
+			$this->_migrate_old_row($old_row);
40
+			$items_actually_migrated++;
41
+		}
42
+		if ($this->count_records_migrated() + $items_actually_migrated >= $this->count_records_to_migrate()) {
43
+			$this->set_completed();
44
+		}
45
+		return $items_actually_migrated;
46
+	}
47
+	public function _count_records_to_migrate()
48
+	{
49
+		global $wpdb;
50
+		$count = $wpdb->get_var("SELECT COUNT(id) FROM " . $this->_old_table . $this->_sql_to_only_select_non_drafts());
51
+		return $count;
52
+	}
54 53
 
55
-    private function _sql_to_only_select_non_drafts()
56
-    {
57
-        return " WHERE post_type NOT IN ('revision','auto-draft','attachment','nav_menu_item') ";
58
-    }
54
+	private function _sql_to_only_select_non_drafts()
55
+	{
56
+		return " WHERE post_type NOT IN ('revision','auto-draft','attachment','nav_menu_item') ";
57
+	}
59 58
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_checkins.dmsstage.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -26,160 +26,160 @@
 block discarded – undo
26 26
 
27 27
 class EE_DMS_4_1_0_checkins extends EE_Data_Migration_Script_Stage_Table
28 28
 {
29
-    private $_new_table;
30
-    public function __construct()
31
-    {
32
-        global $wpdb;
33
-        $this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
-        $this->_old_table = $wpdb->prefix . "events_attendee";
35
-        $this->select_expression = 'att.*, e.event_status';
36
-        $this->_extra_where_sql = 'AS att
29
+	private $_new_table;
30
+	public function __construct()
31
+	{
32
+		global $wpdb;
33
+		$this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
+		$this->_old_table = $wpdb->prefix . "events_attendee";
35
+		$this->select_expression = 'att.*, e.event_status';
36
+		$this->_extra_where_sql = 'AS att
37 37
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39
-        $this->_new_table = $wpdb->prefix . "esp_checkin";
40
-        parent::__construct();
41
-    }
42
-    protected function _migrate_old_row($old_row)
43
-    {
44
-        global $wpdb;
45
-        $new_reg_table = $wpdb->prefix . "esp_registration";
39
+		$this->_new_table = $wpdb->prefix . "esp_checkin";
40
+		parent::__construct();
41
+	}
42
+	protected function _migrate_old_row($old_row)
43
+	{
44
+		global $wpdb;
45
+		$new_reg_table = $wpdb->prefix . "esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+		$num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
48 48
 
49
-        $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
51
-            $new_registrations_for_attendee = array();
52
-        }
53
-        $new_datetime = $this->_try_to_find_datetime($old_row);
49
+		$new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
+		if (! $new_registrations_for_attendee) {
51
+			$new_registrations_for_attendee = array();
52
+		}
53
+		$new_datetime = $this->_try_to_find_datetime($old_row);
54 54
 
55
-        // make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
-        $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
-        $new_checkin_ids = array();
58
-        for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
61
-                $this->add_error(sprintf(
62
-                    esc_html__(
63
-                        /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
55
+		// make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
+		$new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
+		$new_checkin_ids = array();
58
+		for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
+			$new_reg_id = $new_registrations_for_attendee[ $i ];
60
+			if (! $new_reg_id) {
61
+				$this->add_error(sprintf(
62
+					esc_html__(
63
+						/* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
64 64
                         *  %3$s number of registrations for the attendee, %4$s new registration rows represented in JSON
65 65
                         */
66
-                        // @codingStandardsIgnoreStart
67
-                        'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
-                        // @codingStandardsIgnoreEnd
69
-                        'event_espresso'
70
-                    ),
71
-                    $this->_json_encode($old_row),
72
-                    abs($num_to_checkin_at_this_time),
73
-                    count($new_registrations_for_attendee),
74
-                    $this->_json_encode($new_registrations_for_attendee)
75
-                ));
76
-                break;
77
-            }
78
-            $existing_checkin_record = $wpdb->get_var(
79
-                $wpdb->prepare(
80
-                    "SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
-                    $new_reg_id
82
-                )
83
-            );
84
-            if (! $existing_checkin_record) {
85
-                $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
-                if ($new_id) {
87
-                    $new_checkin_ids[] = $new_id;
88
-                }
89
-            }
90
-        }
91
-        if ($new_checkin_ids) {
92
-            $this->get_migration_script()->set_mapping(
93
-                $this->_old_table,
94
-                $old_row['id'],
95
-                $this->_new_table,
96
-                $new_checkin_ids
97
-            );
98
-        }
99
-    }
66
+						// @codingStandardsIgnoreStart
67
+						'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
+						// @codingStandardsIgnoreEnd
69
+						'event_espresso'
70
+					),
71
+					$this->_json_encode($old_row),
72
+					abs($num_to_checkin_at_this_time),
73
+					count($new_registrations_for_attendee),
74
+					$this->_json_encode($new_registrations_for_attendee)
75
+				));
76
+				break;
77
+			}
78
+			$existing_checkin_record = $wpdb->get_var(
79
+				$wpdb->prepare(
80
+					"SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
+					$new_reg_id
82
+				)
83
+			);
84
+			if (! $existing_checkin_record) {
85
+				$new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
+				if ($new_id) {
87
+					$new_checkin_ids[] = $new_id;
88
+				}
89
+			}
90
+		}
91
+		if ($new_checkin_ids) {
92
+			$this->get_migration_script()->set_mapping(
93
+				$this->_old_table,
94
+				$old_row['id'],
95
+				$this->_new_table,
96
+				$new_checkin_ids
97
+			);
98
+		}
99
+	}
100 100
 
101 101
 
102
-    /**
103
-     * Tries to find the new datetime the Check-in was for, based on the attendee row
104
-     * (because we know the attendee was for an event as a specific time, and we know
105
-     * the event's OLD ID...)
106
-     * @global type $wpdb
107
-     * @param array $old_attendee_row
108
-     * @return array row of datetime from DB
109
-     */
110
-    private function _try_to_find_datetime($old_attendee)
111
-    {
112
-        global $wpdb;
102
+	/**
103
+	 * Tries to find the new datetime the Check-in was for, based on the attendee row
104
+	 * (because we know the attendee was for an event as a specific time, and we know
105
+	 * the event's OLD ID...)
106
+	 * @global type $wpdb
107
+	 * @param array $old_attendee_row
108
+	 * @return array row of datetime from DB
109
+	 */
110
+	private function _try_to_find_datetime($old_attendee)
111
+	{
112
+		global $wpdb;
113 113
 
114
-        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
116
-            $this->add_error(
117
-                sprintf(
118
-                    esc_html__(
119
-                        /* translators: 1: original event ID, 2: original attendee database row */
120
-                        // @codingStandardsIgnoreStart
121
-                        'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
-                        // @codingStandardsIgnoreEnd
123
-                        'event_espresso'
124
-                    ),
125
-                    $old_attendee['event_id'],
126
-                    $this->_json_encode($old_attendee)
127
-                )
128
-            );
129
-            return 0;
130
-        }
131
-        $old_att_start_date = $old_attendee['start_date'];
132
-        $old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
-        $old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
114
+		$new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
+		if (! $new_event_id) {
116
+			$this->add_error(
117
+				sprintf(
118
+					esc_html__(
119
+						/* translators: 1: original event ID, 2: original attendee database row */
120
+						// @codingStandardsIgnoreStart
121
+						'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
+						// @codingStandardsIgnoreEnd
123
+						'event_espresso'
124
+					),
125
+					$old_attendee['event_id'],
126
+					$this->_json_encode($old_attendee)
127
+				)
128
+			);
129
+			return 0;
130
+		}
131
+		$old_att_start_date = $old_attendee['start_date'];
132
+		$old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
+		$old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
134 134
 
135
-        $datetime_table = $wpdb->prefix . "esp_datetime";
136
-        // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
-        // the most important condition should be last, as it will be array_shift'ed off last
138
-        $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
-        );
142
-        // start running queries, widening search each time by removing a condition
143
-        $datetime_found = null;
144
-        do {
145
-            $full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
146
-            $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
-            array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
149
-        return $datetime_found;
150
-    }
135
+		$datetime_table = $wpdb->prefix . "esp_datetime";
136
+		// add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
+		// the most important condition should be last, as it will be array_shift'ed off last
138
+		$conditions = array(
139
+			$wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
+			$wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
+		);
142
+		// start running queries, widening search each time by removing a condition
143
+		$datetime_found = null;
144
+		do {
145
+			$full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
146
+			$datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
+			array_shift($conditions);
148
+		} while (! $datetime_found && $conditions);
149
+		return $datetime_found;
150
+	}
151 151
 
152
-    /**
153
-     * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
-     * @param int $new_reg_id
155
-     * @param int $new_datetime_id
156
-     * @param string $timestamp mysql datetime
157
-     * @return int new Check-in id
158
-     */
159
-    private function _insert_checkin_record($new_reg_id, $new_datetime)
160
-    {
161
-        global $wpdb;
152
+	/**
153
+	 * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
+	 * @param int $new_reg_id
155
+	 * @param int $new_datetime_id
156
+	 * @param string $timestamp mysql datetime
157
+	 * @return int new Check-in id
158
+	 */
159
+	private function _insert_checkin_record($new_reg_id, $new_datetime)
160
+	{
161
+		global $wpdb;
162 162
 
163 163
 
164
-        // ok we can actually do what we set out to do: add a checkin/checkout record
165
-        $cols_n_values = array(
166
-            'REG_ID' => $new_reg_id,
167
-            'DTT_ID' => $new_datetime['DTT_ID'],
168
-            'CHK_in' => true,
169
-            'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170
-        );
171
-        $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
176
-        );
177
-        $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
179
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
-            return 0;
181
-        }
182
-        $new_id = $wpdb->insert_id;
183
-        return $new_id;
184
-    }
164
+		// ok we can actually do what we set out to do: add a checkin/checkout record
165
+		$cols_n_values = array(
166
+			'REG_ID' => $new_reg_id,
167
+			'DTT_ID' => $new_datetime['DTT_ID'],
168
+			'CHK_in' => true,
169
+			'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170
+		);
171
+		$datatypes = array(
172
+			'%d',// REG_ID
173
+			'%d',// DTT_ID
174
+			'%d',// CHK_in
175
+			'%s',// CHK_timestamp
176
+		);
177
+		$success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
+		if (! $success) {
179
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
+			return 0;
181
+		}
182
+		$new_id = $wpdb->insert_id;
183
+		return $new_id;
184
+	}
185 185
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -31,23 +31,23 @@  discard block
 block discarded – undo
31 31
     {
32 32
         global $wpdb;
33 33
         $this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
-        $this->_old_table = $wpdb->prefix . "events_attendee";
34
+        $this->_old_table = $wpdb->prefix."events_attendee";
35 35
         $this->select_expression = 'att.*, e.event_status';
36 36
         $this->_extra_where_sql = 'AS att
37
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
37
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39
-        $this->_new_table = $wpdb->prefix . "esp_checkin";
39
+        $this->_new_table = $wpdb->prefix."esp_checkin";
40 40
         parent::__construct();
41 41
     }
42 42
     protected function _migrate_old_row($old_row)
43 43
     {
44 44
         global $wpdb;
45
-        $new_reg_table = $wpdb->prefix . "esp_registration";
45
+        $new_reg_table = $wpdb->prefix."esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']), intval($old_row['checked_in'])));
48 48
 
49 49
         $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
50
+        if ( ! $new_registrations_for_attendee) {
51 51
             $new_registrations_for_attendee = array();
52 52
         }
53 53
         $new_datetime = $this->_try_to_find_datetime($old_row);
@@ -56,8 +56,8 @@  discard block
 block discarded – undo
56 56
         $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57 57
         $new_checkin_ids = array();
58 58
         for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
59
+            $new_reg_id = $new_registrations_for_attendee[$i];
60
+            if ( ! $new_reg_id) {
61 61
                 $this->add_error(sprintf(
62 62
                     esc_html__(
63 63
                         /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                     $new_reg_id
82 82
                 )
83 83
             );
84
-            if (! $existing_checkin_record) {
84
+            if ( ! $existing_checkin_record) {
85 85
                 $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86 86
                 if ($new_id) {
87 87
                     $new_checkin_ids[] = $new_id;
@@ -111,8 +111,8 @@  discard block
 block discarded – undo
111 111
     {
112 112
         global $wpdb;
113 113
 
114
-        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix . "events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
114
+        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_attendee['event_id'], $wpdb->posts);
115
+        if ( ! $new_event_id) {
116 116
             $this->add_error(
117 117
                 sprintf(
118 118
                     esc_html__(
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
         $old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133 133
         $old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
134 134
 
135
-        $datetime_table = $wpdb->prefix . "esp_datetime";
135
+        $datetime_table = $wpdb->prefix."esp_datetime";
136 136
         // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137 137
         // the most important condition should be last, as it will be array_shift'ed off last
138 138
         $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
139
+            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime), // times match?
140
+            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id), // events match?
141 141
         );
142 142
         // start running queries, widening search each time by removing a condition
143 143
         $datetime_found = null;
144 144
         do {
145
-            $full_query = "SELECT * FROM $datetime_table WHERE " . implode(" AND ", $conditions) . " LIMIT 1";
145
+            $full_query = "SELECT * FROM $datetime_table WHERE ".implode(" AND ", $conditions)." LIMIT 1";
146 146
             $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147 147
             array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
148
+        }while ( ! $datetime_found && $conditions);
149 149
         return $datetime_found;
150 150
     }
151 151
 
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
             'CHK_timestamp' => $new_datetime['DTT_EVT_start']
170 170
         );
171 171
         $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
172
+            '%d', // REG_ID
173
+            '%d', // DTT_ID
174
+            '%d', // CHK_in
175
+            '%s', // CHK_timestamp
176 176
         );
177 177
         $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
178
+        if ( ! $success) {
179 179
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180 180
             return 0;
181 181
         }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_9_0.dms.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -9,12 +9,12 @@  discard block
 block discarded – undo
9 9
 // unfortunately, this needs to be done upon INCLUSION of this file,
10 10
 // instead of construction, because it only gets constructed on first page load
11 11
 // (all other times it gets resurrected from a wordpress option)
12
-$stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
12
+$stages = glob(EE_CORE.'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15 15
     $matches = array();
16 16
     preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
-    $class_to_filepath[ $matches[1] ] = $filepath;
17
+    $class_to_filepath[$matches[1]] = $filepath;
18 18
 }
19 19
 // give addons a chance to autoload their stages too
20 20
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_9_0__autoloaded_stages', $class_to_filepath);
@@ -65,10 +65,10 @@  discard block
 block discarded – undo
65 65
         if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
66 66
             //          echo "$version_string can be migrated from";
67 67
             return true;
68
-        } elseif (! $version_string) {
68
+        } elseif ( ! $version_string) {
69 69
             //          echo "no version string provided: $version_string";
70 70
             // no version string provided... this must be pre 4.3
71
-            return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
+            return false; // changed mind. dont want people thinking they should migrate yet because they cant
72 72
         } else {
73 73
             //          echo "$version_string doesnt apply";
74 74
             return false;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
      */
83 83
     public function schema_changes_before_migration()
84 84
     {
85
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
+        require_once(EE_HELPERS.'EEH_Activation.helper.php');
86 86
         $now_in_mysql = current_time('mysql', true);
87 87
         $table_name = 'esp_answer';
88 88
         $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
Please login to merge, or discard this patch.
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -12,9 +12,9 @@  discard block
 block discarded – undo
12 12
 $stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15
-    $matches = array();
16
-    preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
-    $class_to_filepath[ $matches[1] ] = $filepath;
15
+	$matches = array();
16
+	preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
+	$class_to_filepath[ $matches[1] ] = $filepath;
18 18
 }
19 19
 // give addons a chance to autoload their stages too
20 20
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_9_0__autoloaded_stages', $class_to_filepath);
@@ -33,68 +33,68 @@  discard block
 block discarded – undo
33 33
  */
34 34
 class EE_DMS_Core_4_9_0 extends EE_Data_Migration_Script_Base
35 35
 {
36
-    /**
37
-     * return EE_DMS_Core_4_9_0
38
-     *
39
-     * @param TableManager  $table_manager
40
-     * @param TableAnalysis $table_analysis
41
-     */
42
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
-    {
44
-        $this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
-        $this->_priority = 10;
46
-        $this->_migration_stages = array(
47
-            new EE_DMS_4_9_0_Email_System_Question(),
48
-            new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
-        );
50
-        parent::__construct($table_manager, $table_analysis);
51
-    }
36
+	/**
37
+	 * return EE_DMS_Core_4_9_0
38
+	 *
39
+	 * @param TableManager  $table_manager
40
+	 * @param TableAnalysis $table_analysis
41
+	 */
42
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
+	{
44
+		$this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
+		$this->_priority = 10;
46
+		$this->_migration_stages = array(
47
+			new EE_DMS_4_9_0_Email_System_Question(),
48
+			new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
+		);
50
+		parent::__construct($table_manager, $table_analysis);
51
+	}
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     * Whether to migrate or not.
57
-     *
58
-     * @param array $version_array
59
-     * @return bool
60
-     */
61
-    public function can_migrate_from_version($version_array)
62
-    {
63
-        $version_string = $version_array['Core'];
64
-        if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
65
-            //          echo "$version_string can be migrated from";
66
-            return true;
67
-        } elseif (! $version_string) {
68
-            //          echo "no version string provided: $version_string";
69
-            // no version string provided... this must be pre 4.3
70
-            return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
-        } else {
72
-            //          echo "$version_string doesnt apply";
73
-            return false;
74
-        }
75
-    }
55
+	/**
56
+	 * Whether to migrate or not.
57
+	 *
58
+	 * @param array $version_array
59
+	 * @return bool
60
+	 */
61
+	public function can_migrate_from_version($version_array)
62
+	{
63
+		$version_string = $version_array['Core'];
64
+		if (version_compare($version_string, '4.9.0.decaf', '<') && version_compare($version_string, '4.8.0.decaf', '>=')) {
65
+			//          echo "$version_string can be migrated from";
66
+			return true;
67
+		} elseif (! $version_string) {
68
+			//          echo "no version string provided: $version_string";
69
+			// no version string provided... this must be pre 4.3
70
+			return false;// changed mind. dont want people thinking they should migrate yet because they cant
71
+		} else {
72
+			//          echo "$version_string doesnt apply";
73
+			return false;
74
+		}
75
+	}
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     * @return bool
81
-     */
82
-    public function schema_changes_before_migration()
83
-    {
84
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
-        $now_in_mysql = current_time('mysql', true);
86
-        $table_name = 'esp_answer';
87
-        $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
79
+	/**
80
+	 * @return bool
81
+	 */
82
+	public function schema_changes_before_migration()
83
+	{
84
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
+		$now_in_mysql = current_time('mysql', true);
86
+		$table_name = 'esp_answer';
87
+		$sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
88 88
 					REG_ID int(10) unsigned NOT NULL,
89 89
 					QST_ID int(10) unsigned NOT NULL,
90 90
 					ANS_value text NOT NULL,
91 91
 					PRIMARY KEY  (ANS_ID),
92 92
 					KEY REG_ID (REG_ID),
93 93
 					KEY QST_ID (QST_ID)";
94
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
-        $table_name = 'esp_attendee_meta';
96
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
-        $sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
94
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
+		$table_name = 'esp_attendee_meta';
96
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
+		$sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
98 98
 				ATT_ID bigint(20) unsigned NOT NULL,
99 99
 				ATT_fname varchar(45) NOT NULL,
100 100
 				ATT_lname varchar(45) NOT NULL,
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 				KEY ATT_email (ATT_email(191)),
112 112
 				KEY ATT_lname (ATT_lname),
113 113
 				KEY ATT_fname (ATT_fname)";
114
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
-        $table_name = 'esp_checkin';
116
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
114
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
+		$table_name = 'esp_checkin';
116
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
117 117
 				REG_ID int(10) unsigned NOT NULL,
118 118
 				DTT_ID int(10) unsigned NOT NULL,
119 119
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -121,9 +121,9 @@  discard block
 block discarded – undo
121 121
 				PRIMARY KEY  (CHK_ID),
122 122
 				KEY REG_ID (REG_ID),
123 123
 				KEY DTT_ID (DTT_ID)";
124
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
-        $table_name = 'esp_country';
126
-        $sql = "CNT_ISO varchar(2) NOT NULL,
124
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
+		$table_name = 'esp_country';
126
+		$sql = "CNT_ISO varchar(2) NOT NULL,
127 127
 				CNT_ISO3 varchar(3) NOT NULL,
128 128
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
129 129
 				CNT_name varchar(45) NOT NULL,
@@ -139,18 +139,18 @@  discard block
 block discarded – undo
139 139
 				CNT_is_EU tinyint(1) DEFAULT '0',
140 140
 				CNT_active tinyint(1) DEFAULT '0',
141 141
 				PRIMARY KEY  (CNT_ISO)";
142
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
-        $table_name = 'esp_currency';
144
-        $sql = "CUR_code varchar(6) NOT NULL,
142
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
+		$table_name = 'esp_currency';
144
+		$sql = "CUR_code varchar(6) NOT NULL,
145 145
 				CUR_single varchar(45) DEFAULT 'dollar',
146 146
 				CUR_plural varchar(45) DEFAULT 'dollars',
147 147
 				CUR_sign varchar(45) DEFAULT '$',
148 148
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
149 149
 				CUR_active tinyint(1) DEFAULT '0',
150 150
 				PRIMARY KEY  (CUR_code)";
151
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
-        $table_name = 'esp_datetime';
153
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
151
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
+		$table_name = 'esp_datetime';
153
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
154 154
 				EVT_ID bigint(20) unsigned NOT NULL,
155 155
 				DTT_name varchar(255) NOT NULL DEFAULT '',
156 156
 				DTT_description text NOT NULL,
@@ -167,25 +167,25 @@  discard block
 block discarded – undo
167 167
 				KEY DTT_EVT_start (DTT_EVT_start),
168 168
 				KEY EVT_ID (EVT_ID),
169 169
 				KEY DTT_is_primary (DTT_is_primary)";
170
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
171
-        $table_name = "esp_datetime_ticket";
172
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
170
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
171
+		$table_name = "esp_datetime_ticket";
172
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
173 173
 				DTT_ID int(10) unsigned NOT NULL,
174 174
 				TKT_ID int(10) unsigned NOT NULL,
175 175
 				PRIMARY KEY  (DTK_ID),
176 176
 				KEY DTT_ID (DTT_ID),
177 177
 				KEY TKT_ID (TKT_ID)";
178
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
179
-        $table_name = 'esp_event_message_template';
180
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
178
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
179
+		$table_name = 'esp_event_message_template';
180
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
181 181
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
182 182
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
183 183
 				PRIMARY KEY  (EMT_ID),
184 184
 				KEY EVT_ID (EVT_ID),
185 185
 				KEY GRP_ID (GRP_ID)";
186
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
187
-        $table_name = 'esp_event_meta';
188
-        $sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
186
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
187
+		$table_name = 'esp_event_meta';
188
+		$sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
189 189
 				EVT_ID bigint(20) unsigned NOT NULL,
190 190
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
191 191
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -200,34 +200,34 @@  discard block
 block discarded – undo
200 200
 				EVT_donations tinyint(1) NULL,
201 201
 				PRIMARY KEY  (EVTM_ID),
202 202
 				KEY EVT_ID (EVT_ID)";
203
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
204
-        $table_name = 'esp_event_question_group';
205
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
203
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
204
+		$table_name = 'esp_event_question_group';
205
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
206 206
 				EVT_ID bigint(20) unsigned NOT NULL,
207 207
 				QSG_ID int(10) unsigned NOT NULL,
208 208
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
209 209
 				PRIMARY KEY  (EQG_ID),
210 210
 				KEY EVT_ID (EVT_ID),
211 211
 				KEY QSG_ID (QSG_ID)";
212
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
213
-        $table_name = 'esp_event_venue';
214
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
212
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
213
+		$table_name = 'esp_event_venue';
214
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
215 215
 				EVT_ID bigint(20) unsigned NOT NULL,
216 216
 				VNU_ID bigint(20) unsigned NOT NULL,
217 217
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
218 218
 				PRIMARY KEY  (EVV_ID)";
219
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
220
-        $table_name = 'esp_extra_meta';
221
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
219
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
220
+		$table_name = 'esp_extra_meta';
221
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
222 222
 				OBJ_ID int(11) DEFAULT NULL,
223 223
 				EXM_type varchar(45) DEFAULT NULL,
224 224
 				EXM_key varchar(45) DEFAULT NULL,
225 225
 				EXM_value text,
226 226
 				PRIMARY KEY  (EXM_ID),
227 227
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
228
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
229
-        $table_name = 'esp_extra_join';
230
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
228
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
229
+		$table_name = 'esp_extra_join';
230
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
231 231
 				EXJ_first_model_id varchar(6) NOT NULL,
232 232
 				EXJ_first_model_name varchar(20) NOT NULL,
233 233
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
 				PRIMARY KEY  (EXJ_ID),
236 236
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
237 237
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
238
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
239
-        $table_name = 'esp_line_item';
240
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
238
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
239
+		$table_name = 'esp_line_item';
240
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
241 241
 				LIN_code varchar(245) NOT NULL DEFAULT '',
242 242
 				TXN_ID int(11) DEFAULT NULL,
243 243
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -258,11 +258,11 @@  discard block
 block discarded – undo
258 258
 				KEY txn_type_timestamp (TXN_ID,LIN_type,LIN_timestamp),
259 259
 				KEY txn_obj_id_obj_type (TXN_ID,OBJ_ID,OBJ_type),
260 260
 				KEY obj_id_obj_type (OBJ_ID,OBJ_type)";
261
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
262
-        $this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
263
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
264
-        $table_name = 'esp_log';
265
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
261
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'TXN_ID');
262
+		$this->_get_table_manager()->dropIndex('esp_line_item', 'LIN_code');
263
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
264
+		$table_name = 'esp_log';
265
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
266 266
 				LOG_time datetime DEFAULT NULL,
267 267
 				OBJ_ID varchar(45) DEFAULT NULL,
268 268
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -273,12 +273,12 @@  discard block
 block discarded – undo
273 273
 				KEY LOG_time (LOG_time),
274 274
 				KEY OBJ (OBJ_type,OBJ_ID),
275 275
 				KEY LOG_type (LOG_type)";
276
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
277
-        $table_name = 'esp_message';
278
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
279
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
280
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
281
-        $sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
276
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
277
+		$table_name = 'esp_message';
278
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
279
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
280
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
281
+		$sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
282 282
 				GRP_ID int(10) unsigned NULL,
283 283
 				MSG_token varchar(255) NULL,
284 284
 				TXN_ID int(10) unsigned NULL,
@@ -310,18 +310,18 @@  discard block
 block discarded – undo
310 310
 				KEY STS_ID (STS_ID),
311 311
 				KEY MSG_created (MSG_created),
312 312
 				KEY MSG_modified (MSG_modified)";
313
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
314
-        $table_name = 'esp_message_template';
315
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
313
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
314
+		$table_name = 'esp_message_template';
315
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
316 316
 				GRP_ID int(10) unsigned NOT NULL,
317 317
 				MTP_context varchar(50) NOT NULL,
318 318
 				MTP_template_field varchar(30) NOT NULL,
319 319
 				MTP_content text NOT NULL,
320 320
 				PRIMARY KEY  (MTP_ID),
321 321
 				KEY GRP_ID (GRP_ID)";
322
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
323
-        $table_name = 'esp_message_template_group';
324
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
322
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
323
+		$table_name = 'esp_message_template_group';
324
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
325 325
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
326 326
 				MTP_name varchar(245) NOT NULL DEFAULT '',
327 327
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -333,9 +333,9 @@  discard block
 block discarded – undo
333 333
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
334 334
 				PRIMARY KEY  (GRP_ID),
335 335
 				KEY MTP_user_id (MTP_user_id)";
336
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
337
-        $table_name = 'esp_payment';
338
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
336
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
337
+		$table_name = 'esp_payment';
338
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
339 339
 				TXN_ID int(10) unsigned DEFAULT NULL,
340 340
 				STS_ID varchar(3) DEFAULT NULL,
341 341
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
 				PRIMARY KEY  (PAY_ID),
353 353
 				KEY PAY_timestamp (PAY_timestamp),
354 354
 				KEY TXN_ID (TXN_ID)";
355
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
356
-        $table_name = 'esp_payment_method';
357
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
355
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
356
+		$table_name = 'esp_payment_method';
357
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
358 358
 				PMD_type varchar(124) DEFAULT NULL,
359 359
 				PMD_name varchar(255) DEFAULT NULL,
360 360
 				PMD_desc text,
@@ -370,24 +370,24 @@  discard block
 block discarded – undo
370 370
 				PRIMARY KEY  (PMD_ID),
371 371
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
372 372
 				KEY PMD_type (PMD_type)";
373
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
374
-        $table_name = "esp_ticket_price";
375
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
373
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
374
+		$table_name = "esp_ticket_price";
375
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
376 376
 				TKT_ID int(10) unsigned NOT NULL,
377 377
 				PRC_ID int(10) unsigned NOT NULL,
378 378
 				PRIMARY KEY  (TKP_ID),
379 379
 				KEY TKT_ID (TKT_ID),
380 380
 				KEY PRC_ID (PRC_ID)";
381
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
382
-        $table_name = "esp_ticket_template";
383
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
381
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
382
+		$table_name = "esp_ticket_template";
383
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
384 384
 				TTM_name varchar(45) NOT NULL,
385 385
 				TTM_description text,
386 386
 				TTM_file varchar(45),
387 387
 				PRIMARY KEY  (TTM_ID)";
388
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
389
-        $table_name = 'esp_question';
390
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
388
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
389
+		$table_name = 'esp_question';
390
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
391 391
 				QST_display_text text NOT NULL,
392 392
 				QST_admin_label varchar(255) NOT NULL,
393 393
 				QST_system varchar(25) DEFAULT NULL,
@@ -401,18 +401,18 @@  discard block
 block discarded – undo
401 401
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
402 402
 				PRIMARY KEY  (QST_ID),
403 403
 				KEY QST_order (QST_order)';
404
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
405
-        $table_name = 'esp_question_group_question';
406
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
404
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
405
+		$table_name = 'esp_question_group_question';
406
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
407 407
 				QSG_ID int(10) unsigned NOT NULL,
408 408
 				QST_ID int(10) unsigned NOT NULL,
409 409
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
410 410
 				PRIMARY KEY  (QGQ_ID),
411 411
 				KEY QST_ID (QST_ID),
412 412
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
413
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
414
-        $table_name = 'esp_question_option';
415
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
413
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
414
+		$table_name = 'esp_question_option';
415
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
416 416
 				QSO_value varchar(255) NOT NULL,
417 417
 				QSO_desc text NOT NULL,
418 418
 				QST_ID int(10) unsigned NOT NULL,
@@ -422,9 +422,9 @@  discard block
 block discarded – undo
422 422
 				PRIMARY KEY  (QSO_ID),
423 423
 				KEY QST_ID (QST_ID),
424 424
 				KEY QSO_order (QSO_order)";
425
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
426
-        $table_name = 'esp_registration';
427
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
425
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
426
+		$table_name = 'esp_registration';
427
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
428 428
 				EVT_ID bigint(20) unsigned NOT NULL,
429 429
 				ATT_ID bigint(20) unsigned NOT NULL,
430 430
 				TXN_ID int(10) unsigned NOT NULL,
@@ -448,18 +448,18 @@  discard block
 block discarded – undo
448 448
 				KEY TKT_ID (TKT_ID),
449 449
 				KEY EVT_ID (EVT_ID),
450 450
 				KEY STS_ID (STS_ID)";
451
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
452
-        $table_name = 'esp_registration_payment';
453
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
451
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
452
+		$table_name = 'esp_registration_payment';
453
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
454 454
 					  REG_ID int(10) unsigned NOT NULL,
455 455
 					  PAY_ID int(10) unsigned NULL,
456 456
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
457 457
 					  PRIMARY KEY  (RPY_ID),
458 458
 					  KEY REG_ID (REG_ID),
459 459
 					  KEY PAY_ID (PAY_ID)";
460
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
461
-        $table_name = 'esp_state';
462
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
460
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
461
+		$table_name = 'esp_state';
462
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
463 463
 				CNT_ISO varchar(2) NOT NULL,
464 464
 				STA_abbrev varchar(24) NOT NULL,
465 465
 				STA_name varchar(100) NOT NULL,
@@ -467,9 +467,9 @@  discard block
 block discarded – undo
467 467
 				PRIMARY KEY  (STA_ID),
468 468
 				KEY STA_abbrev (STA_abbrev),
469 469
 				KEY CNT_ISO (CNT_ISO)";
470
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
471
-        $table_name = 'esp_status';
472
-        $sql = "STS_ID varchar(3) NOT NULL,
470
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
471
+		$table_name = 'esp_status';
472
+		$sql = "STS_ID varchar(3) NOT NULL,
473 473
 				STS_code varchar(45) NOT NULL,
474 474
 				STS_type varchar(45) NOT NULL,
475 475
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -477,9 +477,9 @@  discard block
 block discarded – undo
477 477
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
478 478
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
479 479
 				KEY STS_type (STS_type)";
480
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
481
-        $table_name = 'esp_transaction';
482
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
480
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
481
+		$table_name = 'esp_transaction';
482
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
483 483
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
484 484
 				TXN_total decimal(12,3) DEFAULT '0.00',
485 485
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -491,9 +491,9 @@  discard block
 block discarded – undo
491 491
 				PRIMARY KEY  (TXN_ID),
492 492
 				KEY TXN_timestamp (TXN_timestamp),
493 493
 				KEY STS_ID (STS_ID)";
494
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
495
-        $table_name = 'esp_venue_meta';
496
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
494
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
495
+		$table_name = 'esp_venue_meta';
496
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
497 497
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
498 498
 			VNU_address varchar(255) DEFAULT NULL,
499 499
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -512,10 +512,10 @@  discard block
 block discarded – undo
512 512
 			KEY VNU_ID (VNU_ID),
513 513
 			KEY STA_ID (STA_ID),
514 514
 			KEY CNT_ISO (CNT_ISO)";
515
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
516
-        // modified tables
517
-        $table_name = "esp_price";
518
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
515
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
516
+		// modified tables
517
+		$table_name = "esp_price";
518
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
519 519
 				PRT_ID tinyint(3) unsigned NOT NULL,
520 520
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
521 521
 				PRC_name varchar(245) NOT NULL,
@@ -528,9 +528,9 @@  discard block
 block discarded – undo
528 528
 				PRC_parent int(10) unsigned DEFAULT 0,
529 529
 				PRIMARY KEY  (PRC_ID),
530 530
 				KEY PRT_ID (PRT_ID)";
531
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
532
-        $table_name = "esp_price_type";
533
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
531
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
532
+		$table_name = "esp_price_type";
533
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
534 534
 				PRT_name varchar(45) NOT NULL,
535 535
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
536 536
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -539,9 +539,9 @@  discard block
 block discarded – undo
539 539
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
540 540
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
541 541
 				PRIMARY KEY  (PRT_ID)";
542
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
543
-        $table_name = "esp_ticket";
544
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
542
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
543
+		$table_name = "esp_ticket";
544
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
545 545
 				TTM_ID int(10) unsigned NOT NULL,
546 546
 				TKT_name varchar(245) NOT NULL DEFAULT '',
547 547
 				TKT_description text NOT NULL,
@@ -564,9 +564,9 @@  discard block
 block discarded – undo
564 564
 				TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
565 565
 				PRIMARY KEY  (TKT_ID),
566 566
 				KEY TKT_start_date (TKT_start_date)";
567
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
568
-        $table_name = 'esp_question_group';
569
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
567
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
568
+		$table_name = 'esp_question_group';
569
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
570 570
 				QSG_name varchar(255) NOT NULL,
571 571
 				QSG_identifier varchar(100) NOT NULL,
572 572
 				QSG_desc text NULL,
@@ -579,165 +579,165 @@  discard block
 block discarded – undo
579 579
 				PRIMARY KEY  (QSG_ID),
580 580
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
581 581
 				KEY QSG_order (QSG_order)';
582
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
583
-        $this->insert_default_data();
584
-        return true;
585
-    }
582
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
583
+		$this->insert_default_data();
584
+		return true;
585
+	}
586 586
 
587
-    /**
588
-     * Inserts default data after parent was called.
589
-     * @since 4.10.0.p
590
-     * @throws EE_Error
591
-     * @throws InvalidArgumentException
592
-     * @throws ReflectionException
593
-     * @throws InvalidDataTypeException
594
-     * @throws InvalidInterfaceException
595
-     */
596
-    public function insert_default_data()
597
-    {
598
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
599
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
600
-        // (because many need to convert old string states to foreign keys into the states table)
601
-        $script_4_1_defaults->insert_default_states();
602
-        $script_4_1_defaults->insert_default_countries();
603
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
604
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
605
-        $script_4_5_defaults->insert_default_price_types();
606
-        $script_4_5_defaults->insert_default_prices();
607
-        $script_4_5_defaults->insert_default_tickets();
608
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
609
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
610
-        $script_4_6_defaults->add_default_admin_only_payments();
611
-        $script_4_6_defaults->insert_default_currencies();
612
-        /** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
613
-        $script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
614
-        $script_4_8_defaults->verify_new_countries();
615
-        $script_4_8_defaults->verify_new_currencies();
616
-        $this->verify_db_collations();
617
-        $this->verify_db_collations_again();
618
-    }
587
+	/**
588
+	 * Inserts default data after parent was called.
589
+	 * @since 4.10.0.p
590
+	 * @throws EE_Error
591
+	 * @throws InvalidArgumentException
592
+	 * @throws ReflectionException
593
+	 * @throws InvalidDataTypeException
594
+	 * @throws InvalidInterfaceException
595
+	 */
596
+	public function insert_default_data()
597
+	{
598
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
599
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
600
+		// (because many need to convert old string states to foreign keys into the states table)
601
+		$script_4_1_defaults->insert_default_states();
602
+		$script_4_1_defaults->insert_default_countries();
603
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
604
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
605
+		$script_4_5_defaults->insert_default_price_types();
606
+		$script_4_5_defaults->insert_default_prices();
607
+		$script_4_5_defaults->insert_default_tickets();
608
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
609
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
610
+		$script_4_6_defaults->add_default_admin_only_payments();
611
+		$script_4_6_defaults->insert_default_currencies();
612
+		/** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
613
+		$script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
614
+		$script_4_8_defaults->verify_new_countries();
615
+		$script_4_8_defaults->verify_new_currencies();
616
+		$this->verify_db_collations();
617
+		$this->verify_db_collations_again();
618
+	}
619 619
 
620 620
 
621 621
 
622
-    /**
623
-     * @return boolean
624
-     */
625
-    public function schema_changes_after_migration()
626
-    {
627
-        return true;
628
-    }
622
+	/**
623
+	 * @return boolean
624
+	 */
625
+	public function schema_changes_after_migration()
626
+	{
627
+		return true;
628
+	}
629 629
 
630 630
 
631 631
 
632
-    public function migration_page_hooks()
633
-    {
634
-    }
632
+	public function migration_page_hooks()
633
+	{
634
+	}
635 635
 
636 636
 
637 637
 
638
-    /**
639
-     * Verify all EE4 models' tables use utf8mb4 collation
640
-     *
641
-     * @return void
642
-     */
643
-    public function verify_db_collations()
644
-    {
645
-        global $wpdb;
646
-        // double-check we haven't already done it or that that the DB doesn't support utf8mb4
647
-        if (
648
-            'utf8mb4' !== $wpdb->charset
649
-            || get_option('ee_verified_db_collations', false)
650
-        ) {
651
-            return;
652
-        }
653
-        // grab tables from each model
654
-        $tables_to_check = array();
655
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
656
-            if (method_exists($model_name, 'instance')) {
657
-                $model_obj = call_user_func(array($model_name, 'instance'));
658
-                if ($model_obj instanceof EEM_Base) {
659
-                    foreach ($model_obj->get_tables() as $table) {
660
-                        if (
661
-                            strpos($table->get_table_name(), 'esp_')
662
-                            && (is_main_site()// for main tables, verify global tables
663
-                                || ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
664
-                            )
665
-                            && function_exists('maybe_convert_table_to_utf8mb4')
666
-                        ) {
667
-                            $tables_to_check[] = $table->get_table_name();
668
-                        }
669
-                    }
670
-                }
671
-            }
672
-        }
673
-        // and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
674
-        // when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
675
-        // of hard-coding this
676
-        $addon_tables = array(
677
-            // mailchimp
678
-            'esp_event_mailchimp_list_group',
679
-            'esp_event_question_mailchimp_field',
680
-            // multisite
681
-            'esp_blog_meta',
682
-            // people
683
-            'esp_people_to_post',
684
-            // promotions
685
-            'esp_promotion',
686
-            'esp_promotion_object',
687
-        );
688
-        foreach ($addon_tables as $table_name) {
689
-                $tables_to_check[] = $table_name;
690
-        }
691
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
692
-        // ok and now let's remember this was done (without needing to check the db schemas all over again)
693
-        add_option('ee_verified_db_collations', true, null, 'no');
694
-        // seeing how this ran with the fix from 10435, no need to check again
695
-        add_option('ee_verified_db_collations_again', true, null, 'no');
696
-    }
638
+	/**
639
+	 * Verify all EE4 models' tables use utf8mb4 collation
640
+	 *
641
+	 * @return void
642
+	 */
643
+	public function verify_db_collations()
644
+	{
645
+		global $wpdb;
646
+		// double-check we haven't already done it or that that the DB doesn't support utf8mb4
647
+		if (
648
+			'utf8mb4' !== $wpdb->charset
649
+			|| get_option('ee_verified_db_collations', false)
650
+		) {
651
+			return;
652
+		}
653
+		// grab tables from each model
654
+		$tables_to_check = array();
655
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
656
+			if (method_exists($model_name, 'instance')) {
657
+				$model_obj = call_user_func(array($model_name, 'instance'));
658
+				if ($model_obj instanceof EEM_Base) {
659
+					foreach ($model_obj->get_tables() as $table) {
660
+						if (
661
+							strpos($table->get_table_name(), 'esp_')
662
+							&& (is_main_site()// for main tables, verify global tables
663
+								|| ! $table->is_global()// if not the main site, then only verify non-global tables (avoid doubling up)
664
+							)
665
+							&& function_exists('maybe_convert_table_to_utf8mb4')
666
+						) {
667
+							$tables_to_check[] = $table->get_table_name();
668
+						}
669
+					}
670
+				}
671
+			}
672
+		}
673
+		// and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
674
+		// when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
675
+		// of hard-coding this
676
+		$addon_tables = array(
677
+			// mailchimp
678
+			'esp_event_mailchimp_list_group',
679
+			'esp_event_question_mailchimp_field',
680
+			// multisite
681
+			'esp_blog_meta',
682
+			// people
683
+			'esp_people_to_post',
684
+			// promotions
685
+			'esp_promotion',
686
+			'esp_promotion_object',
687
+		);
688
+		foreach ($addon_tables as $table_name) {
689
+				$tables_to_check[] = $table_name;
690
+		}
691
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
692
+		// ok and now let's remember this was done (without needing to check the db schemas all over again)
693
+		add_option('ee_verified_db_collations', true, null, 'no');
694
+		// seeing how this ran with the fix from 10435, no need to check again
695
+		add_option('ee_verified_db_collations_again', true, null, 'no');
696
+	}
697 697
 
698 698
 
699 699
 
700
-    /**
701
-     * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
702
-     * which meant some DB collations might not have been updated
703
-     * @return void
704
-     */
705
-    public function verify_db_collations_again()
706
-    {
707
-        global $wpdb;
708
-        // double-check we haven't already done this or that the DB doesn't support it
709
-        // compare to how WordPress' upgrade_430() function does this check
710
-        if (
711
-            'utf8mb4' !== $wpdb->charset
712
-            || get_option('ee_verified_db_collations_again', false)
713
-        ) {
714
-            return;
715
-        }
716
-        $tables_to_check = array(
717
-            'esp_attendee_meta',
718
-            'esp_message'
719
-        );
720
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
721
-        add_option('ee_verified_db_collations_again', true, null, 'no');
722
-    }
700
+	/**
701
+	 * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
702
+	 * which meant some DB collations might not have been updated
703
+	 * @return void
704
+	 */
705
+	public function verify_db_collations_again()
706
+	{
707
+		global $wpdb;
708
+		// double-check we haven't already done this or that the DB doesn't support it
709
+		// compare to how WordPress' upgrade_430() function does this check
710
+		if (
711
+			'utf8mb4' !== $wpdb->charset
712
+			|| get_option('ee_verified_db_collations_again', false)
713
+		) {
714
+			return;
715
+		}
716
+		$tables_to_check = array(
717
+			'esp_attendee_meta',
718
+			'esp_message'
719
+		);
720
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
721
+		add_option('ee_verified_db_collations_again', true, null, 'no');
722
+	}
723 723
 
724 724
 
725 725
 
726
-    /**
727
-     * Runs maybe_convert_table_to_utf8mb4 on the specified tables
728
-     * @param $tables_to_check
729
-     * @return boolean true if logic ran, false if it didn't
730
-     */
731
-    protected function _verify_db_collations_for_tables($tables_to_check)
732
-    {
733
-        foreach ($tables_to_check as $table_name) {
734
-            $table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
735
-            if (
736
-                ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
737
-                && $this->_get_table_analysis()->tableExists($table_name)
738
-            ) {
739
-                maybe_convert_table_to_utf8mb4($table_name);
740
-            }
741
-        }
742
-    }
726
+	/**
727
+	 * Runs maybe_convert_table_to_utf8mb4 on the specified tables
728
+	 * @param $tables_to_check
729
+	 * @return boolean true if logic ran, false if it didn't
730
+	 */
731
+	protected function _verify_db_collations_for_tables($tables_to_check)
732
+	{
733
+		foreach ($tables_to_check as $table_name) {
734
+			$table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
735
+			if (
736
+				! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
737
+				&& $this->_get_table_analysis()->tableExists($table_name)
738
+			) {
739
+				maybe_convert_table_to_utf8mb4($table_name);
740
+			}
741
+		}
742
+	}
743 743
 }
Please login to merge, or discard this patch.
4_6_0_stages/EE_DMS_4_6_0_invoice_settings.dmsstage.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -66,8 +66,8 @@
 block discarded – undo
66 66
     {
67 67
 
68 68
         $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
69
-        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
70
-        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
69
+        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path.'invoice_body.template.php', null, false, false, true);
70
+        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path.'receipt_body.template.php', null, false, false, true);
71 71
         if ($overridden_invoice_body || $overridden_receipt_body) {
72 72
             new PersistentAdminNotice(
73 73
                 'invoice_overriding_templates',
Please login to merge, or discard this patch.
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -27,59 +27,59 @@
 block discarded – undo
27 27
  */
28 28
 class EE_DMS_4_6_0_invoice_settings extends EE_Data_Migration_Script_Stage
29 29
 {
30
-    /**
31
-     * Just initializes the status of the migration
32
-     */
33
-    public function __construct()
34
-    {
35
-        $this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
36
-        parent::__construct();
37
-    }
30
+	/**
31
+	 * Just initializes the status of the migration
32
+	 */
33
+	public function __construct()
34
+	{
35
+		$this->_pretty_name = esc_html__('Update Invoice Settings', 'event_espresso');
36
+		parent::__construct();
37
+	}
38 38
 
39 39
 
40 40
 
41
-    /**
42
-     * _count_records_to_migrate
43
-     * Counts the records to migrate; the public version may cache it
44
-     *
45
-     * @access protected
46
-     * @return int
47
-     */
48
-    protected function _count_records_to_migrate()
49
-    {
50
-        return 1;
51
-    }
41
+	/**
42
+	 * _count_records_to_migrate
43
+	 * Counts the records to migrate; the public version may cache it
44
+	 *
45
+	 * @access protected
46
+	 * @return int
47
+	 */
48
+	protected function _count_records_to_migrate()
49
+	{
50
+		return 1;
51
+	}
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     *    _migration_step
57
-     *
58
-     * @access protected
59
-     * @param int $num_items
60
-     * @throws EE_Error
61
-     * @return int number of items ACTUALLY migrated
62
-     * @throws InvalidDataTypeException
63
-     */
64
-    protected function _migration_step($num_items = 1)
65
-    {
55
+	/**
56
+	 *    _migration_step
57
+	 *
58
+	 * @access protected
59
+	 * @param int $num_items
60
+	 * @throws EE_Error
61
+	 * @return int number of items ACTUALLY migrated
62
+	 * @throws InvalidDataTypeException
63
+	 */
64
+	protected function _migration_step($num_items = 1)
65
+	{
66 66
 
67
-        $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
68
-        $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
69
-        $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
70
-        if ($overridden_invoice_body || $overridden_receipt_body) {
71
-            new PersistentAdminNotice(
72
-                'invoice_overriding_templates',
73
-                esc_html__(
74
-                    'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents (but this will be removed in an upcoming version). We recommend deleting your old Invoice/Receipt templates and using the new messages system. Then modify the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
75
-                    'event_espresso'
76
-                ),
77
-                true
78
-            );
79
-        }
67
+		$templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
68
+		$overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
69
+		$overridden_receipt_body = EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
70
+		if ($overridden_invoice_body || $overridden_receipt_body) {
71
+			new PersistentAdminNotice(
72
+				'invoice_overriding_templates',
73
+				esc_html__(
74
+					'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents (but this will be removed in an upcoming version). We recommend deleting your old Invoice/Receipt templates and using the new messages system. Then modify the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
75
+					'event_espresso'
76
+				),
77
+				true
78
+			);
79
+		}
80 80
 
81
-        // regardless of whether it worked or not, we ought to continue the migration
82
-        $this->set_completed();
83
-        return 1;
84
-    }
81
+		// regardless of whether it worked or not, we ought to continue the migration
82
+		$this->set_completed();
83
+		return 1;
84
+	}
85 85
 }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_Restriction_Generator_Public.strategy.php 2 patches
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
     protected function _generate_restrictions(): array
20 20
     {
21 21
         // if there are no standard caps for this model, then for allow full access
22
-        if (! $this->model()->cap_slug()) {
22
+        if ( ! $this->model()->cap_slug()) {
23 23
             return [];
24 24
         }
25 25
 
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
             )
33 33
         ) {
34 34
             if ($this->model() instanceof EEM_CPT_Base) {
35
-                $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
35
+                $restrictions[EE_Restriction_Generator_Base::get_cap_name(
36 36
                     $this->model(),
37 37
                     $this->action()
38
-                ) ] = new EE_Default_Where_Conditions(
38
+                )] = new EE_Default_Where_Conditions(
39 39
                     $this->addPublishedPostConditions()
40 40
                 );
41 41
             } elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
42
-                $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
42
+                $restrictions[EE_Restriction_Generator_Base::get_cap_name(
43 43
                     $this->model(),
44 44
                     $this->action()
45
-                ) ] = new EE_Default_Where_Conditions(
45
+                )] = new EE_Default_Where_Conditions(
46 46
                     [$this->model()->deleted_field_name() => false]
47 47
                 );
48 48
             }
@@ -52,21 +52,21 @@  discard block
 block discarded – undo
52 52
             if (
53 53
                 EE_Restriction_Generator_Base::is_cap(
54 54
                     $this->model(),
55
-                    $this->action() . '_others'
55
+                    $this->action().'_others'
56 56
                 )
57 57
             ) {// both caps exist
58 58
                 if ($this->model() instanceof EEM_CPT_Base) {
59 59
                     // then if they don't have the others cap,
60 60
                     // AT MOST show them their own and other published ones
61
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
61
+                    $restrictions[EE_Restriction_Generator_Base::get_cap_name(
62 62
                         $this->model(),
63
-                        $this->action() . '_others'
64
-                    ) ] = new EE_Default_Where_Conditions(
63
+                        $this->action().'_others'
64
+                    )] = new EE_Default_Where_Conditions(
65 65
                         [
66
-                            'OR*' .
66
+                            'OR*'.
67 67
                             EE_Restriction_Generator_Base::get_cap_name(
68 68
                                 $this->model(),
69
-                                $this->action() . '_others'
69
+                                $this->action().'_others'
70 70
                             ) => $this->addPublishedPostConditions(
71 71
                                 [
72 72
                                     EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
@@ -77,15 +77,15 @@  discard block
 block discarded – undo
77 77
                 } elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
78 78
                     // then if they don't have the other cap,
79 79
                     // AT MOST show them their own or non deleted ones
80
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
80
+                    $restrictions[EE_Restriction_Generator_Base::get_cap_name(
81 81
                         $this->model(),
82
-                        $this->action() . '_others'
83
-                    ) ] = new EE_Default_Where_Conditions(
82
+                        $this->action().'_others'
83
+                    )] = new EE_Default_Where_Conditions(
84 84
                         [
85
-                            'OR*' .
85
+                            'OR*'.
86 86
                             EE_Restriction_Generator_Base::get_cap_name(
87 87
                                 $this->model(),
88
-                                $this->action() . '_others'
88
+                                $this->action().'_others'
89 89
                             ) => [
90 90
                                 EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
91 91
                                 $this->model()->deleted_field_name(
@@ -101,20 +101,20 @@  discard block
 block discarded – undo
101 101
                 if (
102 102
                     EE_Restriction_Generator_Base::is_cap(
103 103
                         $this->model(),
104
-                        $this->action() . '_private'
104
+                        $this->action().'_private'
105 105
                     ) && $this->model() instanceof EEM_CPT_Base
106 106
                 ) {
107 107
                     // if they have basic and others, but not private,
108 108
                     // restrict them to see theirs and others' that aren't private
109
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
109
+                    $restrictions[EE_Restriction_Generator_Base::get_cap_name(
110 110
                         $this->model(),
111
-                        $this->action() . '_private'
112
-                    ) ] = new EE_Default_Where_Conditions(
111
+                        $this->action().'_private'
112
+                    )] = new EE_Default_Where_Conditions(
113 113
                         [
114
-                            'OR*' .
114
+                            'OR*'.
115 115
                             EE_Restriction_Generator_Base::get_cap_name(
116 116
                                 $this->model(),
117
-                                $this->action() . '_private'
117
+                                $this->action().'_private'
118 118
                             ) => $this->addPublishedPostConditions(
119 119
                                 [
120 120
                                     EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
Please login to merge, or discard this patch.
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -11,123 +11,123 @@
 block discarded – undo
11 11
  */
12 12
 class EE_Restriction_Generator_Public extends EE_Restriction_Generator_Base
13 13
 {
14
-    /**
15
-     * @return EE_Default_Where_Conditions[]|EE_Return_None_Where_Conditions[]
16
-     * @throws EE_Error
17
-     */
18
-    protected function _generate_restrictions(): array
19
-    {
20
-        // if there are no standard caps for this model, then for allow full access
21
-        if (! $this->model()->cap_slug()) {
22
-            return [];
23
-        }
14
+	/**
15
+	 * @return EE_Default_Where_Conditions[]|EE_Return_None_Where_Conditions[]
16
+	 * @throws EE_Error
17
+	 */
18
+	protected function _generate_restrictions(): array
19
+	{
20
+		// if there are no standard caps for this model, then for allow full access
21
+		if (! $this->model()->cap_slug()) {
22
+			return [];
23
+		}
24 24
 
25
-        $restrictions = [];
26
-        // does the basic cap exist? (eg 'ee_read_registrations')
27
-        if (
28
-            EE_Restriction_Generator_Base::is_cap(
29
-                $this->model(),
30
-                $this->action()
31
-            )
32
-        ) {
33
-            if ($this->model() instanceof EEM_CPT_Base) {
34
-                $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
35
-                    $this->model(),
36
-                    $this->action()
37
-                ) ] = new EE_Default_Where_Conditions(
38
-                    $this->addPublishedPostConditions()
39
-                );
40
-            } elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
41
-                $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
42
-                    $this->model(),
43
-                    $this->action()
44
-                ) ] = new EE_Default_Where_Conditions(
45
-                    [$this->model()->deleted_field_name() => false]
46
-                );
47
-            }
48
-            // don't impose any restrictions if they don't have the basic reading cap
25
+		$restrictions = [];
26
+		// does the basic cap exist? (eg 'ee_read_registrations')
27
+		if (
28
+			EE_Restriction_Generator_Base::is_cap(
29
+				$this->model(),
30
+				$this->action()
31
+			)
32
+		) {
33
+			if ($this->model() instanceof EEM_CPT_Base) {
34
+				$restrictions[ EE_Restriction_Generator_Base::get_cap_name(
35
+					$this->model(),
36
+					$this->action()
37
+				) ] = new EE_Default_Where_Conditions(
38
+					$this->addPublishedPostConditions()
39
+				);
40
+			} elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
41
+				$restrictions[ EE_Restriction_Generator_Base::get_cap_name(
42
+					$this->model(),
43
+					$this->action()
44
+				) ] = new EE_Default_Where_Conditions(
45
+					[$this->model()->deleted_field_name() => false]
46
+				);
47
+			}
48
+			// don't impose any restrictions if they don't have the basic reading cap
49 49
 
50
-            // does the others cap exist? (eg 'ee_read_others_registrations')
51
-            if (
52
-                EE_Restriction_Generator_Base::is_cap(
53
-                    $this->model(),
54
-                    $this->action() . '_others'
55
-                )
56
-            ) {// both caps exist
57
-                if ($this->model() instanceof EEM_CPT_Base) {
58
-                    // then if they don't have the others cap,
59
-                    // AT MOST show them their own and other published ones
60
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
61
-                        $this->model(),
62
-                        $this->action() . '_others'
63
-                    ) ] = new EE_Default_Where_Conditions(
64
-                        [
65
-                            'OR*' .
66
-                            EE_Restriction_Generator_Base::get_cap_name(
67
-                                $this->model(),
68
-                                $this->action() . '_others'
69
-                            ) => $this->addPublishedPostConditions(
70
-                                [
71
-                                    EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
72
-                                ]
73
-                            ),
74
-                        ]
75
-                    );
76
-                } elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
77
-                    // then if they don't have the other cap,
78
-                    // AT MOST show them their own or non deleted ones
79
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
80
-                        $this->model(),
81
-                        $this->action() . '_others'
82
-                    ) ] = new EE_Default_Where_Conditions(
83
-                        [
84
-                            'OR*' .
85
-                            EE_Restriction_Generator_Base::get_cap_name(
86
-                                $this->model(),
87
-                                $this->action() . '_others'
88
-                            ) => [
89
-                                EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
90
-                                $this->model()->deleted_field_name(
91
-                                )                                    => false,
92
-                            ],
93
-                        ]
94
-                    );
95
-                }
96
-                // again, if they don't have the others cap,
97
-                // continue showing all because there are no inherently hidden ones
50
+			// does the others cap exist? (eg 'ee_read_others_registrations')
51
+			if (
52
+				EE_Restriction_Generator_Base::is_cap(
53
+					$this->model(),
54
+					$this->action() . '_others'
55
+				)
56
+			) {// both caps exist
57
+				if ($this->model() instanceof EEM_CPT_Base) {
58
+					// then if they don't have the others cap,
59
+					// AT MOST show them their own and other published ones
60
+					$restrictions[ EE_Restriction_Generator_Base::get_cap_name(
61
+						$this->model(),
62
+						$this->action() . '_others'
63
+					) ] = new EE_Default_Where_Conditions(
64
+						[
65
+							'OR*' .
66
+							EE_Restriction_Generator_Base::get_cap_name(
67
+								$this->model(),
68
+								$this->action() . '_others'
69
+							) => $this->addPublishedPostConditions(
70
+								[
71
+									EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
72
+								]
73
+							),
74
+						]
75
+					);
76
+				} elseif ($this->model() instanceof EEM_Soft_Delete_Base) {
77
+					// then if they don't have the other cap,
78
+					// AT MOST show them their own or non deleted ones
79
+					$restrictions[ EE_Restriction_Generator_Base::get_cap_name(
80
+						$this->model(),
81
+						$this->action() . '_others'
82
+					) ] = new EE_Default_Where_Conditions(
83
+						[
84
+							'OR*' .
85
+							EE_Restriction_Generator_Base::get_cap_name(
86
+								$this->model(),
87
+								$this->action() . '_others'
88
+							) => [
89
+								EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
90
+								$this->model()->deleted_field_name(
91
+								)                                    => false,
92
+							],
93
+						]
94
+					);
95
+				}
96
+				// again, if they don't have the others cap,
97
+				// continue showing all because there are no inherently hidden ones
98 98
 
99
-                // does the private cap exist (eg 'ee_read_others_private_events')
100
-                if (
101
-                    EE_Restriction_Generator_Base::is_cap(
102
-                        $this->model(),
103
-                        $this->action() . '_private'
104
-                    ) && $this->model() instanceof EEM_CPT_Base
105
-                ) {
106
-                    // if they have basic and others, but not private,
107
-                    // restrict them to see theirs and others' that aren't private
108
-                    $restrictions[ EE_Restriction_Generator_Base::get_cap_name(
109
-                        $this->model(),
110
-                        $this->action() . '_private'
111
-                    ) ] = new EE_Default_Where_Conditions(
112
-                        [
113
-                            'OR*' .
114
-                            EE_Restriction_Generator_Base::get_cap_name(
115
-                                $this->model(),
116
-                                $this->action() . '_private'
117
-                            ) => $this->addPublishedPostConditions(
118
-                                [
119
-                                    EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
120
-                                ],
121
-                                false
122
-                            ),
123
-                        ]
124
-                    );
125
-                }
126
-            }
127
-        } else {
128
-            // there is no basic cap. So allow full access
129
-            $restrictions = [];
130
-        }
131
-        return $restrictions;
132
-    }
99
+				// does the private cap exist (eg 'ee_read_others_private_events')
100
+				if (
101
+					EE_Restriction_Generator_Base::is_cap(
102
+						$this->model(),
103
+						$this->action() . '_private'
104
+					) && $this->model() instanceof EEM_CPT_Base
105
+				) {
106
+					// if they have basic and others, but not private,
107
+					// restrict them to see theirs and others' that aren't private
108
+					$restrictions[ EE_Restriction_Generator_Base::get_cap_name(
109
+						$this->model(),
110
+						$this->action() . '_private'
111
+					) ] = new EE_Default_Where_Conditions(
112
+						[
113
+							'OR*' .
114
+							EE_Restriction_Generator_Base::get_cap_name(
115
+								$this->model(),
116
+								$this->action() . '_private'
117
+							) => $this->addPublishedPostConditions(
118
+								[
119
+									EE_QUERY_PLACEHOLDER_USER_FIELD_NAME => EE_QUERY_PLACEHOLDER_CURRENT_USER,
120
+								],
121
+								false
122
+							),
123
+						]
124
+					);
125
+				}
126
+			}
127
+		} else {
128
+			// there is no basic cap. So allow full access
129
+			$restrictions = [];
130
+		}
131
+		return $restrictions;
132
+	}
133 133
 }
Please login to merge, or discard this patch.
strategies/EE_Restriction_Generator_Default_Protected.strategy.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
     public function __construct(string $default_field_name, string $path_to_event_model)
44 44
     {
45 45
         $this->_default_field_name  = $default_field_name;
46
-        $this->_path_to_event_model = rtrim($path_to_event_model, '.') . '.';
46
+        $this->_path_to_event_model = rtrim($path_to_event_model, '.').'.';
47 47
     }
48 48
 
49 49
 
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
     {
56 56
         // if there are no standard caps for this model, then for now
57 57
         // all we know is if they need the default cap to access this
58
-        if (! $this->model()->cap_slug()) {
58
+        if ( ! $this->model()->cap_slug()) {
59 59
             return [
60 60
                 self::get_default_restrictions_cap() => new EE_Return_None_Where_Conditions(),
61 61
             ];
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
         // if they don't have the "others" default capability,
84 84
         // restrict access to only their default ones, and non-default ones
85 85
         if (EE_Restriction_Generator_Base::is_cap($this->model(), $others_default)) {
86
-            $restrictions[ $this->getCapKey($this->model(), $others_default) ] = $this->othersDefaultRestrictions(
86
+            $restrictions[$this->getCapKey($this->model(), $others_default)] = $this->othersDefaultRestrictions(
87 87
                 $others_default
88 88
             );
89 89
         }
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
             [
127 127
                 // if they don't have the others default cap, they can't access others default items
128 128
                 // (but they can access their own default items, and non-default items)
129
-                'OR*no_' . $this->getCapKey($this->model(), $action) => [
129
+                'OR*no_'.$this->getCapKey($this->model(), $action) => [
130 130
                     'AND'                      => [
131
-                        $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
131
+                        $this->_path_to_event_model.'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
132 132
                         $this->_default_field_name                  => true,
133 133
                     ],
134 134
                     $this->_default_field_name => false,
@@ -148,8 +148,8 @@  discard block
 block discarded – undo
148 148
     {
149 149
         return new EE_Default_Where_Conditions(
150 150
             [
151
-                'OR*no_' . $this->getCapKey($event_model, $action) => [
152
-                    $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
151
+                'OR*no_'.$this->getCapKey($event_model, $action) => [
152
+                    $this->_path_to_event_model.'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
153 153
                 ],
154 154
                 $this->_default_field_name                         => true,
155 155
             ]
@@ -167,9 +167,9 @@  discard block
 block discarded – undo
167 167
     {
168 168
         return new EE_Default_Where_Conditions(
169 169
             [
170
-                'OR*no_' . $this->getCapKey($event_model, $action) => [
171
-                    $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
172
-                    $this->_path_to_event_model . 'status'      => ['!=', 'private'],
170
+                'OR*no_'.$this->getCapKey($event_model, $action) => [
171
+                    $this->_path_to_event_model.'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
172
+                    $this->_path_to_event_model.'status'      => ['!=', 'private'],
173 173
                     $this->_default_field_name                  => true,
174 174
                 ],
175 175
             ]
Please login to merge, or discard this patch.
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -14,164 +14,164 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Restriction_Generator_Default_Protected extends EE_Restriction_Generator_Base
16 16
 {
17
-    /**
18
-     * Name of the field on this model (or a related model, including the model chain to it)
19
-     * that is a boolean indicating whether or not a model object is considered "Default" or not
20
-     *
21
-     * @var string
22
-     */
23
-    protected $_default_field_name;
24
-
25
-    /**
26
-     * The model chain to follow to get to the event model, including the event model itself.
27
-     * Eg 'Ticket.Datetime.Event'
28
-     *
29
-     * @var string
30
-     */
31
-    protected $_path_to_event_model;
32
-
33
-
34
-    /**
35
-     * @param string $default_field_name  the name of the field Name of the field on this model
36
-     *                                    (or a related model, including the model chain to it)
37
-     *                                    that is a boolean indicating whether or not a model object
38
-     *                                    is considered "Default" or not
39
-     * @param string $path_to_event_model The model chain to follow to get to the event model,
40
-     *                                    including the event model itself. Eg 'Ticket.Datetime.Event'
41
-     */
42
-    public function __construct(string $default_field_name, string $path_to_event_model)
43
-    {
44
-        $this->_default_field_name  = $default_field_name;
45
-        $this->_path_to_event_model = rtrim($path_to_event_model, '.') . '.';
46
-    }
47
-
48
-
49
-    /**
50
-     * @return EE_Default_Where_Conditions[]|EE_Return_None_Where_Conditions[]
51
-     * @throws EE_Error
52
-     */
53
-    protected function _generate_restrictions(): array
54
-    {
55
-        // if there are no standard caps for this model, then for now
56
-        // all we know is if they need the default cap to access this
57
-        if (! $this->model()->cap_slug()) {
58
-            return [
59
-                self::get_default_restrictions_cap() => new EE_Return_None_Where_Conditions(),
60
-            ];
61
-        }
62
-
63
-        $action         = $this->action();
64
-        $others         = "{$action}_others";
65
-        $private        = "{$action}_private";
66
-        $default        = "{$action}_default";
67
-        $others_default = "{$action}_others_default";
68
-        $event_model    = EEM_Event::instance();
69
-
70
-        $restrictions = [
71
-            // first: access to non-defaults is essentially controlled by which events are accessible
72
-            // if they don't have the basic event cap, they can't access ANY non-default items
73
-            $this->getCapKey($event_model, $action)    => $this->nonDefaultRestrictions(true),
74
-            // if they don't have the others event cap, they can't access others' non-default items
75
-            $this->getCapKey($event_model, $others)    => $this->othersNonDefaultRestrictions($event_model, $others),
76
-            // if they have basic and others, but not private, they can't access others' private non-default items
77
-            $this->getCapKey($event_model, $private)   => $this->privateRestrictions($event_model, $private),
78
-            // second: access to defaults is controlled by the default capabilities
79
-            // if they don't have the default capability, restrict access to only non-default items
80
-            $this->getCapKey($this->model(), $default) => $this->nonDefaultRestrictions(false),
81
-        ];
82
-        // if they don't have the "others" default capability,
83
-        // restrict access to only their default ones, and non-default ones
84
-        if (EE_Restriction_Generator_Base::is_cap($this->model(), $others_default)) {
85
-            $restrictions[ $this->getCapKey($this->model(), $others_default) ] = $this->othersDefaultRestrictions(
86
-                $others_default
87
-            );
88
-        }
89
-        return $restrictions;
90
-    }
91
-
92
-
93
-    /**
94
-     * @param EEM_Base $model
95
-     * @param string   $action
96
-     * @return string
97
-     * @since   5.0.0.p
98
-     */
99
-    private function getCapKey(EEM_Base $model, string $action): string
100
-    {
101
-        return EE_Restriction_Generator_Base::get_cap_name($model, $action);
102
-    }
103
-
104
-
105
-    /**
106
-     * @param bool $use_default_field_name
107
-     * @return EE_Default_Where_Conditions
108
-     * @since   5.0.0.p
109
-     */
110
-    private function nonDefaultRestrictions(bool $use_default_field_name): EE_Default_Where_Conditions
111
-    {
112
-        return new EE_Default_Where_Conditions([$this->_default_field_name => $use_default_field_name]);
113
-    }
114
-
115
-
116
-    /**
117
-     * @param string $action
118
-     * @return EE_Default_Where_Conditions
119
-     * @throws EE_Error
120
-     * @since   5.0.0.p
121
-     */
122
-    private function othersDefaultRestrictions(string $action): EE_Default_Where_Conditions
123
-    {
124
-        return new EE_Default_Where_Conditions(
125
-            [
126
-                // if they don't have the others default cap, they can't access others default items
127
-                // (but they can access their own default items, and non-default items)
128
-                'OR*no_' . $this->getCapKey($this->model(), $action) => [
129
-                    'AND'                      => [
130
-                        $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
131
-                        $this->_default_field_name                  => true,
132
-                    ],
133
-                    $this->_default_field_name => false,
134
-                ],
135
-            ]
136
-        );
137
-    }
138
-
139
-
140
-    /**
141
-     * @param EEM_Event $event_model
142
-     * @param string    $action
143
-     * @return EE_Default_Where_Conditions
144
-     * @since   5.0.0.p
145
-     */
146
-    private function othersNonDefaultRestrictions(EEM_Event $event_model, string $action): EE_Default_Where_Conditions
147
-    {
148
-        return new EE_Default_Where_Conditions(
149
-            [
150
-                'OR*no_' . $this->getCapKey($event_model, $action) => [
151
-                    $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
152
-                ],
153
-                $this->_default_field_name                         => true,
154
-            ]
155
-        );
156
-    }
157
-
158
-
159
-    /**
160
-     * @param EEM_Event $event_model
161
-     * @param string    $action
162
-     * @return EE_Default_Where_Conditions
163
-     * @since   5.0.0.p
164
-     */
165
-    private function privateRestrictions(EEM_Event $event_model, string $action): EE_Default_Where_Conditions
166
-    {
167
-        return new EE_Default_Where_Conditions(
168
-            [
169
-                'OR*no_' . $this->getCapKey($event_model, $action) => [
170
-                    $this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
171
-                    $this->_path_to_event_model . 'status'      => ['!=', 'private'],
172
-                    $this->_default_field_name                  => true,
173
-                ],
174
-            ]
175
-        );
176
-    }
17
+	/**
18
+	 * Name of the field on this model (or a related model, including the model chain to it)
19
+	 * that is a boolean indicating whether or not a model object is considered "Default" or not
20
+	 *
21
+	 * @var string
22
+	 */
23
+	protected $_default_field_name;
24
+
25
+	/**
26
+	 * The model chain to follow to get to the event model, including the event model itself.
27
+	 * Eg 'Ticket.Datetime.Event'
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $_path_to_event_model;
32
+
33
+
34
+	/**
35
+	 * @param string $default_field_name  the name of the field Name of the field on this model
36
+	 *                                    (or a related model, including the model chain to it)
37
+	 *                                    that is a boolean indicating whether or not a model object
38
+	 *                                    is considered "Default" or not
39
+	 * @param string $path_to_event_model The model chain to follow to get to the event model,
40
+	 *                                    including the event model itself. Eg 'Ticket.Datetime.Event'
41
+	 */
42
+	public function __construct(string $default_field_name, string $path_to_event_model)
43
+	{
44
+		$this->_default_field_name  = $default_field_name;
45
+		$this->_path_to_event_model = rtrim($path_to_event_model, '.') . '.';
46
+	}
47
+
48
+
49
+	/**
50
+	 * @return EE_Default_Where_Conditions[]|EE_Return_None_Where_Conditions[]
51
+	 * @throws EE_Error
52
+	 */
53
+	protected function _generate_restrictions(): array
54
+	{
55
+		// if there are no standard caps for this model, then for now
56
+		// all we know is if they need the default cap to access this
57
+		if (! $this->model()->cap_slug()) {
58
+			return [
59
+				self::get_default_restrictions_cap() => new EE_Return_None_Where_Conditions(),
60
+			];
61
+		}
62
+
63
+		$action         = $this->action();
64
+		$others         = "{$action}_others";
65
+		$private        = "{$action}_private";
66
+		$default        = "{$action}_default";
67
+		$others_default = "{$action}_others_default";
68
+		$event_model    = EEM_Event::instance();
69
+
70
+		$restrictions = [
71
+			// first: access to non-defaults is essentially controlled by which events are accessible
72
+			// if they don't have the basic event cap, they can't access ANY non-default items
73
+			$this->getCapKey($event_model, $action)    => $this->nonDefaultRestrictions(true),
74
+			// if they don't have the others event cap, they can't access others' non-default items
75
+			$this->getCapKey($event_model, $others)    => $this->othersNonDefaultRestrictions($event_model, $others),
76
+			// if they have basic and others, but not private, they can't access others' private non-default items
77
+			$this->getCapKey($event_model, $private)   => $this->privateRestrictions($event_model, $private),
78
+			// second: access to defaults is controlled by the default capabilities
79
+			// if they don't have the default capability, restrict access to only non-default items
80
+			$this->getCapKey($this->model(), $default) => $this->nonDefaultRestrictions(false),
81
+		];
82
+		// if they don't have the "others" default capability,
83
+		// restrict access to only their default ones, and non-default ones
84
+		if (EE_Restriction_Generator_Base::is_cap($this->model(), $others_default)) {
85
+			$restrictions[ $this->getCapKey($this->model(), $others_default) ] = $this->othersDefaultRestrictions(
86
+				$others_default
87
+			);
88
+		}
89
+		return $restrictions;
90
+	}
91
+
92
+
93
+	/**
94
+	 * @param EEM_Base $model
95
+	 * @param string   $action
96
+	 * @return string
97
+	 * @since   5.0.0.p
98
+	 */
99
+	private function getCapKey(EEM_Base $model, string $action): string
100
+	{
101
+		return EE_Restriction_Generator_Base::get_cap_name($model, $action);
102
+	}
103
+
104
+
105
+	/**
106
+	 * @param bool $use_default_field_name
107
+	 * @return EE_Default_Where_Conditions
108
+	 * @since   5.0.0.p
109
+	 */
110
+	private function nonDefaultRestrictions(bool $use_default_field_name): EE_Default_Where_Conditions
111
+	{
112
+		return new EE_Default_Where_Conditions([$this->_default_field_name => $use_default_field_name]);
113
+	}
114
+
115
+
116
+	/**
117
+	 * @param string $action
118
+	 * @return EE_Default_Where_Conditions
119
+	 * @throws EE_Error
120
+	 * @since   5.0.0.p
121
+	 */
122
+	private function othersDefaultRestrictions(string $action): EE_Default_Where_Conditions
123
+	{
124
+		return new EE_Default_Where_Conditions(
125
+			[
126
+				// if they don't have the others default cap, they can't access others default items
127
+				// (but they can access their own default items, and non-default items)
128
+				'OR*no_' . $this->getCapKey($this->model(), $action) => [
129
+					'AND'                      => [
130
+						$this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
131
+						$this->_default_field_name                  => true,
132
+					],
133
+					$this->_default_field_name => false,
134
+				],
135
+			]
136
+		);
137
+	}
138
+
139
+
140
+	/**
141
+	 * @param EEM_Event $event_model
142
+	 * @param string    $action
143
+	 * @return EE_Default_Where_Conditions
144
+	 * @since   5.0.0.p
145
+	 */
146
+	private function othersNonDefaultRestrictions(EEM_Event $event_model, string $action): EE_Default_Where_Conditions
147
+	{
148
+		return new EE_Default_Where_Conditions(
149
+			[
150
+				'OR*no_' . $this->getCapKey($event_model, $action) => [
151
+					$this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
152
+				],
153
+				$this->_default_field_name                         => true,
154
+			]
155
+		);
156
+	}
157
+
158
+
159
+	/**
160
+	 * @param EEM_Event $event_model
161
+	 * @param string    $action
162
+	 * @return EE_Default_Where_Conditions
163
+	 * @since   5.0.0.p
164
+	 */
165
+	private function privateRestrictions(EEM_Event $event_model, string $action): EE_Default_Where_Conditions
166
+	{
167
+		return new EE_Default_Where_Conditions(
168
+			[
169
+				'OR*no_' . $this->getCapKey($event_model, $action) => [
170
+					$this->_path_to_event_model . 'EVT_wp_user' => EE_QUERY_PLACEHOLDER_CURRENT_USER,
171
+					$this->_path_to_event_model . 'status'      => ['!=', 'private'],
172
+					$this->_default_field_name                  => true,
173
+				],
174
+			]
175
+		);
176
+	}
177 177
 }
Please login to merge, or discard this patch.