Completed
Branch FET-8394-RULES (1ae5e4)
by
unknown
50:31 queued 37:22
created
core/db_models/fields/EE_Datetime_Field.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
      * allowed)
568 568
      *
569 569
      * @param string $datetime_string mysql timestamp in UTC
570
-     * @return  mixed null | DateTime
570
+     * @return  null|DbSafeDateTime null | DateTime
571 571
      * @throws \EE_Error
572 572
      */
573 573
     public function prepare_for_set_from_db($datetime_string)
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
      *
725 725
      * @param \DateTimeZone $DateTimeZone
726 726
      * @param int           $time
727
-     * @return mixed
727
+     * @return integer
728 728
      * @throws \DomainException
729 729
      */
730 730
     public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -210,8 +210,8 @@  discard block
 block discarded – undo
210 210
 
211 211
             default :
212 212
                 return $pretty
213
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
214
-                    : $this->_date_format . ' ' . $this->_time_format;
213
+                    ? $this->_pretty_date_format.' '.$this->_pretty_time_format
214
+                    : $this->_date_format.' '.$this->_time_format;
215 215
         }
216 216
     }
217 217
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
      */
468 468
     protected function _prepare_for_display($DateTime, $schema = false)
469 469
     {
470
-        if (! $DateTime instanceof DateTime) {
470
+        if ( ! $DateTime instanceof DateTime) {
471 471
             if ($this->_nullable) {
472 472
                 return '';
473 473
             } else {
@@ -502,15 +502,15 @@  discard block
 block discarded – undo
502 502
             if ($this->_display_timezone()) {
503 503
                 //must be explicit because schema could equal true.
504 504
                 if ($schema === 'no_html') {
505
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
505
+                    $timezone_string = ' ('.$DateTime->format('T').')';
506 506
                 } else {
507
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
507
+                    $timezone_string = ' <span class="ee_dtt_timezone_string">('.$DateTime->format('T').')</span>';
508 508
                 }
509 509
             } else {
510 510
                 $timezone_string = '';
511 511
             }
512 512
 
513
-            return $DateTime->format($format_string) . $timezone_string;
513
+            return $DateTime->format($format_string).$timezone_string;
514 514
         } else {
515 515
             return $DateTime->format($format_string);
516 516
         }
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
     public function prepare_for_use_in_db($datetime_value)
529 529
     {
530 530
         //we allow an empty value or DateTime object, but nothing else.
531
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
531
+        if ( ! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532 532
             throw new EE_Error(
533 533
                 __(
534 534
                     'The incoming value being prepared for setting in the database must either be empty or a php DateTime object',
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
             }
584 584
         }
585 585
 
586
-        if (! $DateTime instanceof DbSafeDateTime) {
586
+        if ( ! $DateTime instanceof DbSafeDateTime) {
587 587
             // if still no datetime object, then let's just use now
588 588
             $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
589 589
         }
@@ -662,7 +662,7 @@  discard block
 block discarded – undo
662 662
         }
663 663
         //not a unix timestamp.  So we will use the set format on this object and set timezone to
664 664
         //create the DateTime object.
665
-        $format = $this->_date_format . ' ' . $this->_time_format;
665
+        $format = $this->_date_format.' '.$this->_time_format;
666 666
         try {
667 667
             $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
668 668
             if ($DateTime instanceof DateTime) {
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
                     $this->_DateTimeZone
672 672
                 );
673 673
             }
674
-            if (! $DateTime instanceof DbSafeDateTime) {
674
+            if ( ! $DateTime instanceof DbSafeDateTime) {
675 675
                 throw new EE_Error(
676 676
                     sprintf(
677 677
                         __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
Please login to merge, or discard this patch.
Indentation   +749 added lines, -749 removed lines patch added patch discarded remove patch
@@ -15,753 +15,753 @@
 block discarded – undo
15 15
 class EE_Datetime_Field extends EE_Model_Field_Base
16 16
 {
17 17
 
18
-    /**
19
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
-     *
22
-     * @type string unix_timestamp_regex
23
-     */
24
-    const unix_timestamp_regex = '/[0-9]{10,}/';
25
-
26
-    /**
27
-     * @type string mysql_timestamp_format
28
-     */
29
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
30
-
31
-    /**
32
-     * @type string mysql_date_format
33
-     */
34
-    const mysql_date_format = 'Y-m-d';
35
-
36
-    /**
37
-     * @type string mysql_time_format
38
-     */
39
-    const mysql_time_format = 'H:i:s';
40
-
41
-    /**
42
-     * Const for using in the default value. If the field's default is set to this,
43
-     * then we will return the time of calling `get_default_value()`, not
44
-     * just the current time at construction
45
-     */
46
-    const now = 'now';
47
-
48
-    /**
49
-     * The following properties hold the default formats for date and time.
50
-     * Defaults are set via the constructor and can be overridden on class instantiation.
51
-     * However they can also be overridden later by the set_format() method
52
-     * (and corresponding set_date_format, set_time_format methods);
53
-     */
54
-    /**
55
-     * @type string $_date_format
56
-     */
57
-    protected $_date_format = '';
58
-
59
-    /**
60
-     * @type string $_time_format
61
-     */
62
-    protected $_time_format = '';
63
-
64
-    /**
65
-     * @type string $_pretty_date_format
66
-     */
67
-    protected $_pretty_date_format = '';
68
-
69
-    /**
70
-     * @type string $_pretty_time_format
71
-     */
72
-    protected $_pretty_time_format = '';
73
-
74
-    /**
75
-     * @type DateTimeZone $_DateTimeZone
76
-     */
77
-    protected $_DateTimeZone;
78
-
79
-    /**
80
-     * @type DateTimeZone $_UTC_DateTimeZone
81
-     */
82
-    protected $_UTC_DateTimeZone;
83
-
84
-    /**
85
-     * @type DateTimeZone $_blog_DateTimeZone
86
-     */
87
-    protected $_blog_DateTimeZone;
88
-
89
-
90
-    /**
91
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
-     * and time returned via getters.
94
-     *
95
-     * @var mixed (null|string)
96
-     */
97
-    protected $_date_time_output;
98
-
99
-
100
-    /**
101
-     * timezone string
102
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
-     *
106
-     * @var string
107
-     */
108
-    protected $_timezone_string;
109
-
110
-
111
-    /**
112
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
-     * offsets for comparison purposes).
114
-     *
115
-     * @var int
116
-     */
117
-    protected $_blog_offset;
118
-
119
-
120
-    /**
121
-     * @param string $table_column
122
-     * @param string $nice_name
123
-     * @param bool   $nullable
124
-     * @param string $default_value
125
-     * @param string $timezone_string
126
-     * @param string $date_format
127
-     * @param string $time_format
128
-     * @param string $pretty_date_format
129
-     * @param string $pretty_time_format
130
-     * @throws \EE_Error
131
-     */
132
-    public function __construct(
133
-        $table_column,
134
-        $nice_name,
135
-        $nullable,
136
-        $default_value,
137
-        $timezone_string = '',
138
-        $date_format = '',
139
-        $time_format = '',
140
-        $pretty_date_format = '',
141
-        $pretty_time_format = ''
142
-    ) {
143
-
144
-        $this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
145
-        $this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
146
-        $this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
147
-        $this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
148
-
149
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
150
-        $this->set_timezone($timezone_string);
151
-        $this->setSchemaFormat('date-time');
152
-    }
153
-
154
-
155
-    /**
156
-     * @return DateTimeZone
157
-     * @throws \EE_Error
158
-     */
159
-    public function get_UTC_DateTimeZone()
160
-    {
161
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
162
-            ? $this->_UTC_DateTimeZone
163
-            : $this->_create_timezone_object_from_timezone_string('UTC');
164
-    }
165
-
166
-
167
-    /**
168
-     * @return DateTimeZone
169
-     * @throws \EE_Error
170
-     */
171
-    public function get_blog_DateTimeZone()
172
-    {
173
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
174
-            ? $this->_blog_DateTimeZone
175
-            : $this->_create_timezone_object_from_timezone_string('');
176
-    }
177
-
178
-
179
-    /**
180
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
181
-     *
182
-     * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
183
-     *                                                              timestamp
184
-     * @return DateTime
185
-     */
186
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
187
-    {
188
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
189
-    }
190
-
191
-
192
-    /**
193
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
194
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
195
-     *
196
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
197
-     * @return string    The final assembled format string.
198
-     */
199
-    protected function _get_date_time_output($pretty = false)
200
-    {
201
-
202
-        switch ($this->_date_time_output) {
203
-            case 'time' :
204
-                return $pretty ? $this->_pretty_time_format : $this->_time_format;
205
-                break;
206
-
207
-            case 'date' :
208
-                return $pretty ? $this->_pretty_date_format : $this->_date_format;
209
-                break;
210
-
211
-            default :
212
-                return $pretty
213
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
214
-                    : $this->_date_format . ' ' . $this->_time_format;
215
-        }
216
-    }
217
-
218
-
219
-    /**
220
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
221
-     * returned (using the format properties)
222
-     *
223
-     * @param string $what acceptable values are 'time' or 'date'.
224
-     *                     Any other value will be set but will always result
225
-     *                     in both 'date' and 'time' being returned.
226
-     * @return void
227
-     */
228
-    public function set_date_time_output($what = null)
229
-    {
230
-        $this->_date_time_output = $what;
231
-    }
232
-
233
-
234
-    /**
235
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
236
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
237
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
238
-     * We also set some other properties in this method.
239
-     *
240
-     * @param string $timezone_string A valid timezone string as described by @link
241
-     *                                http://www.php.net/manual/en/timezones.php
242
-     * @return void
243
-     * @throws \EE_Error
244
-     */
245
-    public function set_timezone($timezone_string)
246
-    {
247
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
248
-            // leave the timezone AS-IS if we already have one and
249
-            // the function arg didn't provide one
250
-            return;
251
-        }
252
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
253
-        $this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
254
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
255
-    }
256
-
257
-
258
-    /**
259
-     * _create_timezone_object_from_timezone_name
260
-     *
261
-     * @access protected
262
-     * @param string $timezone_string
263
-     * @return \DateTimeZone
264
-     * @throws \EE_Error
265
-     */
266
-    protected function _create_timezone_object_from_timezone_string($timezone_string = '')
267
-    {
268
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
269
-    }
270
-
271
-
272
-    /**
273
-     * This just returns whatever is set for the current timezone.
274
-     *
275
-     * @access public
276
-     * @return string timezone string
277
-     */
278
-    public function get_timezone()
279
-    {
280
-        return $this->_timezone_string;
281
-    }
282
-
283
-
284
-    /**
285
-     * set the $_date_format property
286
-     *
287
-     * @access public
288
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
289
-     * @param bool   $pretty Whether to set pretty format or not.
290
-     * @return void
291
-     */
292
-    public function set_date_format($format, $pretty = false)
293
-    {
294
-        if ($pretty) {
295
-            $this->_pretty_date_format = $format;
296
-        } else {
297
-            $this->_date_format = $format;
298
-        }
299
-    }
300
-
301
-
302
-    /**
303
-     * return the $_date_format property value.
304
-     *
305
-     * @param bool $pretty Whether to get pretty format or not.
306
-     * @return string
307
-     */
308
-    public function get_date_format($pretty = false)
309
-    {
310
-        return $pretty ? $this->_pretty_date_format : $this->_date_format;
311
-    }
312
-
313
-
314
-    /**
315
-     * set the $_time_format property
316
-     *
317
-     * @access public
318
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
319
-     * @param bool   $pretty Whether to set pretty format or not.
320
-     * @return void
321
-     */
322
-    public function set_time_format($format, $pretty = false)
323
-    {
324
-        if ($pretty) {
325
-            $this->_pretty_time_format = $format;
326
-        } else {
327
-            $this->_time_format = $format;
328
-        }
329
-    }
330
-
331
-
332
-    /**
333
-     * return the $_time_format property value.
334
-     *
335
-     * @param bool $pretty Whether to get pretty format or not.
336
-     * @return string
337
-     */
338
-    public function get_time_format($pretty = false)
339
-    {
340
-        return $pretty ? $this->_pretty_time_format : $this->_time_format;
341
-    }
342
-
343
-
344
-    /**
345
-     * set the $_pretty_date_format property
346
-     *
347
-     * @access public
348
-     * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
349
-     * @return void
350
-     */
351
-    public function set_pretty_date_format($format)
352
-    {
353
-        $this->_pretty_date_format = $format;
354
-    }
355
-
356
-
357
-    /**
358
-     * set the $_pretty_time_format property
359
-     *
360
-     * @access public
361
-     * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
362
-     * @return void
363
-     */
364
-    public function set_pretty_time_format($format)
365
-    {
366
-        $this->_pretty_time_format = $format;
367
-    }
368
-
369
-
370
-    /**
371
-     * Only sets the time portion of the datetime.
372
-     *
373
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
374
-     * @param DateTime        $current            current DateTime object for the datetime field
375
-     * @return DateTime
376
-     */
377
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
378
-    {
379
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
380
-        // Otherwise parse the string.
381
-        if ($time_to_set_string instanceof DateTime) {
382
-            $parsed = array(
383
-                'hour'   => $time_to_set_string->format('H'),
384
-                'minute' => $time_to_set_string->format('i'),
385
-                'second' => $time_to_set_string->format('s'),
386
-            );
387
-        } else {
388
-            //parse incoming string
389
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
390
-        }
391
-
392
-        //make sure $current is in the correct timezone.
393
-        $current->setTimezone($this->_DateTimeZone);
394
-
395
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
396
-    }
397
-
398
-
399
-    /**
400
-     * Only sets the date portion of the datetime.
401
-     *
402
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
403
-     * @param DateTime        $current            current DateTime object for the datetime field
404
-     * @return DateTime
405
-     */
406
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
407
-    {
408
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
409
-        // Otherwise parse the string.
410
-        if ($date_to_set_string instanceof DateTime) {
411
-            $parsed = array(
412
-                'year'  => $date_to_set_string->format('Y'),
413
-                'month' => $date_to_set_string->format('m'),
414
-                'day'   => $date_to_set_string->format('d'),
415
-            );
416
-        } else {
417
-            //parse incoming string
418
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
419
-        }
420
-
421
-        //make sure $current is in the correct timezone
422
-        $current->setTimezone($this->_DateTimeZone);
423
-
424
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
425
-    }
426
-
427
-
428
-    /**
429
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
430
-     * datetime gets to this stage it should ALREADY be in UTC time
431
-     *
432
-     * @param  DateTime $DateTime
433
-     * @return string formatted date time for given timezone
434
-     * @throws \EE_Error
435
-     */
436
-    public function prepare_for_get($DateTime)
437
-    {
438
-        return $this->_prepare_for_display($DateTime);
439
-    }
440
-
441
-
442
-    /**
443
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
444
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
445
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
446
-     * abbreviation to the date_string.
447
-     *
448
-     * @param mixed $DateTime
449
-     * @param null  $schema
450
-     * @return string
451
-     * @throws \EE_Error
452
-     */
453
-    public function prepare_for_pretty_echoing($DateTime, $schema = null)
454
-    {
455
-        return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
456
-    }
457
-
458
-
459
-    /**
460
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
461
-     * timezone).
462
-     *
463
-     * @param DateTime    $DateTime
464
-     * @param bool|string $schema
465
-     * @return string
466
-     * @throws \EE_Error
467
-     */
468
-    protected function _prepare_for_display($DateTime, $schema = false)
469
-    {
470
-        if (! $DateTime instanceof DateTime) {
471
-            if ($this->_nullable) {
472
-                return '';
473
-            } else {
474
-                if (WP_DEBUG) {
475
-                    throw new EE_Error(
476
-                        sprintf(
477
-                            __(
478
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
479
-                                'event_espresso'
480
-                            ),
481
-                            $this->_nicename
482
-                        )
483
-                    );
484
-                } else {
485
-                    $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
486
-                    EE_Error::add_error(
487
-                        sprintf(
488
-                            __(
489
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
490
-                                'event_espresso'
491
-                            ),
492
-                            $this->_nicename
493
-                        )
494
-                    );
495
-                }
496
-            }
497
-        }
498
-        $format_string = $this->_get_date_time_output($schema);
499
-        //make sure datetime_value is in the correct timezone (in case that's been updated).
500
-        $DateTime->setTimezone($this->_DateTimeZone);
501
-        if ($schema) {
502
-            if ($this->_display_timezone()) {
503
-                //must be explicit because schema could equal true.
504
-                if ($schema === 'no_html') {
505
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
506
-                } else {
507
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
508
-                }
509
-            } else {
510
-                $timezone_string = '';
511
-            }
512
-
513
-            return $DateTime->format($format_string) . $timezone_string;
514
-        } else {
515
-            return $DateTime->format($format_string);
516
-        }
517
-    }
518
-
519
-
520
-    /**
521
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
522
-     * timezone).
523
-     *
524
-     * @param  mixed $datetime_value u
525
-     * @return string mysql timestamp in UTC
526
-     * @throws \EE_Error
527
-     */
528
-    public function prepare_for_use_in_db($datetime_value)
529
-    {
530
-        //we allow an empty value or DateTime object, but nothing else.
531
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532
-            throw new EE_Error(
533
-                __(
534
-                    'The incoming value being prepared for setting in the database must either be empty or a php DateTime object',
535
-                    'event_espresso'
536
-                )
537
-            );
538
-        }
539
-
540
-        if ($datetime_value instanceof DateTime) {
541
-            if ( ! $datetime_value instanceof DbSafeDateTime) {
542
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
-            }
544
-
545
-            return $datetime_value->setTimezone($this->get_UTC_DateTimeZone())->format(
546
-                EE_Datetime_Field::mysql_timestamp_format
547
-            );
548
-        }
549
-
550
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
-        return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
552
-    }
553
-
554
-
555
-    /**
556
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
557
-     * allowed)
558
-     *
559
-     * @param string $datetime_string mysql timestamp in UTC
560
-     * @return  mixed null | DateTime
561
-     * @throws \EE_Error
562
-     */
563
-    public function prepare_for_set_from_db($datetime_string)
564
-    {
565
-        //if $datetime_value is empty, and ! $this->_nullable, just use time()
566
-        if (empty($datetime_string) && $this->_nullable) {
567
-            return null;
568
-        }
569
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
570
-        if (empty($datetime_string)) {
571
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
572
-        } else {
573
-            $DateTime = DateTime::createFromFormat(
574
-                EE_Datetime_Field::mysql_timestamp_format,
575
-                $datetime_string,
576
-                $this->get_UTC_DateTimeZone()
577
-            );
578
-            if ($DateTime instanceof \DateTime) {
579
-                $DateTime = new DbSafeDateTime(
580
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
581
-                    $this->get_UTC_DateTimeZone()
582
-                );
583
-            }
584
-        }
585
-
586
-        if (! $DateTime instanceof DbSafeDateTime) {
587
-            // if still no datetime object, then let's just use now
588
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
589
-        }
590
-        // THEN apply the field's set DateTimeZone
591
-        $DateTime->setTimezone($this->_DateTimeZone);
592
-
593
-        return $DateTime;
594
-    }
595
-
596
-
597
-    /**
598
-     * All this method does is determine if we're going to display the timezone string or not on any output.
599
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
600
-     * If so, then true.
601
-     *
602
-     * @return bool true for yes false for no
603
-     * @throws \EE_Error
604
-     */
605
-    protected function _display_timezone()
606
-    {
607
-
608
-        // first let's do a comparison of timezone strings.
609
-        // If they match then we can get out without any further calculations
610
-        $blog_string = get_option('timezone_string');
611
-        if ($blog_string === $this->_timezone_string) {
612
-            return false;
613
-        }
614
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
615
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
616
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
617
-        // now compare
618
-        return $blog_offset !== $this_offset;
619
-    }
620
-
621
-
622
-    /**
623
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
624
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
625
-     * with.
626
-     *
627
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
628
-     *                                                    in the format that is set on the date_field (or DateTime
629
-     *                                                    object)!
630
-     * @return DateTime
631
-     */
632
-    protected function _get_date_object($date_string)
633
-    {
634
-        //first if this is an empty date_string and nullable is allowed, just return null.
635
-        if ($this->_nullable && empty($date_string)) {
636
-            return null;
637
-        }
638
-
639
-        // if incoming date
640
-        if ($date_string instanceof DateTime) {
641
-            $date_string->setTimezone($this->_DateTimeZone);
642
-
643
-            return $date_string;
644
-        }
645
-        // if empty date_string and made it here.
646
-        // Return a datetime object for now in the given timezone.
647
-        if (empty($date_string)) {
648
-            return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
649
-        }
650
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
651
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
652
-            try {
653
-                // This is operating under the assumption that the incoming Unix timestamp
654
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
655
-                $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
656
-                $DateTime->setTimestamp($date_string);
657
-
658
-                return $DateTime;
659
-            } catch (Exception $e) {
660
-                // should be rare, but if things got fooled then let's just continue
661
-            }
662
-        }
663
-        //not a unix timestamp.  So we will use the set format on this object and set timezone to
664
-        //create the DateTime object.
665
-        $format = $this->_date_format . ' ' . $this->_time_format;
666
-        try {
667
-            $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
668
-            if ($DateTime instanceof DateTime) {
669
-                $DateTime = new DbSafeDateTime(
670
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
671
-                    $this->_DateTimeZone
672
-                );
673
-            }
674
-            if (! $DateTime instanceof DbSafeDateTime) {
675
-                throw new EE_Error(
676
-                    sprintf(
677
-                        __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
678
-                        $date_string,
679
-                        $format
680
-                    )
681
-                );
682
-            }
683
-        } catch (Exception $e) {
684
-            // if we made it here then likely then something went really wrong.
685
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
686
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
687
-        }
688
-
689
-        return $DateTime;
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     * get_timezone_transitions
696
-     *
697
-     * @param \DateTimeZone $DateTimeZone
698
-     * @param int           $time
699
-     * @param bool          $first_only
700
-     * @return mixed
701
-     */
702
-    public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
703
-    {
704
-        $time = is_int($time) || $time === null ? $time : strtotime($time);
705
-        $time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
706
-        $transitions = $DateTimeZone->getTransitions($time);
707
-        return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * get_timezone_offset
714
-     *
715
-     * @param \DateTimeZone $DateTimeZone
716
-     * @param int           $time
717
-     * @return mixed
718
-     * @throws \DomainException
719
-     */
720
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
721
-    {
722
-        $transitions = $this->get_timezone_transitions($DateTimeZone, $time);
723
-        if ( ! isset($transitions['offset'])) {
724
-            throw new DomainException();
725
-        }
726
-        return $transitions['offset'];
727
-    }
728
-
729
-
730
-    /**
731
-     * This will take an incoming timezone string and return the abbreviation for that timezone
732
-     *
733
-     * @param  string $timezone_string
734
-     * @return string           abbreviation
735
-     * @throws \EE_Error
736
-     */
737
-    public function get_timezone_abbrev($timezone_string)
738
-    {
739
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
740
-        $dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
741
-
742
-        return $dateTime->format('T');
743
-    }
744
-
745
-    /**
746
-     * Overrides the parent to allow for having a dynamic "now" value
747
-     *
748
-     * @return mixed
749
-     */
750
-    public function get_default_value()
751
-    {
752
-        if ($this->_default_value === EE_Datetime_Field::now) {
753
-            return time();
754
-        } else {
755
-            return parent::get_default_value();
756
-        }
757
-    }
758
-
759
-
760
-    public function getSchemaDescription()
761
-    {
762
-        return sprintf(
763
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
764
-            $this->get_nicename()
765
-        );
766
-    }
18
+	/**
19
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
+	 *
22
+	 * @type string unix_timestamp_regex
23
+	 */
24
+	const unix_timestamp_regex = '/[0-9]{10,}/';
25
+
26
+	/**
27
+	 * @type string mysql_timestamp_format
28
+	 */
29
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
30
+
31
+	/**
32
+	 * @type string mysql_date_format
33
+	 */
34
+	const mysql_date_format = 'Y-m-d';
35
+
36
+	/**
37
+	 * @type string mysql_time_format
38
+	 */
39
+	const mysql_time_format = 'H:i:s';
40
+
41
+	/**
42
+	 * Const for using in the default value. If the field's default is set to this,
43
+	 * then we will return the time of calling `get_default_value()`, not
44
+	 * just the current time at construction
45
+	 */
46
+	const now = 'now';
47
+
48
+	/**
49
+	 * The following properties hold the default formats for date and time.
50
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
51
+	 * However they can also be overridden later by the set_format() method
52
+	 * (and corresponding set_date_format, set_time_format methods);
53
+	 */
54
+	/**
55
+	 * @type string $_date_format
56
+	 */
57
+	protected $_date_format = '';
58
+
59
+	/**
60
+	 * @type string $_time_format
61
+	 */
62
+	protected $_time_format = '';
63
+
64
+	/**
65
+	 * @type string $_pretty_date_format
66
+	 */
67
+	protected $_pretty_date_format = '';
68
+
69
+	/**
70
+	 * @type string $_pretty_time_format
71
+	 */
72
+	protected $_pretty_time_format = '';
73
+
74
+	/**
75
+	 * @type DateTimeZone $_DateTimeZone
76
+	 */
77
+	protected $_DateTimeZone;
78
+
79
+	/**
80
+	 * @type DateTimeZone $_UTC_DateTimeZone
81
+	 */
82
+	protected $_UTC_DateTimeZone;
83
+
84
+	/**
85
+	 * @type DateTimeZone $_blog_DateTimeZone
86
+	 */
87
+	protected $_blog_DateTimeZone;
88
+
89
+
90
+	/**
91
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
+	 * and time returned via getters.
94
+	 *
95
+	 * @var mixed (null|string)
96
+	 */
97
+	protected $_date_time_output;
98
+
99
+
100
+	/**
101
+	 * timezone string
102
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
+	 *
106
+	 * @var string
107
+	 */
108
+	protected $_timezone_string;
109
+
110
+
111
+	/**
112
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
+	 * offsets for comparison purposes).
114
+	 *
115
+	 * @var int
116
+	 */
117
+	protected $_blog_offset;
118
+
119
+
120
+	/**
121
+	 * @param string $table_column
122
+	 * @param string $nice_name
123
+	 * @param bool   $nullable
124
+	 * @param string $default_value
125
+	 * @param string $timezone_string
126
+	 * @param string $date_format
127
+	 * @param string $time_format
128
+	 * @param string $pretty_date_format
129
+	 * @param string $pretty_time_format
130
+	 * @throws \EE_Error
131
+	 */
132
+	public function __construct(
133
+		$table_column,
134
+		$nice_name,
135
+		$nullable,
136
+		$default_value,
137
+		$timezone_string = '',
138
+		$date_format = '',
139
+		$time_format = '',
140
+		$pretty_date_format = '',
141
+		$pretty_time_format = ''
142
+	) {
143
+
144
+		$this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
145
+		$this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
146
+		$this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
147
+		$this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
148
+
149
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
150
+		$this->set_timezone($timezone_string);
151
+		$this->setSchemaFormat('date-time');
152
+	}
153
+
154
+
155
+	/**
156
+	 * @return DateTimeZone
157
+	 * @throws \EE_Error
158
+	 */
159
+	public function get_UTC_DateTimeZone()
160
+	{
161
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
162
+			? $this->_UTC_DateTimeZone
163
+			: $this->_create_timezone_object_from_timezone_string('UTC');
164
+	}
165
+
166
+
167
+	/**
168
+	 * @return DateTimeZone
169
+	 * @throws \EE_Error
170
+	 */
171
+	public function get_blog_DateTimeZone()
172
+	{
173
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
174
+			? $this->_blog_DateTimeZone
175
+			: $this->_create_timezone_object_from_timezone_string('');
176
+	}
177
+
178
+
179
+	/**
180
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
181
+	 *
182
+	 * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
183
+	 *                                                              timestamp
184
+	 * @return DateTime
185
+	 */
186
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
187
+	{
188
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
189
+	}
190
+
191
+
192
+	/**
193
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
194
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
195
+	 *
196
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
197
+	 * @return string    The final assembled format string.
198
+	 */
199
+	protected function _get_date_time_output($pretty = false)
200
+	{
201
+
202
+		switch ($this->_date_time_output) {
203
+			case 'time' :
204
+				return $pretty ? $this->_pretty_time_format : $this->_time_format;
205
+				break;
206
+
207
+			case 'date' :
208
+				return $pretty ? $this->_pretty_date_format : $this->_date_format;
209
+				break;
210
+
211
+			default :
212
+				return $pretty
213
+					? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
214
+					: $this->_date_format . ' ' . $this->_time_format;
215
+		}
216
+	}
217
+
218
+
219
+	/**
220
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
221
+	 * returned (using the format properties)
222
+	 *
223
+	 * @param string $what acceptable values are 'time' or 'date'.
224
+	 *                     Any other value will be set but will always result
225
+	 *                     in both 'date' and 'time' being returned.
226
+	 * @return void
227
+	 */
228
+	public function set_date_time_output($what = null)
229
+	{
230
+		$this->_date_time_output = $what;
231
+	}
232
+
233
+
234
+	/**
235
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
236
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
237
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
238
+	 * We also set some other properties in this method.
239
+	 *
240
+	 * @param string $timezone_string A valid timezone string as described by @link
241
+	 *                                http://www.php.net/manual/en/timezones.php
242
+	 * @return void
243
+	 * @throws \EE_Error
244
+	 */
245
+	public function set_timezone($timezone_string)
246
+	{
247
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
248
+			// leave the timezone AS-IS if we already have one and
249
+			// the function arg didn't provide one
250
+			return;
251
+		}
252
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
253
+		$this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
254
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
255
+	}
256
+
257
+
258
+	/**
259
+	 * _create_timezone_object_from_timezone_name
260
+	 *
261
+	 * @access protected
262
+	 * @param string $timezone_string
263
+	 * @return \DateTimeZone
264
+	 * @throws \EE_Error
265
+	 */
266
+	protected function _create_timezone_object_from_timezone_string($timezone_string = '')
267
+	{
268
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
269
+	}
270
+
271
+
272
+	/**
273
+	 * This just returns whatever is set for the current timezone.
274
+	 *
275
+	 * @access public
276
+	 * @return string timezone string
277
+	 */
278
+	public function get_timezone()
279
+	{
280
+		return $this->_timezone_string;
281
+	}
282
+
283
+
284
+	/**
285
+	 * set the $_date_format property
286
+	 *
287
+	 * @access public
288
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
289
+	 * @param bool   $pretty Whether to set pretty format or not.
290
+	 * @return void
291
+	 */
292
+	public function set_date_format($format, $pretty = false)
293
+	{
294
+		if ($pretty) {
295
+			$this->_pretty_date_format = $format;
296
+		} else {
297
+			$this->_date_format = $format;
298
+		}
299
+	}
300
+
301
+
302
+	/**
303
+	 * return the $_date_format property value.
304
+	 *
305
+	 * @param bool $pretty Whether to get pretty format or not.
306
+	 * @return string
307
+	 */
308
+	public function get_date_format($pretty = false)
309
+	{
310
+		return $pretty ? $this->_pretty_date_format : $this->_date_format;
311
+	}
312
+
313
+
314
+	/**
315
+	 * set the $_time_format property
316
+	 *
317
+	 * @access public
318
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
319
+	 * @param bool   $pretty Whether to set pretty format or not.
320
+	 * @return void
321
+	 */
322
+	public function set_time_format($format, $pretty = false)
323
+	{
324
+		if ($pretty) {
325
+			$this->_pretty_time_format = $format;
326
+		} else {
327
+			$this->_time_format = $format;
328
+		}
329
+	}
330
+
331
+
332
+	/**
333
+	 * return the $_time_format property value.
334
+	 *
335
+	 * @param bool $pretty Whether to get pretty format or not.
336
+	 * @return string
337
+	 */
338
+	public function get_time_format($pretty = false)
339
+	{
340
+		return $pretty ? $this->_pretty_time_format : $this->_time_format;
341
+	}
342
+
343
+
344
+	/**
345
+	 * set the $_pretty_date_format property
346
+	 *
347
+	 * @access public
348
+	 * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
349
+	 * @return void
350
+	 */
351
+	public function set_pretty_date_format($format)
352
+	{
353
+		$this->_pretty_date_format = $format;
354
+	}
355
+
356
+
357
+	/**
358
+	 * set the $_pretty_time_format property
359
+	 *
360
+	 * @access public
361
+	 * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
362
+	 * @return void
363
+	 */
364
+	public function set_pretty_time_format($format)
365
+	{
366
+		$this->_pretty_time_format = $format;
367
+	}
368
+
369
+
370
+	/**
371
+	 * Only sets the time portion of the datetime.
372
+	 *
373
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
374
+	 * @param DateTime        $current            current DateTime object for the datetime field
375
+	 * @return DateTime
376
+	 */
377
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
378
+	{
379
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
380
+		// Otherwise parse the string.
381
+		if ($time_to_set_string instanceof DateTime) {
382
+			$parsed = array(
383
+				'hour'   => $time_to_set_string->format('H'),
384
+				'minute' => $time_to_set_string->format('i'),
385
+				'second' => $time_to_set_string->format('s'),
386
+			);
387
+		} else {
388
+			//parse incoming string
389
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
390
+		}
391
+
392
+		//make sure $current is in the correct timezone.
393
+		$current->setTimezone($this->_DateTimeZone);
394
+
395
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Only sets the date portion of the datetime.
401
+	 *
402
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
403
+	 * @param DateTime        $current            current DateTime object for the datetime field
404
+	 * @return DateTime
405
+	 */
406
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
407
+	{
408
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
409
+		// Otherwise parse the string.
410
+		if ($date_to_set_string instanceof DateTime) {
411
+			$parsed = array(
412
+				'year'  => $date_to_set_string->format('Y'),
413
+				'month' => $date_to_set_string->format('m'),
414
+				'day'   => $date_to_set_string->format('d'),
415
+			);
416
+		} else {
417
+			//parse incoming string
418
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
419
+		}
420
+
421
+		//make sure $current is in the correct timezone
422
+		$current->setTimezone($this->_DateTimeZone);
423
+
424
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
425
+	}
426
+
427
+
428
+	/**
429
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
430
+	 * datetime gets to this stage it should ALREADY be in UTC time
431
+	 *
432
+	 * @param  DateTime $DateTime
433
+	 * @return string formatted date time for given timezone
434
+	 * @throws \EE_Error
435
+	 */
436
+	public function prepare_for_get($DateTime)
437
+	{
438
+		return $this->_prepare_for_display($DateTime);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
444
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
445
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
446
+	 * abbreviation to the date_string.
447
+	 *
448
+	 * @param mixed $DateTime
449
+	 * @param null  $schema
450
+	 * @return string
451
+	 * @throws \EE_Error
452
+	 */
453
+	public function prepare_for_pretty_echoing($DateTime, $schema = null)
454
+	{
455
+		return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
456
+	}
457
+
458
+
459
+	/**
460
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
461
+	 * timezone).
462
+	 *
463
+	 * @param DateTime    $DateTime
464
+	 * @param bool|string $schema
465
+	 * @return string
466
+	 * @throws \EE_Error
467
+	 */
468
+	protected function _prepare_for_display($DateTime, $schema = false)
469
+	{
470
+		if (! $DateTime instanceof DateTime) {
471
+			if ($this->_nullable) {
472
+				return '';
473
+			} else {
474
+				if (WP_DEBUG) {
475
+					throw new EE_Error(
476
+						sprintf(
477
+							__(
478
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
479
+								'event_espresso'
480
+							),
481
+							$this->_nicename
482
+						)
483
+					);
484
+				} else {
485
+					$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
486
+					EE_Error::add_error(
487
+						sprintf(
488
+							__(
489
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
490
+								'event_espresso'
491
+							),
492
+							$this->_nicename
493
+						)
494
+					);
495
+				}
496
+			}
497
+		}
498
+		$format_string = $this->_get_date_time_output($schema);
499
+		//make sure datetime_value is in the correct timezone (in case that's been updated).
500
+		$DateTime->setTimezone($this->_DateTimeZone);
501
+		if ($schema) {
502
+			if ($this->_display_timezone()) {
503
+				//must be explicit because schema could equal true.
504
+				if ($schema === 'no_html') {
505
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
506
+				} else {
507
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
508
+				}
509
+			} else {
510
+				$timezone_string = '';
511
+			}
512
+
513
+			return $DateTime->format($format_string) . $timezone_string;
514
+		} else {
515
+			return $DateTime->format($format_string);
516
+		}
517
+	}
518
+
519
+
520
+	/**
521
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
522
+	 * timezone).
523
+	 *
524
+	 * @param  mixed $datetime_value u
525
+	 * @return string mysql timestamp in UTC
526
+	 * @throws \EE_Error
527
+	 */
528
+	public function prepare_for_use_in_db($datetime_value)
529
+	{
530
+		//we allow an empty value or DateTime object, but nothing else.
531
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532
+			throw new EE_Error(
533
+				__(
534
+					'The incoming value being prepared for setting in the database must either be empty or a php DateTime object',
535
+					'event_espresso'
536
+				)
537
+			);
538
+		}
539
+
540
+		if ($datetime_value instanceof DateTime) {
541
+			if ( ! $datetime_value instanceof DbSafeDateTime) {
542
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
543
+			}
544
+
545
+			return $datetime_value->setTimezone($this->get_UTC_DateTimeZone())->format(
546
+				EE_Datetime_Field::mysql_timestamp_format
547
+			);
548
+		}
549
+
550
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
551
+		return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
552
+	}
553
+
554
+
555
+	/**
556
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
557
+	 * allowed)
558
+	 *
559
+	 * @param string $datetime_string mysql timestamp in UTC
560
+	 * @return  mixed null | DateTime
561
+	 * @throws \EE_Error
562
+	 */
563
+	public function prepare_for_set_from_db($datetime_string)
564
+	{
565
+		//if $datetime_value is empty, and ! $this->_nullable, just use time()
566
+		if (empty($datetime_string) && $this->_nullable) {
567
+			return null;
568
+		}
569
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
570
+		if (empty($datetime_string)) {
571
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
572
+		} else {
573
+			$DateTime = DateTime::createFromFormat(
574
+				EE_Datetime_Field::mysql_timestamp_format,
575
+				$datetime_string,
576
+				$this->get_UTC_DateTimeZone()
577
+			);
578
+			if ($DateTime instanceof \DateTime) {
579
+				$DateTime = new DbSafeDateTime(
580
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
581
+					$this->get_UTC_DateTimeZone()
582
+				);
583
+			}
584
+		}
585
+
586
+		if (! $DateTime instanceof DbSafeDateTime) {
587
+			// if still no datetime object, then let's just use now
588
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
589
+		}
590
+		// THEN apply the field's set DateTimeZone
591
+		$DateTime->setTimezone($this->_DateTimeZone);
592
+
593
+		return $DateTime;
594
+	}
595
+
596
+
597
+	/**
598
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
599
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
600
+	 * If so, then true.
601
+	 *
602
+	 * @return bool true for yes false for no
603
+	 * @throws \EE_Error
604
+	 */
605
+	protected function _display_timezone()
606
+	{
607
+
608
+		// first let's do a comparison of timezone strings.
609
+		// If they match then we can get out without any further calculations
610
+		$blog_string = get_option('timezone_string');
611
+		if ($blog_string === $this->_timezone_string) {
612
+			return false;
613
+		}
614
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
615
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
616
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
617
+		// now compare
618
+		return $blog_offset !== $this_offset;
619
+	}
620
+
621
+
622
+	/**
623
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
624
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
625
+	 * with.
626
+	 *
627
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
628
+	 *                                                    in the format that is set on the date_field (or DateTime
629
+	 *                                                    object)!
630
+	 * @return DateTime
631
+	 */
632
+	protected function _get_date_object($date_string)
633
+	{
634
+		//first if this is an empty date_string and nullable is allowed, just return null.
635
+		if ($this->_nullable && empty($date_string)) {
636
+			return null;
637
+		}
638
+
639
+		// if incoming date
640
+		if ($date_string instanceof DateTime) {
641
+			$date_string->setTimezone($this->_DateTimeZone);
642
+
643
+			return $date_string;
644
+		}
645
+		// if empty date_string and made it here.
646
+		// Return a datetime object for now in the given timezone.
647
+		if (empty($date_string)) {
648
+			return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
649
+		}
650
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
651
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
652
+			try {
653
+				// This is operating under the assumption that the incoming Unix timestamp
654
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
655
+				$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
656
+				$DateTime->setTimestamp($date_string);
657
+
658
+				return $DateTime;
659
+			} catch (Exception $e) {
660
+				// should be rare, but if things got fooled then let's just continue
661
+			}
662
+		}
663
+		//not a unix timestamp.  So we will use the set format on this object and set timezone to
664
+		//create the DateTime object.
665
+		$format = $this->_date_format . ' ' . $this->_time_format;
666
+		try {
667
+			$DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
668
+			if ($DateTime instanceof DateTime) {
669
+				$DateTime = new DbSafeDateTime(
670
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
671
+					$this->_DateTimeZone
672
+				);
673
+			}
674
+			if (! $DateTime instanceof DbSafeDateTime) {
675
+				throw new EE_Error(
676
+					sprintf(
677
+						__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
678
+						$date_string,
679
+						$format
680
+					)
681
+				);
682
+			}
683
+		} catch (Exception $e) {
684
+			// if we made it here then likely then something went really wrong.
685
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
686
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
687
+		}
688
+
689
+		return $DateTime;
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 * get_timezone_transitions
696
+	 *
697
+	 * @param \DateTimeZone $DateTimeZone
698
+	 * @param int           $time
699
+	 * @param bool          $first_only
700
+	 * @return mixed
701
+	 */
702
+	public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
703
+	{
704
+		$time = is_int($time) || $time === null ? $time : strtotime($time);
705
+		$time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
706
+		$transitions = $DateTimeZone->getTransitions($time);
707
+		return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * get_timezone_offset
714
+	 *
715
+	 * @param \DateTimeZone $DateTimeZone
716
+	 * @param int           $time
717
+	 * @return mixed
718
+	 * @throws \DomainException
719
+	 */
720
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
721
+	{
722
+		$transitions = $this->get_timezone_transitions($DateTimeZone, $time);
723
+		if ( ! isset($transitions['offset'])) {
724
+			throw new DomainException();
725
+		}
726
+		return $transitions['offset'];
727
+	}
728
+
729
+
730
+	/**
731
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
732
+	 *
733
+	 * @param  string $timezone_string
734
+	 * @return string           abbreviation
735
+	 * @throws \EE_Error
736
+	 */
737
+	public function get_timezone_abbrev($timezone_string)
738
+	{
739
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
740
+		$dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
741
+
742
+		return $dateTime->format('T');
743
+	}
744
+
745
+	/**
746
+	 * Overrides the parent to allow for having a dynamic "now" value
747
+	 *
748
+	 * @return mixed
749
+	 */
750
+	public function get_default_value()
751
+	{
752
+		if ($this->_default_value === EE_Datetime_Field::now) {
753
+			return time();
754
+		} else {
755
+			return parent::get_default_value();
756
+		}
757
+	}
758
+
759
+
760
+	public function getSchemaDescription()
761
+	{
762
+		return sprintf(
763
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
764
+			$this->get_nicename()
765
+		);
766
+	}
767 767
 }
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +734 added lines, -734 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 EE_Registry::instance()->load_class('Processor_Base');
5 5
 
@@ -16,737 +16,737 @@  discard block
 block discarded – undo
16 16
 class EE_Payment_Processor extends EE_Processor_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_Payment_Processor $_instance
21
-     * @access    private
22
-     */
23
-    private static $_instance;
24
-
25
-
26
-
27
-    /**
28
-     * @singleton method used to instantiate class object
29
-     * @access    public
30
-     * @return EE_Payment_Processor instance
31
-     */
32
-    public static function instance()
33
-    {
34
-        // check if class object is instantiated
35
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
-            self::$_instance = new self();
37
-        }
38
-        return self::$_instance;
39
-    }
40
-
41
-
42
-
43
-    /**
44
-     *private constructor to prevent direct creation
45
-     *
46
-     * @Constructor
47
-     * @access private
48
-     */
49
-    private function __construct()
50
-    {
51
-        do_action('AHEE__EE_Payment_Processor__construct');
52
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
-     * appropriately. Saves the payment that is generated
60
-     *
61
-     * @param EE_Payment_Method    $payment_method
62
-     * @param EE_Transaction       $transaction
63
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
-     *                                           Leave null if payment is for the full amount owing
65
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
-     *                                           Receive_form_submission() should have
67
-     *                                           already been called on the billing form
68
-     *                                           (ie, its inputs should have their normalized values set).
69
-     * @param string               $return_url   string used mostly by offsite gateways to specify
70
-     *                                           where to go AFTER the offsite gateway
71
-     * @param string               $method       like 'CART', indicates who the client who called this was
72
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
-     * @param boolean              $update_txn   whether or not to call
74
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
-     * @return \EE_Payment
77
-     * @throws \EE_Error
78
-     */
79
-    public function process_payment(
80
-        EE_Payment_Method $payment_method,
81
-        EE_Transaction $transaction,
82
-        $amount = null,
83
-        $billing_form = null,
84
-        $return_url = null,
85
-        $method = 'CART',
86
-        $by_admin = false,
87
-        $update_txn = true,
88
-        $cancel_url = ''
89
-    ) {
90
-        if ((float)$amount < 0) {
91
-            throw new EE_Error(
92
-                sprintf(
93
-                    __(
94
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
-                        'event_espresso'
96
-                    ),
97
-                    $amount,
98
-                    $transaction->ID()
99
-                )
100
-            );
101
-        }
102
-        // verify payment method
103
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
-        // verify transaction
105
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
106
-        $transaction->set_payment_method_ID($payment_method->ID());
107
-        // verify payment method type
108
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
-            $payment = $payment_method->type_obj()->process_payment(
110
-                $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
112
-                $billing_form,
113
-                $return_url,
114
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
-                $method,
116
-                $by_admin
117
-            );
118
-            // check if payment method uses an off-site gateway
119
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
-                // don't process payments for off-site gateways yet because no payment has occurred yet
121
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
-            }
123
-            return $payment;
124
-        } else {
125
-            EE_Error::add_error(
126
-                sprintf(
127
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
-                    '<br/>',
129
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
130
-                ), __FILE__, __FUNCTION__, __LINE__
131
-            );
132
-            return null;
133
-        }
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * @param EE_Transaction|int $transaction
140
-     * @param EE_Payment_Method  $payment_method
141
-     * @throws EE_Error
142
-     * @return string
143
-     */
144
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
-    {
146
-        /** @type \EE_Transaction $transaction */
147
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
-        $primary_reg = $transaction->primary_registration();
149
-        if ( ! $primary_reg instanceof EE_Registration) {
150
-            throw new EE_Error(
151
-                sprintf(
152
-                    __(
153
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
-                        "event_espresso"
155
-                    ),
156
-                    $transaction->ID()
157
-                )
158
-            );
159
-        }
160
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
-        $url = add_query_arg(
162
-            array(
163
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
-                'ee_payment_method' => $payment_method->slug(),
165
-            ),
166
-            EE_Registry::instance()->CFG->core->txn_page_url()
167
-        );
168
-        return $url;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
-     * we can easily find what registration the IPN is for and what payment method.
176
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
177
-     * If a payment is found for the IPN info, it is saved.
178
-     *
179
-     * @param array              $_req_data            eg $_REQUEST
180
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
-     * @param boolean            $update_txn           whether or not to call
183
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
-     *                                                 or is processed manually ( false like Mijireh )
186
-     * @throws EE_Error
187
-     * @throws Exception
188
-     * @return EE_Payment
189
-     */
190
-    public function process_ipn(
191
-        $_req_data,
192
-        $transaction = null,
193
-        $payment_method = null,
194
-        $update_txn = true,
195
-        $separate_IPN_request = true
196
-    ) {
197
-        EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
-        EE_Processor_Base::set_IPN($separate_IPN_request);
200
-        $obj_for_log = null;
201
-        if ($transaction instanceof EE_Transaction) {
202
-            $obj_for_log = $transaction;
203
-            if ($payment_method instanceof EE_Payment_Method) {
204
-                $obj_for_log = EEM_Payment::instance()->get_one(
205
-                    array(
206
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
-                        'order_by' => array('PAY_timestamp' => 'desc'),
208
-                    )
209
-                );
210
-            }
211
-        } else if ($payment_method instanceof EE_Payment) {
212
-            $obj_for_log = $payment_method;
213
-        }
214
-        $log = EEM_Change_Log::instance()->log(
215
-            EEM_Change_Log::type_gateway,
216
-            array('IPN data received' => $_req_data),
217
-            $obj_for_log
218
-        );
219
-        try {
220
-            /**
221
-             * @var EE_Payment $payment
222
-             */
223
-            $payment = null;
224
-            if ($transaction && $payment_method) {
225
-                /** @type EE_Transaction $transaction */
226
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
-                /** @type EE_Payment_Method $payment_method */
228
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
-                    try {
231
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
-                        $log->set_object($payment);
233
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
234
-                        EEM_Change_Log::instance()->log(
235
-                            EEM_Change_Log::type_gateway,
236
-                            array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
238
-                                'current_url' => EEH_URL::current_url(),
239
-                                'payment'     => $e->getPaymentProperties(),
240
-                                'IPN_data'    => $e->getIpnData(),
241
-                            ),
242
-                            $obj_for_log
243
-                        );
244
-                        return $e->getPayment();
245
-                    }
246
-                } else {
247
-                    // not a payment
248
-                    EE_Error::add_error(
249
-                        sprintf(
250
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
-                            '<br/>',
252
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
253
-                        ),
254
-                        __FILE__, __FUNCTION__, __LINE__
255
-                    );
256
-                }
257
-            } else {
258
-                //that's actually pretty ok. The IPN just wasn't able
259
-                //to identify which transaction or payment method this was for
260
-                // give all active payment methods a chance to claim it
261
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
-                foreach ($active_payment_methods as $active_payment_method) {
263
-                    try {
264
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
-                        $payment_method = $active_payment_method;
266
-                        EEM_Change_Log::instance()->log(
267
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
-                        );
269
-                        break;
270
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
271
-                        EEM_Change_Log::instance()->log(
272
-                            EEM_Change_Log::type_gateway,
273
-                            array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
275
-                                'current_url' => EEH_URL::current_url(),
276
-                                'payment'     => $e->getPaymentProperties(),
277
-                                'IPN_data'    => $e->getIpnData(),
278
-                            ),
279
-                            $obj_for_log
280
-                        );
281
-                        return $e->getPayment();
282
-                    } catch (EE_Error $e) {
283
-                        //that's fine- it apparently couldn't handle the IPN
284
-                    }
285
-                }
286
-            }
287
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
-            if ($payment instanceof EE_Payment) {
289
-                $payment->save();
290
-                //  update the TXN
291
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
-            } else {
293
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
-                if ($payment_method) {
295
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
-                } elseif ($transaction) {
297
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
-                }
299
-            }
300
-            return $payment;
301
-        } catch (EE_Error $e) {
302
-            do_action(
303
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
-                    print_r($transaction, true),
306
-                    print_r($_req_data, true),
307
-                    $e->getMessage()
308
-                )
309
-            );
310
-            throw $e;
311
-        }
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Removes any non-printable illegal characters from the input,
318
-     * which might cause a raucous when trying to insert into the database
319
-     *
320
-     * @param  array $request_data
321
-     * @return array
322
-     */
323
-    protected function _remove_unusable_characters_from_array(array $request_data)
324
-    {
325
-        $return_data = array();
326
-        foreach ($request_data as $key => $value) {
327
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
-        }
329
-        return $return_data;
330
-    }
331
-
332
-
333
-
334
-    /**
335
-     * Removes any non-printable illegal characters from the input,
336
-     * which might cause a raucous when trying to insert into the database
337
-     *
338
-     * @param string $request_data
339
-     * @return string
340
-     */
341
-    protected function _remove_unusable_characters($request_data)
342
-    {
343
-        return preg_replace('/[^[:print:]]/', '', $request_data);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * Should be called just before displaying the payment attempt results to the user,
350
-     * when the payment attempt has finished. Some payment methods may have special
351
-     * logic to perform here. For example, if process_payment() happens on a special request
352
-     * and then the user is redirected to a page that displays the payment's status, this
353
-     * should be called while loading the page that displays the payment's status. If the user is
354
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
-     * provider.
356
-     *
357
-     * @param EE_Transaction|int $transaction
358
-     * @param bool               $update_txn whether or not to call
359
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
-     * @throws \EE_Error
361
-     * @return EE_Payment
362
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
-     */
365
-    public function finalize_payment_for($transaction, $update_txn = true)
366
-    {
367
-        /** @var $transaction EE_Transaction */
368
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
-        $last_payment_method = $transaction->payment_method();
370
-        if ($last_payment_method instanceof EE_Payment_Method) {
371
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
-            return $payment;
374
-        } else {
375
-            return null;
376
-        }
377
-    }
378
-
379
-
380
-
381
-    /**
382
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
-     *
384
-     * @param EE_Payment_Method $payment_method
385
-     * @param EE_Payment        $payment_to_refund
386
-     * @param array             $refund_info
387
-     * @return EE_Payment
388
-     * @throws \EE_Error
389
-     */
390
-    public function process_refund(
391
-        EE_Payment_Method $payment_method,
392
-        EE_Payment $payment_to_refund,
393
-        $refund_info = array()
394
-    ) {
395
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
-        }
399
-        return $payment_to_refund;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * This should be called each time there may have been an update to a
406
-     * payment on a transaction (ie, we asked for a payment to process a
407
-     * payment for a transaction, or we told a payment method about an IPN, or
408
-     * we told a payment method to
409
-     * "finalize_payment_for" (a transaction), or we told a payment method to
410
-     * process a refund. This should handle firing the correct hooks to
411
-     * indicate
412
-     * what exactly happened and updating the transaction appropriately). This
413
-     * could be integrated directly into EE_Transaction upon save, but we want
414
-     * this logic to be separate from 'normal' plain-jane saving and updating
415
-     * of transactions and payments, and to be tied to payment processing.
416
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
-     * of previous code to decide whether or not to save (because the payment passed into
418
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
-     * in which case we only want that payment object for some temporary usage during this request,
420
-     * but we don't want it to be saved).
421
-     *
422
-     * @param EE_Transaction|int $transaction
423
-     * @param EE_Payment         $payment
424
-     * @param boolean            $update_txn
425
-     *                        whether or not to call
426
-     *                        EE_Transaction_Processor::
427
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
428
-     *                        (you can save 1 DB query if you know you're going
429
-     *                        to save it later instead)
430
-     * @param bool               $IPN
431
-     *                        if processing IPNs or other similar payment
432
-     *                        related activities that occur in alternate
433
-     *                        requests than the main one that is processing the
434
-     *                        TXN, then set this to true to check whether the
435
-     *                        TXN is locked before updating
436
-     * @throws \EE_Error
437
-     */
438
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
-    {
440
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
-        /** @type EE_Transaction $transaction */
442
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
-        // can we freely update the TXN at this moment?
444
-        if ($IPN && $transaction->is_locked()) {
445
-            // don't update the transaction at this exact moment
446
-            // because the TXN is active in another request
447
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
-                time(),
449
-                $transaction->ID(),
450
-                $payment->ID()
451
-            );
452
-        } else {
453
-            // verify payment and that it has been saved
454
-            if ($payment instanceof EE_Payment && $payment->ID()) {
455
-                if (
456
-                    $payment->payment_method() instanceof EE_Payment_Method
457
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
-                ) {
459
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
-                    // update TXN registrations with payment info
461
-                    $this->process_registration_payments($transaction, $payment);
462
-                }
463
-                $do_action = $payment->just_approved()
464
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
-                    : $do_action;
466
-            } else {
467
-                // send out notifications
468
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
-            }
471
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
472
-                /** @type EE_Transaction_Payments $transaction_payments */
473
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
-                // set new value for total paid
475
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
476
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
-                if ($update_txn) {
478
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
479
-                }
480
-            }
481
-            // granular hook for others to use.
482
-            do_action($do_action, $transaction, $payment);
483
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
-            //global hook for others to use.
485
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
-        }
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * update registrations REG_paid field after successful payment and link registrations with payment
493
-     *
494
-     * @param EE_Transaction    $transaction
495
-     * @param EE_Payment        $payment
496
-     * @param EE_Registration[] $registrations
497
-     * @throws \EE_Error
498
-     */
499
-    public function process_registration_payments(
500
-        EE_Transaction $transaction,
501
-        EE_Payment $payment,
502
-        $registrations = array()
503
-    ) {
504
-        // only process if payment was successful
505
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
506
-            return;
507
-        }
508
-        //EEM_Registration::instance()->show_next_x_db_queries();
509
-        if (empty($registrations)) {
510
-            // find registrations with monies owing that can receive a payment
511
-            $registrations = $transaction->registrations(
512
-                array(
513
-                    array(
514
-                        // only these reg statuses can receive payments
515
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
-                        'REG_final_price'  => array('!=', 0),
517
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
518
-                    ),
519
-                )
520
-            );
521
-        }
522
-        // still nothing ??!??
523
-        if (empty($registrations)) {
524
-            return;
525
-        }
526
-        // todo: break out the following logic into a separate strategy class
527
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
528
-        // todo: which would apply payments using the capitalist "first come first paid" approach
529
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
531
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
-        $refund = $payment->is_a_refund();
533
-        // how much is available to apply to registrations?
534
-        $available_payment_amount = abs($payment->amount());
535
-        foreach ($registrations as $registration) {
536
-            if ($registration instanceof EE_Registration) {
537
-                // nothing left?
538
-                if ($available_payment_amount <= 0) {
539
-                    break;
540
-                }
541
-                if ($refund) {
542
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
-                } else {
544
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
-                }
546
-            }
547
-        }
548
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
-            EE_Error::add_attention(
550
-                sprintf(
551
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
-                        'event_espresso'),
553
-                    EEH_Template::format_currency($available_payment_amount),
554
-                    implode(', ', array_keys($registrations)),
555
-                    '<br/>',
556
-                    EEH_Template::format_currency($payment->amount())
557
-                ),
558
-                __FILE__, __FUNCTION__, __LINE__
559
-            );
560
-        }
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * update registration REG_paid field after successful payment and link registration with payment
567
-     *
568
-     * @param EE_Registration $registration
569
-     * @param EE_Payment      $payment
570
-     * @param float           $available_payment_amount
571
-     * @return float
572
-     * @throws \EE_Error
573
-     */
574
-    public function process_registration_payment(
575
-        EE_Registration $registration,
576
-        EE_Payment $payment,
577
-        $available_payment_amount = 0.00
578
-    ) {
579
-        $owing = $registration->final_price() - $registration->paid();
580
-        if ($owing > 0) {
581
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
582
-            $payment_amount = min($available_payment_amount, $owing);
583
-            // update $available_payment_amount
584
-            $available_payment_amount -= $payment_amount;
585
-            //calculate and set new REG_paid
586
-            $registration->set_paid($registration->paid() + $payment_amount);
587
-            // now save it
588
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
589
-        }
590
-        return $available_payment_amount;
591
-    }
592
-
593
-
594
-
595
-    /**
596
-     * update registration REG_paid field after successful payment and link registration with payment
597
-     *
598
-     * @param EE_Registration $registration
599
-     * @param EE_Payment      $payment
600
-     * @param float           $payment_amount
601
-     * @return void
602
-     * @throws \EE_Error
603
-     */
604
-    protected function _apply_registration_payment(
605
-        EE_Registration $registration,
606
-        EE_Payment $payment,
607
-        $payment_amount = 0.00
608
-    ) {
609
-        // find any existing reg payment records for this registration and payment
610
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
-        );
613
-        // if existing registration payment exists
614
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
-            // then update that record
616
-            $existing_reg_payment->set_amount($payment_amount);
617
-            $existing_reg_payment->save();
618
-        } else {
619
-            // or add new relation between registration and payment and set amount
620
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
-            // make it stick
622
-            $registration->save();
623
-        }
624
-    }
625
-
626
-
627
-
628
-    /**
629
-     * update registration REG_paid field after refund and link registration with payment
630
-     *
631
-     * @param EE_Registration $registration
632
-     * @param EE_Payment      $payment
633
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
-     * @return float
635
-     * @throws \EE_Error
636
-     */
637
-    public function process_registration_refund(
638
-        EE_Registration $registration,
639
-        EE_Payment $payment,
640
-        $available_refund_amount = 0.00
641
-    ) {
642
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
-        if ($registration->paid() > 0) {
644
-            // ensure $available_refund_amount is NOT negative
645
-            $available_refund_amount = (float)abs($available_refund_amount);
646
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
647
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
648
-            // update $available_payment_amount
649
-            $available_refund_amount -= $refund_amount;
650
-            //calculate and set new REG_paid
651
-            $registration->set_paid($registration->paid() - $refund_amount);
652
-            // convert payment amount back to a negative value for storage in the db
653
-            $refund_amount = (float)abs($refund_amount) * -1;
654
-            // now save it
655
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
656
-        }
657
-        return $available_refund_amount;
658
-    }
659
-
660
-
661
-
662
-    /**
663
-     * Process payments and transaction after payment process completed.
664
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
-     * if this request happens to be processing an IPN,
666
-     * then we will also set the Payment Options Reg Step to completed,
667
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
-     *
669
-     * @param EE_Transaction $transaction
670
-     * @param EE_Payment     $payment
671
-     * @param bool           $IPN
672
-     * @throws \EE_Error
673
-     */
674
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
-    {
676
-        /** @type EE_Transaction_Processor $transaction_processor */
677
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
-        // is the Payment Options Reg Step completed ?
679
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
-        // if the Payment Options Reg Step is completed...
681
-        $revisit = $payment_options_step_completed === true ? true : false;
682
-        // then this is kinda sorta a revisit with regards to payments at least
683
-        $transaction_processor->set_revisit($revisit);
684
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
-        if (
686
-            $IPN
687
-            && $payment_options_step_completed !== true
688
-            && ($payment->is_approved() || $payment->is_pending())
689
-        ) {
690
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
691
-                'payment_options'
692
-            );
693
-        }
694
-        // maybe update status, but don't save transaction just yet
695
-        $transaction->update_status_based_on_total_paid(false);
696
-        // check if 'finalize_registration' step has been completed...
697
-        $finalized = $transaction->reg_step_completed('finalize_registration');
698
-        //  if this is an IPN and the final step has not been initiated
699
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
700
-            // and if it hasn't already been set as being started...
701
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
-        }
703
-        $transaction->save();
704
-        // because the above will return false if the final step was not fully completed, we need to check again...
705
-        if ($IPN && $finalized !== false) {
706
-            // and if we are all good to go, then send out notifications
707
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
-            //ok, now process the transaction according to the payment
709
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
-        }
711
-        // DEBUG LOG
712
-        $payment_method = $payment->payment_method();
713
-        if ($payment_method instanceof EE_Payment_Method) {
714
-            $payment_method_type_obj = $payment_method->type_obj();
715
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
-                $gateway = $payment_method_type_obj->get_gateway();
717
-                if ($gateway instanceof EE_Gateway) {
718
-                    $gateway->log(
719
-                        array(
720
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
-                            'transaction'           => $transaction->model_field_array(),
722
-                            'finalized'             => $finalized,
723
-                            'IPN'                   => $IPN,
724
-                            'deliver_notifications' => has_filter(
725
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
-                            ),
727
-                        ),
728
-                        $payment
729
-                    );
730
-                }
731
-            }
732
-        }
733
-    }
734
-
735
-
736
-
737
-    /**
738
-     * Force posts to PayPal to use TLS v1.2. See:
739
-     * https://core.trac.wordpress.org/ticket/36320
740
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
741
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
-     * This will affect paypal standard, pro, express, and payflow.
743
-     */
744
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
-    {
746
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
-            //instead of the constant because it might not be defined
749
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
-        }
751
-    }
19
+	/**
20
+	 * @var EE_Payment_Processor $_instance
21
+	 * @access    private
22
+	 */
23
+	private static $_instance;
24
+
25
+
26
+
27
+	/**
28
+	 * @singleton method used to instantiate class object
29
+	 * @access    public
30
+	 * @return EE_Payment_Processor instance
31
+	 */
32
+	public static function instance()
33
+	{
34
+		// check if class object is instantiated
35
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
+			self::$_instance = new self();
37
+		}
38
+		return self::$_instance;
39
+	}
40
+
41
+
42
+
43
+	/**
44
+	 *private constructor to prevent direct creation
45
+	 *
46
+	 * @Constructor
47
+	 * @access private
48
+	 */
49
+	private function __construct()
50
+	{
51
+		do_action('AHEE__EE_Payment_Processor__construct');
52
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
59
+	 * appropriately. Saves the payment that is generated
60
+	 *
61
+	 * @param EE_Payment_Method    $payment_method
62
+	 * @param EE_Transaction       $transaction
63
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
+	 *                                           Leave null if payment is for the full amount owing
65
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
+	 *                                           Receive_form_submission() should have
67
+	 *                                           already been called on the billing form
68
+	 *                                           (ie, its inputs should have their normalized values set).
69
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
70
+	 *                                           where to go AFTER the offsite gateway
71
+	 * @param string               $method       like 'CART', indicates who the client who called this was
72
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
+	 * @param boolean              $update_txn   whether or not to call
74
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
+	 * @return \EE_Payment
77
+	 * @throws \EE_Error
78
+	 */
79
+	public function process_payment(
80
+		EE_Payment_Method $payment_method,
81
+		EE_Transaction $transaction,
82
+		$amount = null,
83
+		$billing_form = null,
84
+		$return_url = null,
85
+		$method = 'CART',
86
+		$by_admin = false,
87
+		$update_txn = true,
88
+		$cancel_url = ''
89
+	) {
90
+		if ((float)$amount < 0) {
91
+			throw new EE_Error(
92
+				sprintf(
93
+					__(
94
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
+						'event_espresso'
96
+					),
97
+					$amount,
98
+					$transaction->ID()
99
+				)
100
+			);
101
+		}
102
+		// verify payment method
103
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
+		// verify transaction
105
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
106
+		$transaction->set_payment_method_ID($payment_method->ID());
107
+		// verify payment method type
108
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
+			$payment = $payment_method->type_obj()->process_payment(
110
+				$transaction,
111
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
112
+				$billing_form,
113
+				$return_url,
114
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
+				$method,
116
+				$by_admin
117
+			);
118
+			// check if payment method uses an off-site gateway
119
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
+				// don't process payments for off-site gateways yet because no payment has occurred yet
121
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
+			}
123
+			return $payment;
124
+		} else {
125
+			EE_Error::add_error(
126
+				sprintf(
127
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
+					'<br/>',
129
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
130
+				), __FILE__, __FUNCTION__, __LINE__
131
+			);
132
+			return null;
133
+		}
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * @param EE_Transaction|int $transaction
140
+	 * @param EE_Payment_Method  $payment_method
141
+	 * @throws EE_Error
142
+	 * @return string
143
+	 */
144
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
+	{
146
+		/** @type \EE_Transaction $transaction */
147
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
+		$primary_reg = $transaction->primary_registration();
149
+		if ( ! $primary_reg instanceof EE_Registration) {
150
+			throw new EE_Error(
151
+				sprintf(
152
+					__(
153
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
+						"event_espresso"
155
+					),
156
+					$transaction->ID()
157
+				)
158
+			);
159
+		}
160
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
+		$url = add_query_arg(
162
+			array(
163
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
+				'ee_payment_method' => $payment_method->slug(),
165
+			),
166
+			EE_Registry::instance()->CFG->core->txn_page_url()
167
+		);
168
+		return $url;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
+	 * we can easily find what registration the IPN is for and what payment method.
176
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
177
+	 * If a payment is found for the IPN info, it is saved.
178
+	 *
179
+	 * @param array              $_req_data            eg $_REQUEST
180
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
+	 * @param boolean            $update_txn           whether or not to call
183
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
+	 *                                                 or is processed manually ( false like Mijireh )
186
+	 * @throws EE_Error
187
+	 * @throws Exception
188
+	 * @return EE_Payment
189
+	 */
190
+	public function process_ipn(
191
+		$_req_data,
192
+		$transaction = null,
193
+		$payment_method = null,
194
+		$update_txn = true,
195
+		$separate_IPN_request = true
196
+	) {
197
+		EE_Registry::instance()->load_model('Change_Log');
198
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
+		EE_Processor_Base::set_IPN($separate_IPN_request);
200
+		$obj_for_log = null;
201
+		if ($transaction instanceof EE_Transaction) {
202
+			$obj_for_log = $transaction;
203
+			if ($payment_method instanceof EE_Payment_Method) {
204
+				$obj_for_log = EEM_Payment::instance()->get_one(
205
+					array(
206
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
+						'order_by' => array('PAY_timestamp' => 'desc'),
208
+					)
209
+				);
210
+			}
211
+		} else if ($payment_method instanceof EE_Payment) {
212
+			$obj_for_log = $payment_method;
213
+		}
214
+		$log = EEM_Change_Log::instance()->log(
215
+			EEM_Change_Log::type_gateway,
216
+			array('IPN data received' => $_req_data),
217
+			$obj_for_log
218
+		);
219
+		try {
220
+			/**
221
+			 * @var EE_Payment $payment
222
+			 */
223
+			$payment = null;
224
+			if ($transaction && $payment_method) {
225
+				/** @type EE_Transaction $transaction */
226
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
+				/** @type EE_Payment_Method $payment_method */
228
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
+					try {
231
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
+						$log->set_object($payment);
233
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
234
+						EEM_Change_Log::instance()->log(
235
+							EEM_Change_Log::type_gateway,
236
+							array(
237
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
238
+								'current_url' => EEH_URL::current_url(),
239
+								'payment'     => $e->getPaymentProperties(),
240
+								'IPN_data'    => $e->getIpnData(),
241
+							),
242
+							$obj_for_log
243
+						);
244
+						return $e->getPayment();
245
+					}
246
+				} else {
247
+					// not a payment
248
+					EE_Error::add_error(
249
+						sprintf(
250
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
+							'<br/>',
252
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
253
+						),
254
+						__FILE__, __FUNCTION__, __LINE__
255
+					);
256
+				}
257
+			} else {
258
+				//that's actually pretty ok. The IPN just wasn't able
259
+				//to identify which transaction or payment method this was for
260
+				// give all active payment methods a chance to claim it
261
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
+				foreach ($active_payment_methods as $active_payment_method) {
263
+					try {
264
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
+						$payment_method = $active_payment_method;
266
+						EEM_Change_Log::instance()->log(
267
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
+						);
269
+						break;
270
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
271
+						EEM_Change_Log::instance()->log(
272
+							EEM_Change_Log::type_gateway,
273
+							array(
274
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
275
+								'current_url' => EEH_URL::current_url(),
276
+								'payment'     => $e->getPaymentProperties(),
277
+								'IPN_data'    => $e->getIpnData(),
278
+							),
279
+							$obj_for_log
280
+						);
281
+						return $e->getPayment();
282
+					} catch (EE_Error $e) {
283
+						//that's fine- it apparently couldn't handle the IPN
284
+					}
285
+				}
286
+			}
287
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
+			if ($payment instanceof EE_Payment) {
289
+				$payment->save();
290
+				//  update the TXN
291
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
+			} else {
293
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
+				if ($payment_method) {
295
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
+				} elseif ($transaction) {
297
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
+				}
299
+			}
300
+			return $payment;
301
+		} catch (EE_Error $e) {
302
+			do_action(
303
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
+					print_r($transaction, true),
306
+					print_r($_req_data, true),
307
+					$e->getMessage()
308
+				)
309
+			);
310
+			throw $e;
311
+		}
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Removes any non-printable illegal characters from the input,
318
+	 * which might cause a raucous when trying to insert into the database
319
+	 *
320
+	 * @param  array $request_data
321
+	 * @return array
322
+	 */
323
+	protected function _remove_unusable_characters_from_array(array $request_data)
324
+	{
325
+		$return_data = array();
326
+		foreach ($request_data as $key => $value) {
327
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
+		}
329
+		return $return_data;
330
+	}
331
+
332
+
333
+
334
+	/**
335
+	 * Removes any non-printable illegal characters from the input,
336
+	 * which might cause a raucous when trying to insert into the database
337
+	 *
338
+	 * @param string $request_data
339
+	 * @return string
340
+	 */
341
+	protected function _remove_unusable_characters($request_data)
342
+	{
343
+		return preg_replace('/[^[:print:]]/', '', $request_data);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * Should be called just before displaying the payment attempt results to the user,
350
+	 * when the payment attempt has finished. Some payment methods may have special
351
+	 * logic to perform here. For example, if process_payment() happens on a special request
352
+	 * and then the user is redirected to a page that displays the payment's status, this
353
+	 * should be called while loading the page that displays the payment's status. If the user is
354
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
+	 * provider.
356
+	 *
357
+	 * @param EE_Transaction|int $transaction
358
+	 * @param bool               $update_txn whether or not to call
359
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
+	 * @throws \EE_Error
361
+	 * @return EE_Payment
362
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
+	 */
365
+	public function finalize_payment_for($transaction, $update_txn = true)
366
+	{
367
+		/** @var $transaction EE_Transaction */
368
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
+		$last_payment_method = $transaction->payment_method();
370
+		if ($last_payment_method instanceof EE_Payment_Method) {
371
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
+			return $payment;
374
+		} else {
375
+			return null;
376
+		}
377
+	}
378
+
379
+
380
+
381
+	/**
382
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
+	 *
384
+	 * @param EE_Payment_Method $payment_method
385
+	 * @param EE_Payment        $payment_to_refund
386
+	 * @param array             $refund_info
387
+	 * @return EE_Payment
388
+	 * @throws \EE_Error
389
+	 */
390
+	public function process_refund(
391
+		EE_Payment_Method $payment_method,
392
+		EE_Payment $payment_to_refund,
393
+		$refund_info = array()
394
+	) {
395
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
+		}
399
+		return $payment_to_refund;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * This should be called each time there may have been an update to a
406
+	 * payment on a transaction (ie, we asked for a payment to process a
407
+	 * payment for a transaction, or we told a payment method about an IPN, or
408
+	 * we told a payment method to
409
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
410
+	 * process a refund. This should handle firing the correct hooks to
411
+	 * indicate
412
+	 * what exactly happened and updating the transaction appropriately). This
413
+	 * could be integrated directly into EE_Transaction upon save, but we want
414
+	 * this logic to be separate from 'normal' plain-jane saving and updating
415
+	 * of transactions and payments, and to be tied to payment processing.
416
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
+	 * of previous code to decide whether or not to save (because the payment passed into
418
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
+	 * in which case we only want that payment object for some temporary usage during this request,
420
+	 * but we don't want it to be saved).
421
+	 *
422
+	 * @param EE_Transaction|int $transaction
423
+	 * @param EE_Payment         $payment
424
+	 * @param boolean            $update_txn
425
+	 *                        whether or not to call
426
+	 *                        EE_Transaction_Processor::
427
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
428
+	 *                        (you can save 1 DB query if you know you're going
429
+	 *                        to save it later instead)
430
+	 * @param bool               $IPN
431
+	 *                        if processing IPNs or other similar payment
432
+	 *                        related activities that occur in alternate
433
+	 *                        requests than the main one that is processing the
434
+	 *                        TXN, then set this to true to check whether the
435
+	 *                        TXN is locked before updating
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
+	{
440
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
+		/** @type EE_Transaction $transaction */
442
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
+		// can we freely update the TXN at this moment?
444
+		if ($IPN && $transaction->is_locked()) {
445
+			// don't update the transaction at this exact moment
446
+			// because the TXN is active in another request
447
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
+				time(),
449
+				$transaction->ID(),
450
+				$payment->ID()
451
+			);
452
+		} else {
453
+			// verify payment and that it has been saved
454
+			if ($payment instanceof EE_Payment && $payment->ID()) {
455
+				if (
456
+					$payment->payment_method() instanceof EE_Payment_Method
457
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
+				) {
459
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
+					// update TXN registrations with payment info
461
+					$this->process_registration_payments($transaction, $payment);
462
+				}
463
+				$do_action = $payment->just_approved()
464
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
+					: $do_action;
466
+			} else {
467
+				// send out notifications
468
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
+			}
471
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
472
+				/** @type EE_Transaction_Payments $transaction_payments */
473
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
+				// set new value for total paid
475
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
476
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
+				if ($update_txn) {
478
+					$this->_post_payment_processing($transaction, $payment, $IPN);
479
+				}
480
+			}
481
+			// granular hook for others to use.
482
+			do_action($do_action, $transaction, $payment);
483
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
+			//global hook for others to use.
485
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
+		}
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * update registrations REG_paid field after successful payment and link registrations with payment
493
+	 *
494
+	 * @param EE_Transaction    $transaction
495
+	 * @param EE_Payment        $payment
496
+	 * @param EE_Registration[] $registrations
497
+	 * @throws \EE_Error
498
+	 */
499
+	public function process_registration_payments(
500
+		EE_Transaction $transaction,
501
+		EE_Payment $payment,
502
+		$registrations = array()
503
+	) {
504
+		// only process if payment was successful
505
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
506
+			return;
507
+		}
508
+		//EEM_Registration::instance()->show_next_x_db_queries();
509
+		if (empty($registrations)) {
510
+			// find registrations with monies owing that can receive a payment
511
+			$registrations = $transaction->registrations(
512
+				array(
513
+					array(
514
+						// only these reg statuses can receive payments
515
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
+						'REG_final_price'  => array('!=', 0),
517
+						'REG_final_price*' => array('!=', 'REG_paid', true),
518
+					),
519
+				)
520
+			);
521
+		}
522
+		// still nothing ??!??
523
+		if (empty($registrations)) {
524
+			return;
525
+		}
526
+		// todo: break out the following logic into a separate strategy class
527
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
528
+		// todo: which would apply payments using the capitalist "first come first paid" approach
529
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
531
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
+		$refund = $payment->is_a_refund();
533
+		// how much is available to apply to registrations?
534
+		$available_payment_amount = abs($payment->amount());
535
+		foreach ($registrations as $registration) {
536
+			if ($registration instanceof EE_Registration) {
537
+				// nothing left?
538
+				if ($available_payment_amount <= 0) {
539
+					break;
540
+				}
541
+				if ($refund) {
542
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
+				} else {
544
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
+				}
546
+			}
547
+		}
548
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
+			EE_Error::add_attention(
550
+				sprintf(
551
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
+						'event_espresso'),
553
+					EEH_Template::format_currency($available_payment_amount),
554
+					implode(', ', array_keys($registrations)),
555
+					'<br/>',
556
+					EEH_Template::format_currency($payment->amount())
557
+				),
558
+				__FILE__, __FUNCTION__, __LINE__
559
+			);
560
+		}
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * update registration REG_paid field after successful payment and link registration with payment
567
+	 *
568
+	 * @param EE_Registration $registration
569
+	 * @param EE_Payment      $payment
570
+	 * @param float           $available_payment_amount
571
+	 * @return float
572
+	 * @throws \EE_Error
573
+	 */
574
+	public function process_registration_payment(
575
+		EE_Registration $registration,
576
+		EE_Payment $payment,
577
+		$available_payment_amount = 0.00
578
+	) {
579
+		$owing = $registration->final_price() - $registration->paid();
580
+		if ($owing > 0) {
581
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
582
+			$payment_amount = min($available_payment_amount, $owing);
583
+			// update $available_payment_amount
584
+			$available_payment_amount -= $payment_amount;
585
+			//calculate and set new REG_paid
586
+			$registration->set_paid($registration->paid() + $payment_amount);
587
+			// now save it
588
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
589
+		}
590
+		return $available_payment_amount;
591
+	}
592
+
593
+
594
+
595
+	/**
596
+	 * update registration REG_paid field after successful payment and link registration with payment
597
+	 *
598
+	 * @param EE_Registration $registration
599
+	 * @param EE_Payment      $payment
600
+	 * @param float           $payment_amount
601
+	 * @return void
602
+	 * @throws \EE_Error
603
+	 */
604
+	protected function _apply_registration_payment(
605
+		EE_Registration $registration,
606
+		EE_Payment $payment,
607
+		$payment_amount = 0.00
608
+	) {
609
+		// find any existing reg payment records for this registration and payment
610
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
611
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
612
+		);
613
+		// if existing registration payment exists
614
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
615
+			// then update that record
616
+			$existing_reg_payment->set_amount($payment_amount);
617
+			$existing_reg_payment->save();
618
+		} else {
619
+			// or add new relation between registration and payment and set amount
620
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
621
+			// make it stick
622
+			$registration->save();
623
+		}
624
+	}
625
+
626
+
627
+
628
+	/**
629
+	 * update registration REG_paid field after refund and link registration with payment
630
+	 *
631
+	 * @param EE_Registration $registration
632
+	 * @param EE_Payment      $payment
633
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
634
+	 * @return float
635
+	 * @throws \EE_Error
636
+	 */
637
+	public function process_registration_refund(
638
+		EE_Registration $registration,
639
+		EE_Payment $payment,
640
+		$available_refund_amount = 0.00
641
+	) {
642
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
643
+		if ($registration->paid() > 0) {
644
+			// ensure $available_refund_amount is NOT negative
645
+			$available_refund_amount = (float)abs($available_refund_amount);
646
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
647
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
648
+			// update $available_payment_amount
649
+			$available_refund_amount -= $refund_amount;
650
+			//calculate and set new REG_paid
651
+			$registration->set_paid($registration->paid() - $refund_amount);
652
+			// convert payment amount back to a negative value for storage in the db
653
+			$refund_amount = (float)abs($refund_amount) * -1;
654
+			// now save it
655
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
656
+		}
657
+		return $available_refund_amount;
658
+	}
659
+
660
+
661
+
662
+	/**
663
+	 * Process payments and transaction after payment process completed.
664
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
665
+	 * if this request happens to be processing an IPN,
666
+	 * then we will also set the Payment Options Reg Step to completed,
667
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
668
+	 *
669
+	 * @param EE_Transaction $transaction
670
+	 * @param EE_Payment     $payment
671
+	 * @param bool           $IPN
672
+	 * @throws \EE_Error
673
+	 */
674
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
675
+	{
676
+		/** @type EE_Transaction_Processor $transaction_processor */
677
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
678
+		// is the Payment Options Reg Step completed ?
679
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
680
+		// if the Payment Options Reg Step is completed...
681
+		$revisit = $payment_options_step_completed === true ? true : false;
682
+		// then this is kinda sorta a revisit with regards to payments at least
683
+		$transaction_processor->set_revisit($revisit);
684
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
685
+		if (
686
+			$IPN
687
+			&& $payment_options_step_completed !== true
688
+			&& ($payment->is_approved() || $payment->is_pending())
689
+		) {
690
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
691
+				'payment_options'
692
+			);
693
+		}
694
+		// maybe update status, but don't save transaction just yet
695
+		$transaction->update_status_based_on_total_paid(false);
696
+		// check if 'finalize_registration' step has been completed...
697
+		$finalized = $transaction->reg_step_completed('finalize_registration');
698
+		//  if this is an IPN and the final step has not been initiated
699
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
700
+			// and if it hasn't already been set as being started...
701
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
702
+		}
703
+		$transaction->save();
704
+		// because the above will return false if the final step was not fully completed, we need to check again...
705
+		if ($IPN && $finalized !== false) {
706
+			// and if we are all good to go, then send out notifications
707
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
708
+			//ok, now process the transaction according to the payment
709
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
710
+		}
711
+		// DEBUG LOG
712
+		$payment_method = $payment->payment_method();
713
+		if ($payment_method instanceof EE_Payment_Method) {
714
+			$payment_method_type_obj = $payment_method->type_obj();
715
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
716
+				$gateway = $payment_method_type_obj->get_gateway();
717
+				if ($gateway instanceof EE_Gateway) {
718
+					$gateway->log(
719
+						array(
720
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
721
+							'transaction'           => $transaction->model_field_array(),
722
+							'finalized'             => $finalized,
723
+							'IPN'                   => $IPN,
724
+							'deliver_notifications' => has_filter(
725
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
726
+							),
727
+						),
728
+						$payment
729
+					);
730
+				}
731
+			}
732
+		}
733
+	}
734
+
735
+
736
+
737
+	/**
738
+	 * Force posts to PayPal to use TLS v1.2. See:
739
+	 * https://core.trac.wordpress.org/ticket/36320
740
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
741
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
742
+	 * This will affect paypal standard, pro, express, and payflow.
743
+	 */
744
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
745
+	{
746
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
747
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
748
+			//instead of the constant because it might not be defined
749
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
750
+		}
751
+	}
752 752
 }
Please login to merge, or discard this patch.
core/libraries/payment_methods/EEI_Payment_Method_Interfaces.php 1 patch
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
  *
6 6
  * allows gateways to be used by different systems other than Event Espresso
7 7
  */
8
-interface EEI_Payment extends EEI_Base{
8
+interface EEI_Payment extends EEI_Base {
9 9
 
10 10
 	/**
11 11
 	 * @return string indicating which the payment is approved, pending, cancelled or failed
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 /**
154 154
  * Interface EEI_Payment_Method
155 155
  */
156
-interface EEI_Payment_Method{
156
+interface EEI_Payment_Method {
157 157
 
158 158
 }
159 159
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	 * @param string $model_name
173 173
 	 * @return EE_Log
174 174
 	 */
175
-	public function gateway_log($message,$id,$model_name);
175
+	public function gateway_log($message, $id, $model_name);
176 176
 }
177 177
 
178 178
 
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 2 patches
Indentation   +98 added lines, -100 removed lines patch added patch discarded remove patch
@@ -44,77 +44,76 @@  discard block
 block discarded – undo
44 44
 	 */
45 45
 	protected $_image_url;
46 46
 
47
-    /**
48
-     * gateway URL variable
49
-     *
50
-     * @var string
51
-     */
52
-    protected $_base_gateway_url = '';
53
-
54
-
55
-
56
-    /**
57
-     * EEG_Paypal_Express constructor.
58
-     */
59
-    public function __construct()
60
-    {
61
-        $this->_currencies_supported = array(
62
-            'USD',
63
-            'AUD',
64
-            'BRL',
65
-            'CAD',
66
-            'CZK',
67
-            'DKK',
68
-            'EUR',
69
-            'HKD',
70
-            'HUF',
71
-            'ILS',
72
-            'JPY',
73
-            'MYR',
74
-            'MXN',
75
-            'NOK',
76
-            'NZD',
77
-            'PHP',
78
-            'PLN',
79
-            'GBP',
80
-            'RUB',
81
-            'SGD',
82
-            'SEK',
83
-            'CHF',
84
-            'TWD',
85
-            'THB',
86
-            'TRY'
87
-        );
88
-        parent::__construct();
89
-    }
90
-
91
-
92
-
93
-    /**
94
-	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
47
+	/**
48
+	 * gateway URL variable
49
+	 *
50
+	 * @var string
51
+	 */
52
+	protected $_base_gateway_url = '';
53
+
54
+
55
+
56
+	/**
57
+	 * EEG_Paypal_Express constructor.
58
+	 */
59
+	public function __construct()
60
+	{
61
+		$this->_currencies_supported = array(
62
+			'USD',
63
+			'AUD',
64
+			'BRL',
65
+			'CAD',
66
+			'CZK',
67
+			'DKK',
68
+			'EUR',
69
+			'HKD',
70
+			'HUF',
71
+			'ILS',
72
+			'JPY',
73
+			'MYR',
74
+			'MXN',
75
+			'NOK',
76
+			'NZD',
77
+			'PHP',
78
+			'PLN',
79
+			'GBP',
80
+			'RUB',
81
+			'SGD',
82
+			'SEK',
83
+			'CHF',
84
+			'TWD',
85
+			'THB',
86
+			'TRY'
87
+		);
88
+		parent::__construct();
89
+	}
90
+
95 91
 
92
+
93
+	/**
94
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
96 95
 	 *
97 96
 *@param array $settings_array
98 97
 	 */
99 98
 	public function set_settings( $settings_array ) {
100 99
 		parent::set_settings($settings_array);
101 100
 		// Redirect URL.
102
-        $this->_base_gateway_url = $this->_debug_mode
103
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
104
-            : 'https://api-3t.paypal.com/nvp';
101
+		$this->_base_gateway_url = $this->_debug_mode
102
+			? 'https://api-3t.sandbox.paypal.com/nvp'
103
+			: 'https://api-3t.paypal.com/nvp';
105 104
 	}
106 105
 
107 106
 
108 107
 
109
-    /**
110
-     * @param EEI_Payment $payment
111
-     * @param array       $billing_info
112
-     * @param string      $return_url
113
-     * @param string      $notify_url
114
-     * @param string      $cancel_url
115
-     * @return \EE_Payment|\EEI_Payment
116
-     * @throws \EE_Error
117
-     */
108
+	/**
109
+	 * @param EEI_Payment $payment
110
+	 * @param array       $billing_info
111
+	 * @param string      $return_url
112
+	 * @param string      $notify_url
113
+	 * @param string      $cancel_url
114
+	 * @return \EE_Payment|\EEI_Payment
115
+	 * @throws \EE_Error
116
+	 */
118 117
 	public function set_redirection_info( $payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL ) {
119 118
 		if ( ! $payment instanceof EEI_Payment ) {
120 119
 			$payment->set_gateway_response( __( 'Error. No associated payment was found.', 'event_espresso' ) );
@@ -202,9 +201,9 @@  discard block
 block discarded – undo
202 201
 				$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
203 202
 				// Item quantity.
204 203
 				$token_request_dtls['L_PAYMENTREQUEST_0_QTY'.$item_num] = 1;
205
-                // Digital item is sold.
206
-                $token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
207
-                $item_num++;
204
+				// Digital item is sold.
205
+				$token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY'.$item_num] = 'Physical';
206
+				$item_num++;
208 207
 			}
209 208
 		} else {
210 209
 			// Just one Item.
@@ -272,7 +271,6 @@  discard block
 block discarded – undo
272 271
 
273 272
 
274 273
 	/**
275
-
276 274
 	 *  @param array $update_info {
277 275
 	 *	  @type string $gateway_txn_id
278 276
 	 *	  @type string status an EEMI_Payment status
@@ -292,8 +290,8 @@  discard block
 block discarded – undo
292 290
 				return $payment;
293 291
 			}
294 292
 			$primary_registrant = $transaction->primary_registration();
295
-            $payment_details = $payment->details();
296
-            // Check if we still have the token.
293
+			$payment_details = $payment->details();
294
+			// Check if we still have the token.
297 295
 			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN']) ) {
298 296
 				$payment->set_status( $this->_pay_model->failed_status() );
299 297
 				return $payment;
@@ -402,36 +400,36 @@  discard block
 block discarded – undo
402 400
 	 */
403 401
 	public function _ppExpress_check_response( $request_response ) {
404 402
 		if (empty($request_response['body']) || is_wp_error( $request_response ) ) {
405
-            // If we got here then there was an error in this request.
406
-            return array('status' => false, 'args' => $request_response);
407
-        }
408
-        $response_args = array();
409
-        parse_str( urldecode($request_response['body']), $response_args );
410
-        if ( ! isset($response_args['ACK'])) {
411
-            return array('status' => false, 'args' => $request_response);
412
-        }
413
-        if (
414
-            $response_args['ACK'] === 'Success'
415
-            && (
416
-                isset($response_args['PAYERID'])
417
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
418
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
419
-                || isset($response_args['TOKEN'])
420
-            )
421
-        ) {
422
-            // Response status OK, return response parameters for further processing.
423
-            return array('status' => true, 'args' => $response_args);
424
-        } else {
425
-            $errors = $this->_get_errors($response_args);
426
-            return array('status' => false, 'args' => $errors);
427
-        }
403
+			// If we got here then there was an error in this request.
404
+			return array('status' => false, 'args' => $request_response);
405
+		}
406
+		$response_args = array();
407
+		parse_str( urldecode($request_response['body']), $response_args );
408
+		if ( ! isset($response_args['ACK'])) {
409
+			return array('status' => false, 'args' => $request_response);
410
+		}
411
+		if (
412
+			$response_args['ACK'] === 'Success'
413
+			&& (
414
+				isset($response_args['PAYERID'])
415
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
416
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
417
+				|| isset($response_args['TOKEN'])
418
+			)
419
+		) {
420
+			// Response status OK, return response parameters for further processing.
421
+			return array('status' => true, 'args' => $response_args);
422
+		} else {
423
+			$errors = $this->_get_errors($response_args);
424
+			return array('status' => false, 'args' => $errors);
425
+		}
428 426
 	}
429 427
 
430 428
 
431 429
 	/**
432
-     *  Log a "Cleared" request.
433
-     *
434
-     * @param array $request
430
+	 *  Log a "Cleared" request.
431
+	 *
432
+	 * @param array $request
435 433
 	 * @param EEI_Payment  $payment
436 434
 	 * @param string  		$info
437 435
 	 * @return void
@@ -454,17 +452,17 @@  discard block
 block discarded – undo
454 452
 		$n = 0;
455 453
 		while ( isset($data_array["L_ERRORCODE{$n}"]) ) {
456 454
 			$l_error_code = isset($data_array["L_ERRORCODE{$n}"])
457
-                ? $data_array["L_ERRORCODE{$n}"]
458
-                : '';
455
+				? $data_array["L_ERRORCODE{$n}"]
456
+				: '';
459 457
 			$l_severity_code = isset($data_array["L_SEVERITYCODE{$n}"])
460
-                ? $data_array["L_SEVERITYCODE{$n}"]
461
-                : '';
458
+				? $data_array["L_SEVERITYCODE{$n}"]
459
+				: '';
462 460
 			$l_short_message = isset($data_array["L_SHORTMESSAGE{$n}"])
463
-                ? $data_array["L_SHORTMESSAGE{$n}"]
464
-                : '';
461
+				? $data_array["L_SHORTMESSAGE{$n}"]
462
+				: '';
465 463
 			$l_long_message = isset($data_array["L_LONGMESSAGE{$n}"])
466
-                ? $data_array["L_LONGMESSAGE{$n}"]
467
-                : '';
464
+				? $data_array["L_LONGMESSAGE{$n}"]
465
+				: '';
468 466
 
469 467
 			if ( $n === 0 ) {
470 468
 				$errors = array(
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' )) { exit('NO direct script access allowed'); }
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('NO direct script access allowed'); }
2 2
 
3 3
 /**
4 4
  * ----------------------------------------------
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 	 *
97 97
 *@param array $settings_array
98 98
 	 */
99
-	public function set_settings( $settings_array ) {
99
+	public function set_settings($settings_array) {
100 100
 		parent::set_settings($settings_array);
101 101
 		// Redirect URL.
102 102
         $this->_base_gateway_url = $this->_debug_mode
@@ -115,19 +115,19 @@  discard block
 block discarded – undo
115 115
      * @return \EE_Payment|\EEI_Payment
116 116
      * @throws \EE_Error
117 117
      */
118
-	public function set_redirection_info( $payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL ) {
119
-		if ( ! $payment instanceof EEI_Payment ) {
120
-			$payment->set_gateway_response( __( 'Error. No associated payment was found.', 'event_espresso' ) );
121
-			$payment->set_status( $this->_pay_model->failed_status() );
118
+	public function set_redirection_info($payment, $billing_info = array(), $return_url = NULL, $notify_url = NULL, $cancel_url = NULL) {
119
+		if ( ! $payment instanceof EEI_Payment) {
120
+			$payment->set_gateway_response(__('Error. No associated payment was found.', 'event_espresso'));
121
+			$payment->set_status($this->_pay_model->failed_status());
122 122
 			return $payment;
123 123
 		}
124 124
 		$transaction = $payment->transaction();
125
-		if ( ! $transaction instanceof EEI_Transaction ) {
126
-			$payment->set_gateway_response( __( 'Could not process this payment because it has no associated transaction.', 'event_espresso' ) );
127
-			$payment->set_status( $this->_pay_model->failed_status() );
125
+		if ( ! $transaction instanceof EEI_Transaction) {
126
+			$payment->set_gateway_response(__('Could not process this payment because it has no associated transaction.', 'event_espresso'));
127
+			$payment->set_status($this->_pay_model->failed_status());
128 128
 			return $payment;
129 129
 		}
130
-		$order_description = substr( $this->_format_order_description($payment), 0, 127 );
130
+		$order_description = substr($this->_format_order_description($payment), 0, 127);
131 131
 		$primary_registration = $transaction->primary_registration();
132 132
 		$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee() : false;
133 133
 		$locale = explode('-', get_bloginfo('language'));
@@ -141,37 +141,37 @@  discard block
 block discarded – undo
141 141
 			'RETURNURL' => $return_url,
142 142
 			'CANCELURL' => $cancel_url,
143 143
 			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
144
-			'SOLUTIONTYPE' => 'Sole',	// Buyer does not need to create a PayPal account to check out. This is referred to as PayPal Account Optional.
145
-			'BUTTONSOURCE' => 'EventEspresso_SP',//EE will blow up if you change this
144
+			'SOLUTIONTYPE' => 'Sole', // Buyer does not need to create a PayPal account to check out. This is referred to as PayPal Account Optional.
145
+			'BUTTONSOURCE' => 'EventEspresso_SP', //EE will blow up if you change this
146 146
 			'LOCALECODE' => $locale[1]	// Locale of the pages displayed by PayPal during Express Checkout.
147 147
 		);
148 148
 
149 149
 		// Show itemized list.
150
-		if ( $this->_money->compare_floats( $payment->amount(), $transaction->total(), '==' ) ) {
150
+		if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
151 151
 			$item_num = 0;
152 152
 			$itemized_sum = 0;
153 153
 			$total_line_items = $transaction->total_line_item();
154 154
 			// Go through each item in the list.
155
-			foreach ( $total_line_items->get_items() as $line_item ) {
156
-				if ( $line_item instanceof EE_Line_Item ) {
155
+			foreach ($total_line_items->get_items() as $line_item) {
156
+				if ($line_item instanceof EE_Line_Item) {
157 157
 					// PayPal doesn't like line items with 0.00 amount, so we may skip those.
158
-					if ( EEH_Money::compare_floats( $line_item->total(), '0.00', '==' ) ) {
158
+					if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
159 159
 						continue;
160 160
 					}
161 161
 
162 162
 					$unit_price = $line_item->unit_price();
163 163
 					$line_item_quantity = $line_item->quantity();
164 164
 					// This is a discount.
165
-					if ( $line_item->is_percent() ) {
165
+					if ($line_item->is_percent()) {
166 166
 						$unit_price = $line_item->total();
167 167
 						$line_item_quantity = 1;
168 168
 					}
169 169
 					// Item Name.
170
-					$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr($this->_format_line_item_name( $line_item, $payment), 0, 127);
170
+					$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr($this->_format_line_item_name($line_item, $payment), 0, 127);
171 171
 					// Item description.
172
-					$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = substr($this->_format_line_item_desc( $line_item, $payment), 0, 127);
172
+					$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = substr($this->_format_line_item_desc($line_item, $payment), 0, 127);
173 173
 					// Cost of individual item.
174
-					$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency( $unit_price );
174
+					$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency($unit_price);
175 175
 					// Item Number.
176 176
 					$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
177 177
 					// Item quantity.
@@ -188,16 +188,16 @@  discard block
 block discarded – undo
188 188
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
189 189
 			$token_request_dtls['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
190 190
 
191
-			$itemized_sum_diff_from_txn_total = round( $transaction->total() - $itemized_sum - $total_line_items->get_total_tax(), 2 );
191
+			$itemized_sum_diff_from_txn_total = round($transaction->total() - $itemized_sum - $total_line_items->get_total_tax(), 2);
192 192
 			// If we were not able to recognize some item like promotion, surcharge or cancellation,
193 193
 			// add the difference as an extra line item.
194
-			if ( $this->_money->compare_floats( $itemized_sum_diff_from_txn_total, 0, '!=' ) ) {
194
+			if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
195 195
 				// Item Name.
196
-				$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr( __( 'Other (promotion/surcharge/cancellation)', 'event_espresso' ), 0, 127 );
196
+				$token_request_dtls['L_PAYMENTREQUEST_0_NAME'.$item_num] = substr(__('Other (promotion/surcharge/cancellation)', 'event_espresso'), 0, 127);
197 197
 				// Item description.
198 198
 				$token_request_dtls['L_PAYMENTREQUEST_0_DESC'.$item_num] = '';
199 199
 				// Cost of individual item.
200
-				$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency( $itemized_sum_diff_from_txn_total );
200
+				$token_request_dtls['L_PAYMENTREQUEST_0_AMT'.$item_num] = $this->format_currency($itemized_sum_diff_from_txn_total);
201 201
 				// Item Number.
202 202
 				$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER'.$item_num] = $item_num + 1;
203 203
 				// Item quantity.
@@ -209,11 +209,11 @@  discard block
 block discarded – undo
209 209
 		} else {
210 210
 			// Just one Item.
211 211
 			// Item Name.
212
-			$token_request_dtls['L_PAYMENTREQUEST_0_NAME0'] = substr( $this->_format_partial_payment_line_item_name($payment), 0, 127 );
212
+			$token_request_dtls['L_PAYMENTREQUEST_0_NAME0'] = substr($this->_format_partial_payment_line_item_name($payment), 0, 127);
213 213
 			// Item description.
214
-			$token_request_dtls['L_PAYMENTREQUEST_0_DESC0'] = substr( $this->_format_partial_payment_line_item_desc($payment), 0, 127 );
214
+			$token_request_dtls['L_PAYMENTREQUEST_0_DESC0'] = substr($this->_format_partial_payment_line_item_desc($payment), 0, 127);
215 215
 			// Cost of individual item.
216
-			$token_request_dtls['L_PAYMENTREQUEST_0_AMT0'] = $this->format_currency( $payment->amount() );
216
+			$token_request_dtls['L_PAYMENTREQUEST_0_AMT0'] = $this->format_currency($payment->amount());
217 217
 			// Item Number.
218 218
 			$token_request_dtls['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
219 219
 			// Item quantity.
@@ -221,14 +221,14 @@  discard block
 block discarded – undo
221 221
 			// Digital item is sold.
222 222
 			$token_request_dtls['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
223 223
 			// Item's sales S/H and tax amount.
224
-			$token_request_dtls['PAYMENTREQUEST_0_ITEMAMT'] = $this->format_currency( $payment->amount() );
224
+			$token_request_dtls['PAYMENTREQUEST_0_ITEMAMT'] = $this->format_currency($payment->amount());
225 225
 			$token_request_dtls['PAYMENTREQUEST_0_TAXAMT'] = '0';
226 226
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
227 227
 			$token_request_dtls['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
228 228
 		}
229 229
 		// Automatically filling out shipping and contact information.
230
-		if ( $this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee ) {
231
-			$token_request_dtls['NOSHIPPING'] = '2';	//  If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
230
+		if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
231
+			$token_request_dtls['NOSHIPPING'] = '2'; //  If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
232 232
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
233 233
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
234 234
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
@@ -237,14 +237,14 @@  discard block
 block discarded – undo
237 237
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
238 238
 			$token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
239 239
 			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
240
-		} elseif ( ! $this->_request_shipping_addr ) {
240
+		} elseif ( ! $this->_request_shipping_addr) {
241 241
 			// Do not request shipping details on the PP Checkout page.
242 242
 			$token_request_dtls['NOSHIPPING'] = '1';
243 243
 			$token_request_dtls['REQCONFIRMSHIPPING'] = '0';
244 244
 
245 245
 		}
246 246
 		// Used a business/personal logo on the PayPal page.
247
-		if ( ! empty($this->_image_url) ) {
247
+		if ( ! empty($this->_image_url)) {
248 248
 			$token_request_dtls['LOGOIMG'] = $this->_image_url;
249 249
 		}
250 250
 		$token_request_dtls = apply_filters( 
@@ -253,23 +253,23 @@  discard block
 block discarded – undo
253 253
 			$this 
254 254
 		);
255 255
 		// Request PayPal token.
256
-		$token_request_response = $this->_ppExpress_request( $token_request_dtls, 'Payment Token', $payment );
257
-		$token_rstatus = $this->_ppExpress_check_response( $token_request_response );
258
-		$response_args = ( isset($token_rstatus['args']) && is_array($token_rstatus['args']) ) ? $token_rstatus['args'] : array();
259
-		if ( $token_rstatus['status'] ) {
256
+		$token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
257
+		$token_rstatus = $this->_ppExpress_check_response($token_request_response);
258
+		$response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args'])) ? $token_rstatus['args'] : array();
259
+		if ($token_rstatus['status']) {
260 260
 			// We got the Token so we may continue with the payment and redirect the client.
261
-			$payment->set_details( $response_args );
261
+			$payment->set_details($response_args);
262 262
 
263 263
 			$gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
264
-			$payment->set_redirect_url( $gateway_url . '/checkoutnow?useraction=commit&cmd=_express-checkout&token=' . $response_args['TOKEN'] );
264
+			$payment->set_redirect_url($gateway_url.'/checkoutnow?useraction=commit&cmd=_express-checkout&token='.$response_args['TOKEN']);
265 265
 		} else {
266
-			if ( isset($response_args['L_ERRORCODE']) ) {
267
-				$payment->set_gateway_response( $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE'] );
266
+			if (isset($response_args['L_ERRORCODE'])) {
267
+				$payment->set_gateway_response($response_args['L_ERRORCODE'].'; '.$response_args['L_SHORTMESSAGE']);
268 268
 			} else {
269
-				$payment->set_gateway_response( __( 'Error occurred while trying to setup the Express Checkout.', 'event_espresso' ) );
269
+				$payment->set_gateway_response(__('Error occurred while trying to setup the Express Checkout.', 'event_espresso'));
270 270
 			}
271
-			$payment->set_details( $response_args );
272
-			$payment->set_status( $this->_pay_model->failed_status() );
271
+			$payment->set_details($response_args);
272
+			$payment->set_status($this->_pay_model->failed_status());
273 273
 		}
274 274
 
275 275
 		return $payment;
@@ -285,22 +285,22 @@  discard block
 block discarded – undo
285 285
 	 *  @param EEI_Transaction $transaction
286 286
 	 *  @return EEI_Payment
287 287
 	 */
288
-	public function handle_payment_update( $update_info, $transaction ) {
288
+	public function handle_payment_update($update_info, $transaction) {
289 289
 		$payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
290 290
 
291
-		if ( $payment instanceof EEI_Payment ) {
292
-			$this->log( array( 'Return from Authorization' => $update_info ), $payment );
291
+		if ($payment instanceof EEI_Payment) {
292
+			$this->log(array('Return from Authorization' => $update_info), $payment);
293 293
 			$transaction = $payment->transaction();
294
-			if ( ! $transaction instanceof EEI_Transaction ) {
295
-				$payment->set_gateway_response( __( 'Could not process this payment because it has no associated transaction.', 'event_espresso' ) );
296
-				$payment->set_status( $this->_pay_model->failed_status() );
294
+			if ( ! $transaction instanceof EEI_Transaction) {
295
+				$payment->set_gateway_response(__('Could not process this payment because it has no associated transaction.', 'event_espresso'));
296
+				$payment->set_status($this->_pay_model->failed_status());
297 297
 				return $payment;
298 298
 			}
299 299
 			$primary_registrant = $transaction->primary_registration();
300 300
             $payment_details = $payment->details();
301 301
             // Check if we still have the token.
302
-			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN']) ) {
303
-				$payment->set_status( $this->_pay_model->failed_status() );
302
+			if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
303
+				$payment->set_status($this->_pay_model->failed_status());
304 304
 				return $payment;
305 305
 			}
306 306
 
@@ -309,10 +309,10 @@  discard block
 block discarded – undo
309 309
 				'TOKEN' => $payment_details['TOKEN']
310 310
 			);
311 311
 			// Request Customer Details.
312
-			$cdetails_request_response = $this->_ppExpress_request( $cdetails_request_dtls, 'Customer Details', $payment );
313
-			$cdetails_rstatus = $this->_ppExpress_check_response( $cdetails_request_response );
314
-			$cdata_response_args = ( isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']) ) ? $cdetails_rstatus['args'] : array();
315
-			if ( $cdetails_rstatus['status'] ) {
312
+			$cdetails_request_response = $this->_ppExpress_request($cdetails_request_dtls, 'Customer Details', $payment);
313
+			$cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
314
+			$cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args'])) ? $cdetails_rstatus['args'] : array();
315
+			if ($cdetails_rstatus['status']) {
316 316
 				// We got the PayerID so now we can Complete the transaction.
317 317
 				$docheckout_request_dtls = array(
318 318
 					'METHOD' => 'DoExpressCheckoutPayment',
@@ -323,39 +323,39 @@  discard block
 block discarded – undo
323 323
 					'PAYMENTREQUEST_0_CURRENCYCODE' => $payment->currency_code()
324 324
 				);
325 325
 				// Payment Checkout/Capture.
326
-				$docheckout_request_response = $this->_ppExpress_request( $docheckout_request_dtls, 'Do Payment', $payment );
327
-				$docheckout_rstatus = $this->_ppExpress_check_response( $docheckout_request_response );
328
-				$docheckout_response_args = ( isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']) ) ? $docheckout_rstatus['args'] : array();
329
-				if ( $docheckout_rstatus['status'] ) {
326
+				$docheckout_request_response = $this->_ppExpress_request($docheckout_request_dtls, 'Do Payment', $payment);
327
+				$docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
328
+				$docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args'])) ? $docheckout_rstatus['args'] : array();
329
+				if ($docheckout_rstatus['status']) {
330 330
 					// All is well, payment approved.
331 331
 					$primary_registration_code = $primary_registrant instanceof EE_Registration ? $primary_registrant->reg_code() : '';
332
-					$payment->set_extra_accntng( $primary_registration_code );
333
-					$payment->set_amount( isset($docheckout_response_args['PAYMENTINFO_0_AMT']) ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT'] : 0 );
334
-					$payment->set_txn_id_chq_nmbr( isset( $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] ) ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] : null );
335
-					$payment->set_details( $cdata_response_args );
336
-					$payment->set_gateway_response( isset( $docheckout_response_args['PAYMENTINFO_0_ACK'] ) ? $docheckout_response_args['PAYMENTINFO_0_ACK'] : '' );
337
-					$payment->set_status( $this->_pay_model->approved_status() );
332
+					$payment->set_extra_accntng($primary_registration_code);
333
+					$payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT']) ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT'] : 0);
334
+					$payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']) ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'] : null);
335
+					$payment->set_details($cdata_response_args);
336
+					$payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK']) ? $docheckout_response_args['PAYMENTINFO_0_ACK'] : '');
337
+					$payment->set_status($this->_pay_model->approved_status());
338 338
 				} else {
339
-					if ( isset($docheckout_response_args['L_ERRORCODE']) ) {
340
-						$payment->set_gateway_response( $docheckout_response_args['L_ERRORCODE'] . '; ' . $docheckout_response_args['L_SHORTMESSAGE'] );
339
+					if (isset($docheckout_response_args['L_ERRORCODE'])) {
340
+						$payment->set_gateway_response($docheckout_response_args['L_ERRORCODE'].'; '.$docheckout_response_args['L_SHORTMESSAGE']);
341 341
 					} else {
342
-						$payment->set_gateway_response( __( 'Error occurred while trying to Capture the funds.', 'event_espresso' ) );
342
+						$payment->set_gateway_response(__('Error occurred while trying to Capture the funds.', 'event_espresso'));
343 343
 					}
344
-					$payment->set_details( $docheckout_response_args );
345
-					$payment->set_status( $this->_pay_model->declined_status() );
344
+					$payment->set_details($docheckout_response_args);
345
+					$payment->set_status($this->_pay_model->declined_status());
346 346
 				}
347 347
 			} else {
348
-				if ( isset($cdata_response_args['L_ERRORCODE']) ) {
349
-					$payment->set_gateway_response( $cdata_response_args['L_ERRORCODE'] . '; ' . $cdata_response_args['L_SHORTMESSAGE'] );
348
+				if (isset($cdata_response_args['L_ERRORCODE'])) {
349
+					$payment->set_gateway_response($cdata_response_args['L_ERRORCODE'].'; '.$cdata_response_args['L_SHORTMESSAGE']);
350 350
 				} else {
351
-					$payment->set_gateway_response( __( 'Error occurred while trying to get payment Details from PayPal.', 'event_espresso' ) );
351
+					$payment->set_gateway_response(__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso'));
352 352
 				}
353
-				$payment->set_details( $cdata_response_args );
354
-				$payment->set_status( $this->_pay_model->failed_status() );
353
+				$payment->set_details($cdata_response_args);
354
+				$payment->set_status($this->_pay_model->failed_status());
355 355
 			}
356 356
 		} else {
357
-			$payment->set_gateway_response( __( 'Error occurred while trying to process the payment.', 'event_espresso' ) );
358
-			$payment->set_status( $this->_pay_model->failed_status() );
357
+			$payment->set_gateway_response(__('Error occurred while trying to process the payment.', 'event_espresso'));
358
+			$payment->set_status($this->_pay_model->failed_status());
359 359
 		}
360 360
 
361 361
 		return $payment;
@@ -370,16 +370,16 @@  discard block
 block discarded – undo
370 370
 	 *  @param EEI_Payment  $payment
371 371
 	 *	@return mixed
372 372
 	 */
373
-	public function _ppExpress_request( $request_params, $request_text, $payment ) {
373
+	public function _ppExpress_request($request_params, $request_text, $payment) {
374 374
 		$request_dtls = array(
375 375
 			'VERSION' => '204.0',
376
-			'USER' => urlencode( $this->_api_username ),
377
-			'PWD' => urlencode( $this->_api_password ),
378
-			'SIGNATURE' => urlencode( $this->_api_signature )
376
+			'USER' => urlencode($this->_api_username),
377
+			'PWD' => urlencode($this->_api_password),
378
+			'SIGNATURE' => urlencode($this->_api_signature)
379 379
 		);
380
-		$dtls = array_merge( $request_dtls, $request_params );
380
+		$dtls = array_merge($request_dtls, $request_params);
381 381
 
382
-		$this->_log_clean_request( $dtls, $payment, $request_text . ' Request' );
382
+		$this->_log_clean_request($dtls, $payment, $request_text.' Request');
383 383
 		// Request Customer Details.
384 384
 		$request_response = wp_remote_post(
385 385
 			$this->_base_gateway_url,
@@ -389,11 +389,11 @@  discard block
 block discarded – undo
389 389
 				'httpversion' => '1.1',
390 390
 				'cookies' => array(),
391 391
 				'headers' => array(),
392
-				'body' => http_build_query( $dtls )
392
+				'body' => http_build_query($dtls)
393 393
 			)
394 394
 		);
395 395
 		// Log the response.
396
-		$this->log( array( $request_text . ' Response' => $request_response), $payment );
396
+		$this->log(array($request_text.' Response' => $request_response), $payment);
397 397
 
398 398
 		return $request_response;
399 399
 	}
@@ -405,13 +405,13 @@  discard block
 block discarded – undo
405 405
 	 *	@param mixed        $request_response
406 406
 	 *	@return array
407 407
 	 */
408
-	public function _ppExpress_check_response( $request_response ) {
409
-		if (empty($request_response['body']) || is_wp_error( $request_response ) ) {
408
+	public function _ppExpress_check_response($request_response) {
409
+		if (empty($request_response['body']) || is_wp_error($request_response)) {
410 410
             // If we got here then there was an error in this request.
411 411
             return array('status' => false, 'args' => $request_response);
412 412
         }
413 413
         $response_args = array();
414
-        parse_str( urldecode($request_response['body']), $response_args );
414
+        parse_str(urldecode($request_response['body']), $response_args);
415 415
         if ( ! isset($response_args['ACK'])) {
416 416
             return array('status' => false, 'args' => $request_response);
417 417
         }
@@ -441,10 +441,10 @@  discard block
 block discarded – undo
441 441
 	 * @param string  		$info
442 442
 	 * @return void
443 443
 	 */
444
-	private function _log_clean_request($request, $payment, $info ) {
444
+	private function _log_clean_request($request, $payment, $info) {
445 445
 		$cleaned_request_data = $request;
446 446
 		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
447
-		$this->log( array($info => $cleaned_request_data), $payment );
447
+		$this->log(array($info => $cleaned_request_data), $payment);
448 448
 	}
449 449
 
450 450
 
@@ -454,10 +454,10 @@  discard block
 block discarded – undo
454 454
 	 *  @param array	$data_array
455 455
 	 *  @return array
456 456
 	 */
457
-	private function _get_errors( $data_array ) {
457
+	private function _get_errors($data_array) {
458 458
 		$errors = array();
459 459
 		$n = 0;
460
-		while ( isset($data_array["L_ERRORCODE{$n}"]) ) {
460
+		while (isset($data_array["L_ERRORCODE{$n}"])) {
461 461
 			$l_error_code = isset($data_array["L_ERRORCODE{$n}"])
462 462
                 ? $data_array["L_ERRORCODE{$n}"]
463 463
                 : '';
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
                 ? $data_array["L_LONGMESSAGE{$n}"]
472 472
                 : '';
473 473
 
474
-			if ( $n === 0 ) {
474
+			if ($n === 0) {
475 475
 				$errors = array(
476 476
 					'L_ERRORCODE' => $l_error_code,
477 477
 					'L_SHORTMESSAGE' => $l_short_message,
@@ -479,10 +479,10 @@  discard block
 block discarded – undo
479 479
 					'L_SEVERITYCODE' => $l_severity_code
480 480
 				);
481 481
 			} else {
482
-				$errors['L_ERRORCODE'] .= ', ' . $l_error_code;
483
-				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
484
-				$errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
485
-				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
482
+				$errors['L_ERRORCODE'] .= ', '.$l_error_code;
483
+				$errors['L_SHORTMESSAGE'] .= ', '.$l_short_message;
484
+				$errors['L_LONGMESSAGE'] .= ', '.$l_long_message;
485
+				$errors['L_SEVERITYCODE'] .= ', '.$l_severity_code;
486 486
 			}
487 487
 
488 488
 			$n++;
Please login to merge, or discard this patch.
core/interfaces/EEI_Interfaces.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 interface EEI_Attendee {
191 191
 	public function fname();
192 192
 	public function lname();
193
-    public function full_name();
193
+	public function full_name();
194 194
 	public function email();
195 195
 	public function phone();
196 196
 	public function address();
@@ -311,23 +311,23 @@  discard block
 block discarded – undo
311 311
 	 * @param float $amount
312 312
 	 * @param string $name
313 313
 	 * @param string $description
314
-         * @param string $code
315
-         * @param boolean $add_to_existing_line_item if true and a duplicate line item with
316
-         *  the same code is found, $amount will be added onto it; otherwise will simply
317
-         *  set the taxes to match $amount
314
+	 * @param string $code
315
+	 * @param boolean $add_to_existing_line_item if true and a duplicate line item with
316
+	 *  the same code is found, $amount will be added onto it; otherwise will simply
317
+	 *  set the taxes to match $amount
318 318
 	 * @return EE_Line_Item the new tax created
319 319
 	 */
320 320
 	public function set_total_tax_to( EE_Line_Item $total_line_item, $amount, $name  = NULL, $description = NULL, $code = NULL, $add_to_existing_line_item = false );
321 321
 
322
-         /**
323
-         * Makes all the line items which are children of $line_item taxable (or not).
324
-         * Does NOT save the line items
325
-         * @param EE_Line_Item $line_item
326
-         * @param boolean $taxable
327
-         * @param string $code_substring_for_whitelist if this string is part of the line item's code
328
-         *  it will be whitelisted (ie, except from becoming taxable)
329
-         */
330
-        public static function set_line_items_taxable( EE_Line_Item $line_item, $taxable = true, $code_substring_for_whitelist = null );
322
+		 /**
323
+		  * Makes all the line items which are children of $line_item taxable (or not).
324
+		  * Does NOT save the line items
325
+		  * @param EE_Line_Item $line_item
326
+		  * @param boolean $taxable
327
+		  * @param string $code_substring_for_whitelist if this string is part of the line item's code
328
+		  *  it will be whitelisted (ie, except from becoming taxable)
329
+		  */
330
+		public static function set_line_items_taxable( EE_Line_Item $line_item, $taxable = true, $code_substring_for_whitelist = null );
331 331
 
332 332
 	/**
333 333
 	 * Adds a simple item ( unrelated to any other model object) to the total line item,
@@ -357,15 +357,15 @@  discard block
 block discarded – undo
357 357
  */
358 358
 interface EEHI_Money{
359 359
 		/**
360
-	 * For comparing floats. Default operator is '=', but see the $operator below for all options.
361
-	 * This should be used to compare floats instead of normal '==' because floats
362
-	 * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
363
-	 * but actually differ by 0.00000001.
364
-	 * @param float $float1
365
-	 * @param float $float2
366
-	 * @param string $operator  The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
367
-	 * @return boolean whether the equation is true or false
368
-	 */
360
+		 * For comparing floats. Default operator is '=', but see the $operator below for all options.
361
+		 * This should be used to compare floats instead of normal '==' because floats
362
+		 * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
363
+		 * but actually differ by 0.00000001.
364
+		 * @param float $float1
365
+		 * @param float $float2
366
+		 * @param string $operator  The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
367
+		 * @return boolean whether the equation is true or false
368
+		 */
369 369
 	public function compare_floats( $float1, $float2, $operator='=' );
370 370
 }
371 371
 
Please login to merge, or discard this patch.
core/services/database/TableManager.php 2 patches
Indentation   +207 added lines, -209 removed lines patch added patch discarded remove patch
@@ -17,216 +17,214 @@
 block discarded – undo
17 17
 class TableManager extends \EE_Base
18 18
 {
19 19
 
20
-    /**
21
-     * @var TableAnalysis $table_analysis
22
-     */
23
-    private $table_analysis;
24
-
25
-
26
-
27
-    /**
28
-     * TableManager constructor.
29
-     *
30
-     * @param TableAnalysis $TableAnalysis
31
-     */
32
-    public function __construct(TableAnalysis $TableAnalysis)
33
-    {
34
-        $this->table_analysis = $TableAnalysis;
35
-    }
36
-
37
-
38
-
39
-    /**
40
-     * Gets the injected table analyzer, or throws an exception
41
-     *
42
-     * @return TableAnalysis
43
-     * @throws \EE_Error
44
-     */
45
-    protected function getTableAnalysis()
46
-    {
47
-        if ($this->table_analysis instanceof TableAnalysis) {
48
-            return $this->table_analysis;
49
-        } else {
50
-            throw new \EE_Error(
51
-                sprintf(
52
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
53
-                    get_class($this)
54
-                )
55
-            );
56
-        }
57
-    }
58
-
59
-
60
-
61
-    /**
62
-     * @param string $table_name which can optionally start with $wpdb->prefix or not
63
-     * @param string $column_name
64
-     * @param string $column_info
65
-     * @return bool|false|int
66
-     */
67
-    public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
68
-    {
69
-        if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
70
-            return false;
71
-        }
72
-        global $wpdb;
73
-        $full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
74
-        $columns = $this->getTableColumns($table_name);
75
-        if ( ! in_array($column_name, $columns)) {
76
-            $alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
77
-            return $wpdb->query($alter_query);
78
-        }
79
-        return true;
80
-    }
81
-
82
-
83
-
84
-    /**
85
-     * Gets the name of all columns on the  table. $table_name can
86
-     * optionally start with $wpdb->prefix or not
87
-     *
88
-     * @global \wpdb $wpdb
89
-     * @param string $table_name
90
-     * @return array
91
-     */
92
-    public function getTableColumns($table_name)
93
-    {
94
-        global $wpdb;
95
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
96
-        $field_array = array();
97
-        if ( ! empty($table_name)) {
98
-            $columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
99
-            if ($columns !== false) {
100
-                foreach ($columns as $column) {
101
-                    $field_array[] = $column->Field;
102
-                }
103
-            }
104
-        }
105
-        return $field_array;
106
-    }
107
-
108
-
109
-
110
-    /**
111
-     * Drops the specified table from the database. $table_name can
112
-     * optionally start with $wpdb->prefix or not
113
-     *
114
-     * @global \wpdb $wpdb
115
-     * @param string $table_name
116
-     * @return int
117
-     */
118
-    public function dropTable($table_name)
119
-    {
120
-        global $wpdb;
121
-        if ($this->getTableAnalysis()->tableExists($table_name)) {
122
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
123
-            return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
124
-        }
125
-        return 0;
126
-    }
127
-
128
-
129
-
130
-    /**
131
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
132
-     * each table name provided has a wpdb prefix attached, and that it exists.
133
-     * Returns the list actually deleted
134
-     *
135
-     * @global WPDB $wpdb
136
-     * @param array $table_names
137
-     * @return array of table names which we deleted
138
-     */
139
-    public function dropTables($table_names)
140
-    {
141
-        $tables_to_delete = array();
142
-        foreach ($table_names as $table_name) {
143
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
144
-            if ($this->getTableAnalysis()->tableExists($table_name)) {
145
-                $tables_to_delete[] = $table_name;
146
-            }
147
-        }
148
-        if( ! empty( $tables_to_delete ) ) {
149
-            global $wpdb;
150
-            $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
151
-        }
152
-        return $tables_to_delete;
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * Drops the specified index from the specified table. $table_name can
159
-     * optionally start with $wpdb->prefix or not
160
-
161
-     *
20
+	/**
21
+	 * @var TableAnalysis $table_analysis
22
+	 */
23
+	private $table_analysis;
24
+
25
+
26
+
27
+	/**
28
+	 * TableManager constructor.
29
+	 *
30
+	 * @param TableAnalysis $TableAnalysis
31
+	 */
32
+	public function __construct(TableAnalysis $TableAnalysis)
33
+	{
34
+		$this->table_analysis = $TableAnalysis;
35
+	}
36
+
37
+
38
+
39
+	/**
40
+	 * Gets the injected table analyzer, or throws an exception
41
+	 *
42
+	 * @return TableAnalysis
43
+	 * @throws \EE_Error
44
+	 */
45
+	protected function getTableAnalysis()
46
+	{
47
+		if ($this->table_analysis instanceof TableAnalysis) {
48
+			return $this->table_analysis;
49
+		} else {
50
+			throw new \EE_Error(
51
+				sprintf(
52
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
53
+					get_class($this)
54
+				)
55
+			);
56
+		}
57
+	}
58
+
59
+
60
+
61
+	/**
62
+	 * @param string $table_name which can optionally start with $wpdb->prefix or not
63
+	 * @param string $column_name
64
+	 * @param string $column_info
65
+	 * @return bool|false|int
66
+	 */
67
+	public function addColumn($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
68
+	{
69
+		if (apply_filters('FHEE__EEH_Activation__add_column_if_it_doesnt_exist__short_circuit', false)) {
70
+			return false;
71
+		}
72
+		global $wpdb;
73
+		$full_table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
74
+		$columns = $this->getTableColumns($table_name);
75
+		if ( ! in_array($column_name, $columns)) {
76
+			$alter_query = "ALTER TABLE {$full_table_name} ADD {$column_name} {$column_info}";
77
+			return $wpdb->query($alter_query);
78
+		}
79
+		return true;
80
+	}
81
+
82
+
83
+
84
+	/**
85
+	 * Gets the name of all columns on the  table. $table_name can
86
+	 * optionally start with $wpdb->prefix or not
87
+	 *
88
+	 * @global \wpdb $wpdb
89
+	 * @param string $table_name
90
+	 * @return array
91
+	 */
92
+	public function getTableColumns($table_name)
93
+	{
94
+		global $wpdb;
95
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
96
+		$field_array = array();
97
+		if ( ! empty($table_name)) {
98
+			$columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} ");
99
+			if ($columns !== false) {
100
+				foreach ($columns as $column) {
101
+					$field_array[] = $column->Field;
102
+				}
103
+			}
104
+		}
105
+		return $field_array;
106
+	}
107
+
108
+
109
+
110
+	/**
111
+	 * Drops the specified table from the database. $table_name can
112
+	 * optionally start with $wpdb->prefix or not
113
+	 *
114
+	 * @global \wpdb $wpdb
115
+	 * @param string $table_name
116
+	 * @return int
117
+	 */
118
+	public function dropTable($table_name)
119
+	{
120
+		global $wpdb;
121
+		if ($this->getTableAnalysis()->tableExists($table_name)) {
122
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
123
+			return $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
124
+		}
125
+		return 0;
126
+	}
127
+
128
+
129
+
130
+	/**
131
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
132
+	 * each table name provided has a wpdb prefix attached, and that it exists.
133
+	 * Returns the list actually deleted
134
+	 *
135
+	 * @global WPDB $wpdb
136
+	 * @param array $table_names
137
+	 * @return array of table names which we deleted
138
+	 */
139
+	public function dropTables($table_names)
140
+	{
141
+		$tables_to_delete = array();
142
+		foreach ($table_names as $table_name) {
143
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
144
+			if ($this->getTableAnalysis()->tableExists($table_name)) {
145
+				$tables_to_delete[] = $table_name;
146
+			}
147
+		}
148
+		if( ! empty( $tables_to_delete ) ) {
149
+			global $wpdb;
150
+			$wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
151
+		}
152
+		return $tables_to_delete;
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * Drops the specified index from the specified table. $table_name can
159
+	 * optionally start with $wpdb->prefix or not
160
+	 *
162 161
 *@global \wpdb       $wpdb
163
-     * @param string $table_name
164
-     * @param string $index_name
165
-     * @return int
166
-     */
167
-    public function dropIndex($table_name, $index_name)
168
-    {
169
-        if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
170
-            return false;
171
-        }
172
-        global $wpdb;
173
-        $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
174
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
175
-        if (
176
-            $this->getTableAnalysis()->tableExists($table_name)
177
-            && $wpdb->get_var($index_exists_query)
178
-               === $table_name //using get_var with the $index_exists_query returns the table's name
179
-        ) {
180
-            return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
181
-        }
182
-        return 0;
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * Just creates the requested table. $table_name can
189
-     * optionally start with $wpdb->prefix or not
190
-
191
-     *
162
+	 * @param string $table_name
163
+	 * @param string $index_name
164
+	 * @return int
165
+	 */
166
+	public function dropIndex($table_name, $index_name)
167
+	{
168
+		if (apply_filters('FHEE__EEH_Activation__drop_index__short_circuit', false)) {
169
+			return false;
170
+		}
171
+		global $wpdb;
172
+		$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
173
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
174
+		if (
175
+			$this->getTableAnalysis()->tableExists($table_name)
176
+			&& $wpdb->get_var($index_exists_query)
177
+			   === $table_name //using get_var with the $index_exists_query returns the table's name
178
+		) {
179
+			return $wpdb->query("ALTER TABLE {$table_name} DROP INDEX {$index_name}");
180
+		}
181
+		return 0;
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * Just creates the requested table. $table_name can
188
+	 * optionally start with $wpdb->prefix or not
189
+	 *
192 190
 *@param string       $table_name
193
-     * @param string $create_sql defining the table's columns and indexes
194
-     * @param string $engine     (no need to specify "ENGINE=", that's implied)
195
-     * @return void
196
-     * @throws \EE_Error
197
-     */
198
-    public function createTable($table_name, $create_sql, $engine = 'MyISAM')
199
-    {
200
-        // does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
201
-        if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
202
-            $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
203
-            /** @var \wpdb $wpdb */
204
-            global $wpdb;
205
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
206
-
207
-            //get $wpdb to echo errors, but buffer them. This way at least WE know an error
208
-            //happened. And then we can choose to tell the end user
209
-            $old_show_errors_policy = $wpdb->show_errors(true);
210
-            $old_error_suppression_policy = $wpdb->suppress_errors(false);
211
-            ob_start();
212
-            dbDelta($SQL);
213
-            $output = ob_get_contents();
214
-            ob_end_clean();
215
-            $wpdb->show_errors($old_show_errors_policy);
216
-            $wpdb->suppress_errors($old_error_suppression_policy);
217
-            if ( ! empty($output)) {
218
-                throw new \EE_Error($output);
219
-            }
220
-        } else {
221
-            throw new \EE_Error(
222
-                sprintf(
223
-                    __('The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
224
-                        'event_espresso'),
225
-                    '<br />',
226
-                    $create_sql
227
-                )
228
-            );
229
-        }
230
-    }
191
+	 * @param string $create_sql defining the table's columns and indexes
192
+	 * @param string $engine     (no need to specify "ENGINE=", that's implied)
193
+	 * @return void
194
+	 * @throws \EE_Error
195
+	 */
196
+	public function createTable($table_name, $create_sql, $engine = 'MyISAM')
197
+	{
198
+		// does $sql contain valid column information? ( LPT: https://regex101.com/ is great for working out regex patterns )
199
+		if (preg_match('((((.*?))(,\s))+)', $create_sql, $valid_column_data)) {
200
+			$table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
201
+			/** @var \wpdb $wpdb */
202
+			global $wpdb;
203
+			$SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
204
+
205
+			//get $wpdb to echo errors, but buffer them. This way at least WE know an error
206
+			//happened. And then we can choose to tell the end user
207
+			$old_show_errors_policy = $wpdb->show_errors(true);
208
+			$old_error_suppression_policy = $wpdb->suppress_errors(false);
209
+			ob_start();
210
+			dbDelta($SQL);
211
+			$output = ob_get_contents();
212
+			ob_end_clean();
213
+			$wpdb->show_errors($old_show_errors_policy);
214
+			$wpdb->suppress_errors($old_error_suppression_policy);
215
+			if ( ! empty($output)) {
216
+				throw new \EE_Error($output);
217
+			}
218
+		} else {
219
+			throw new \EE_Error(
220
+				sprintf(
221
+					__('The following table creation SQL does not contain valid information about the table columns: %1$s %2$s',
222
+						'event_espresso'),
223
+					'<br />',
224
+					$create_sql
225
+				)
226
+			);
227
+		}
228
+	}
231 229
 
232 230
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
                 $tables_to_delete[] = $table_name;
146 146
             }
147 147
         }
148
-        if( ! empty( $tables_to_delete ) ) {
148
+        if ( ! empty($tables_to_delete)) {
149 149
             global $wpdb;
150
-            $wpdb->query('DROP TABLE ' . implode(', ', $tables_to_delete));
150
+            $wpdb->query('DROP TABLE '.implode(', ', $tables_to_delete));
151 151
         }
152 152
         return $tables_to_delete;
153 153
     }
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
             $table_name = $this->getTableAnalysis()->ensureTableNameHasPrefix($table_name);
203 203
             /** @var \wpdb $wpdb */
204 204
             global $wpdb;
205
-            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} " . $wpdb->get_charset_collate();
205
+            $SQL = "CREATE TABLE {$table_name} ( {$create_sql} ) ENGINE={$engine} ".$wpdb->get_charset_collate();
206 206
 
207 207
             //get $wpdb to echo errors, but buffer them. This way at least WE know an error
208 208
             //happened. And then we can choose to tell the end user
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 	 * increments reserved by amount passed by $qty
254 254
 	 *
255 255
 	 * @param int $qty
256
-	 * @return boolean
256
+	 * @return boolean|null
257 257
 	 */
258 258
 	public function increase_reserved( $qty = 1 ) {
259 259
 		$reserved = $this->reserved() + absint( $qty );
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 * decrements (subtracts) reserved by amount passed by $qty
267 267
 	 *
268 268
 	 * @param int $qty
269
-	 * @return boolean
269
+	 * @return boolean|null
270 270
 	 */
271 271
 	public function decrease_reserved( $qty = 1 ) {
272 272
 		$reserved = $this->reserved() - absint( $qty );
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 	 * @param string $dt_frmt     - string representation of date format defaults to WP settings
412 412
 	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
413 413
 	 *                            the end date ie: Jan 01 "to" Dec 31
414
-	 * @return mixed        string on success, FALSE on fail
414
+	 * @return string        string on success, FALSE on fail
415 415
 	 * @throws \EE_Error
416 416
 	 */
417 417
 	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
484 484
 	 * @param string $conjunction conjunction junction what's your function ?
485 485
 	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
486
-	 * @return mixed              string on success, FALSE on fail
486
+	 * @return string              string on success, FALSE on fail
487 487
 	 * @throws \EE_Error
488 488
 	 */
489 489
 	public function time_range( $tm_format = '', $conjunction = ' - ' ) {
Please login to merge, or discard this patch.
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 
359 359
 
360 360
 
361
-    /**
362
-     * get event start date.  Provide either the date format, or NULL to re-use the
363
-     * last-used format, or '' to use the default date format
364
-     *
365
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
-     * @return        mixed        string on success, FALSE on fail
367
-     */
361
+	/**
362
+	 * get event start date.  Provide either the date format, or NULL to re-use the
363
+	 * last-used format, or '' to use the default date format
364
+	 *
365
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
+	 * @return        mixed        string on success, FALSE on fail
367
+	 */
368 368
 	public function start_date( $dt_frmt = '' ) {
369 369
 		return $this->_show_datetime( 'D', 'start', $dt_frmt );
370 370
 	}
@@ -381,13 +381,13 @@  discard block
 block discarded – undo
381 381
 
382 382
 
383 383
 
384
-    /**
385
-     * get end date. Provide either the date format, or NULL to re-use the
386
-     * last-used format, or '' to use the default date format
387
-     *
388
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
-     * @return        mixed        string on success, FALSE on fail
390
-     */
384
+	/**
385
+	 * get end date. Provide either the date format, or NULL to re-use the
386
+	 * last-used format, or '' to use the default date format
387
+	 *
388
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
+	 * @return        mixed        string on success, FALSE on fail
390
+	 */
391 391
 	public function end_date( $dt_frmt = '' ) {
392 392
 		return $this->_show_datetime( 'D', 'end', $dt_frmt );
393 393
 	}
@@ -509,23 +509,23 @@  discard block
 block discarded – undo
509 509
 	/**
510 510
 	 * This returns a range representation of the date and times.
511 511
 	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
512
-     * Also, the return value is localized.
513
-     *
514
-     * @param string $dt_format
512
+	 * Also, the return value is localized.
513
+	 *
514
+	 * @param string $dt_format
515 515
 	 * @param string $tm_format
516 516
 	 * @param string $conjunction used between two different dates or times.
517
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
-     * @param string $separator   used between the date and time formats.
519
-     *                            ex: Dec 1, 2016{$separator}2pm
517
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
+	 * @param string $separator   used between the date and time formats.
519
+	 *                            ex: Dec 1, 2016{$separator}2pm
520 520
 	 * @return string
521 521
 	 * @throws \EE_Error
522 522
 	 */
523 523
 	public function date_and_time_range(
524
-	    $dt_format = '',
525
-        $tm_format = '',
526
-        $conjunction = ' - ' ,
527
-        $separator = ' '
528
-    ) {
524
+		$dt_format = '',
525
+		$tm_format = '',
526
+		$conjunction = ' - ' ,
527
+		$separator = ' '
528
+	) {
529 529
 		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530 530
 		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531 531
 		$full_format = $dt_format . $separator . $tm_format;
@@ -539,14 +539,14 @@  discard block
 block discarded – undo
539 539
 			//start and end date are the same but times are different
540 540
 			case ( $this->start_date() === $this->end_date() ) :
541 541
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
542
-				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
542
+						  . $conjunction
543
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547 547
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
548
-				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
548
+						  . $conjunction
549
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -630,13 +630,13 @@  discard block
 block discarded – undo
630 630
 
631 631
 
632 632
 	/**
633
-     *        get end date and time
634
-     *
635
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
-     * @return    mixed                string on success, FALSE on fail
638
-     */
639
-    public function end_date_and_time($dt_frmt = '', $tm_format = '') {
633
+	 *        get end date and time
634
+	 *
635
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
+	 * @return    mixed                string on success, FALSE on fail
638
+	 */
639
+	public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640 640
 		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
641 641
 	}
642 642
 
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -74,9 +74,9 @@  discard block
 block discarded – undo
74 74
 	 *                             		    date_format and the second value is the time format
75 75
 	 * @return EE_Datetime
76 76
 	 */
77
-	public static function new_instance( $props_n_values = array(), $timezone = null, $date_formats = array() ) {
78
-		$has_object = parent::_check_for_object( $props_n_values, __CLASS__, $timezone, $date_formats );
79
-		return $has_object ? $has_object : new self( $props_n_values, false, $timezone, $date_formats );
77
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array()) {
78
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
79
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
80 80
 	}
81 81
 
82 82
 
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 	 *                          		the website will be used.
88 88
 	 * @return EE_Datetime
89 89
 	 */
90
-	public static function new_instance_from_db( $props_n_values = array(), $timezone = null ) {
91
-		return new self( $props_n_values, TRUE, $timezone );
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null) {
91
+		return new self($props_n_values, TRUE, $timezone);
92 92
 	}
93 93
 
94 94
 
@@ -96,8 +96,8 @@  discard block
 block discarded – undo
96 96
 	/**
97 97
 	 * @param $name
98 98
 	 */
99
-	public function set_name( $name ) {
100
-		$this->set( 'DTT_name', $name );
99
+	public function set_name($name) {
100
+		$this->set('DTT_name', $name);
101 101
 	}
102 102
 
103 103
 
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 	/**
106 106
 	 * @param $description
107 107
 	 */
108
-	public function set_description( $description ) {
109
-		$this->set( 'DTT_description', $description );
108
+	public function set_description($description) {
109
+		$this->set('DTT_description', $description);
110 110
 	}
111 111
 
112 112
 
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 	 *
119 119
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
120 120
 	 */
121
-	public function set_start_date( $date ) {
122
-		$this->_set_date_for( $date, 'DTT_EVT_start' );
121
+	public function set_start_date($date) {
122
+		$this->_set_date_for($date, 'DTT_EVT_start');
123 123
 	}
124 124
 
125 125
 
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
 	 *
132 132
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
133 133
 	 */
134
-	public function set_start_time( $time ) {
135
-		$this->_set_time_for( $time, 'DTT_EVT_start' );
134
+	public function set_start_time($time) {
135
+		$this->_set_time_for($time, 'DTT_EVT_start');
136 136
 	}
137 137
 
138 138
 
@@ -144,8 +144,8 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
146 146
 	 */
147
-	public function set_end_date( $date ) {
148
-		$this->_set_date_for( $date, 'DTT_EVT_end' );
147
+	public function set_end_date($date) {
148
+		$this->_set_date_for($date, 'DTT_EVT_end');
149 149
 	}
150 150
 
151 151
 
@@ -157,8 +157,8 @@  discard block
 block discarded – undo
157 157
 	 *
158 158
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
159 159
 	 */
160
-	public function set_end_time( $time ) {
161
-		$this->_set_time_for( $time, 'DTT_EVT_end' );
160
+	public function set_end_time($time) {
161
+		$this->_set_time_for($time, 'DTT_EVT_end');
162 162
 	}
163 163
 
164 164
 
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 	 *
171 171
 	 * @param        int $reg_limit
172 172
 	 */
173
-	public function set_reg_limit( $reg_limit ) {
174
-		$this->set( 'DTT_reg_limit', $reg_limit );
173
+	public function set_reg_limit($reg_limit) {
174
+		$this->set('DTT_reg_limit', $reg_limit);
175 175
 	}
176 176
 
177 177
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	 * @return        mixed        int on success, FALSE on fail
184 184
 	 */
185 185
 	public function sold() {
186
-		return $this->get_raw( 'DTT_sold' );
186
+		return $this->get_raw('DTT_sold');
187 187
 	}
188 188
 
189 189
 
@@ -193,10 +193,10 @@  discard block
 block discarded – undo
193 193
 	 *
194 194
 	 * @param        int $sold
195 195
 	 */
196
-	public function set_sold( $sold ) {
196
+	public function set_sold($sold) {
197 197
 		// sold can not go below zero
198
-		$sold = max( 0, $sold );
199
-		$this->set( 'DTT_sold', $sold );
198
+		$sold = max(0, $sold);
199
+		$this->set('DTT_sold', $sold);
200 200
 	}
201 201
 
202 202
 
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
 	 * increments sold by amount passed by $qty
206 206
 	 * @param int $qty
207 207
 	 */
208
-	public function increase_sold( $qty = 1 ) {
208
+	public function increase_sold($qty = 1) {
209 209
 		$sold = $this->sold() + $qty;
210 210
 		// remove ticket reservation
211
-		$this->decrease_reserved( $qty );
212
-		$this->set_sold( $sold );
211
+		$this->decrease_reserved($qty);
212
+		$this->set_sold($sold);
213 213
 	}
214 214
 
215 215
 
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 	 * decrements (subtracts) sold amount passed by $qty
219 219
 	 * @param int $qty
220 220
 	 */
221
-	public function decrease_sold( $qty = 1 ) {
221
+	public function decrease_sold($qty = 1) {
222 222
 		$sold = $this->sold() - $qty;
223
-		$this->set_sold( $sold );
223
+		$this->set_sold($sold);
224 224
 	}
225 225
 
226 226
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 	 * @return int
232 232
 	 */
233 233
 	public function reserved() {
234
-		return $this->get_raw( 'DTT_reserved' );
234
+		return $this->get_raw('DTT_reserved');
235 235
 	}
236 236
 
237 237
 
@@ -241,10 +241,10 @@  discard block
 block discarded – undo
241 241
 	 *
242 242
 	 * @param int $reserved
243 243
 	 */
244
-	public function set_reserved( $reserved ) {
244
+	public function set_reserved($reserved) {
245 245
 		// reserved can not go below zero
246
-		$reserved = max( 0, (int) $reserved );
247
-		$this->set( 'DTT_reserved', $reserved );
246
+		$reserved = max(0, (int) $reserved);
247
+		$this->set('DTT_reserved', $reserved);
248 248
 	}
249 249
 
250 250
 
@@ -255,9 +255,9 @@  discard block
 block discarded – undo
255 255
 	 * @param int $qty
256 256
 	 * @return boolean
257 257
 	 */
258
-	public function increase_reserved( $qty = 1 ) {
259
-		$reserved = $this->reserved() + absint( $qty );
260
-		return $this->set_reserved( $reserved );
258
+	public function increase_reserved($qty = 1) {
259
+		$reserved = $this->reserved() + absint($qty);
260
+		return $this->set_reserved($reserved);
261 261
 	}
262 262
 
263 263
 
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
 	 * @param int $qty
269 269
 	 * @return boolean
270 270
 	 */
271
-	public function decrease_reserved( $qty = 1 ) {
272
-		$reserved = $this->reserved() - absint( $qty );
273
-		return $this->set_reserved( $reserved );
271
+	public function decrease_reserved($qty = 1) {
272
+		$reserved = $this->reserved() - absint($qty);
273
+		return $this->set_reserved($reserved);
274 274
 	}
275 275
 
276 276
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 	 * @return string
292 292
 	 */
293 293
 	public function name() {
294
-		return $this->get( 'DTT_name' );
294
+		return $this->get('DTT_name');
295 295
 	}
296 296
 
297 297
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @return string
302 302
 	 */
303 303
 	public function description() {
304
-		return $this->get( 'DTT_description' );
304
+		return $this->get('DTT_description');
305 305
 	}
306 306
 
307 307
 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	 * @return boolean          TRUE if is primary, FALSE if not.
312 312
 	 */
313 313
 	public function is_primary() {
314
-		return $this->get( 'DTT_is_primary' );
314
+		return $this->get('DTT_is_primary');
315 315
 	}
316 316
 
317 317
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 	 * @return int         The order of the datetime for this event.
322 322
 	 */
323 323
 	public function order() {
324
-		return $this->get( 'DTT_order' );
324
+		return $this->get('DTT_order');
325 325
 	}
326 326
 
327 327
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 	 * @return int
332 332
 	 */
333 333
 	public function parent() {
334
-		return $this->get( 'DTT_parent' );
334
+		return $this->get('DTT_parent');
335 335
 	}
336 336
 
337 337
 
@@ -347,10 +347,10 @@  discard block
 block discarded – undo
347 347
 	 * @param    bool   $echo         - whether we echo or return (note echoing uses "pretty" formats, otherwise we use the standard formats)
348 348
 	 * @return    string|bool  string on success, FALSE on fail
349 349
 	 */
350
-	private function _show_datetime( $date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE ) {
350
+	private function _show_datetime($date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE) {
351 351
 		$field_name = "DTT_EVT_{$start_or_end}";
352
-		$dtt = $this->_get_datetime( $field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo );
353
-		if ( ! $echo ) {
352
+		$dtt = $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo);
353
+		if ( ! $echo) {
354 354
 			return $dtt;
355 355
 		}
356 356
 		return '';
@@ -365,8 +365,8 @@  discard block
 block discarded – undo
365 365
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366 366
      * @return        mixed        string on success, FALSE on fail
367 367
      */
368
-	public function start_date( $dt_frmt = '' ) {
369
-		return $this->_show_datetime( 'D', 'start', $dt_frmt );
368
+	public function start_date($dt_frmt = '') {
369
+		return $this->_show_datetime('D', 'start', $dt_frmt);
370 370
 	}
371 371
 
372 372
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * Echoes start_date()
376 376
 	 * @param string $dt_frmt
377 377
 	 */
378
-	public function e_start_date( $dt_frmt = '' ) {
379
-		$this->_show_datetime( 'D', 'start', $dt_frmt, NULL, TRUE );
378
+	public function e_start_date($dt_frmt = '') {
379
+		$this->_show_datetime('D', 'start', $dt_frmt, NULL, TRUE);
380 380
 	}
381 381
 
382 382
 
@@ -388,8 +388,8 @@  discard block
 block discarded – undo
388 388
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389 389
      * @return        mixed        string on success, FALSE on fail
390 390
      */
391
-	public function end_date( $dt_frmt = '' ) {
392
-		return $this->_show_datetime( 'D', 'end', $dt_frmt );
391
+	public function end_date($dt_frmt = '') {
392
+		return $this->_show_datetime('D', 'end', $dt_frmt);
393 393
 	}
394 394
 
395 395
 
@@ -398,8 +398,8 @@  discard block
 block discarded – undo
398 398
 	 * Echoes the end date. See end_date()
399 399
 	 * @param string $dt_frmt
400 400
 	 */
401
-	public function e_end_date( $dt_frmt = '' ) {
402
-		$this->_show_datetime( 'D', 'end', $dt_frmt, NULL, TRUE );
401
+	public function e_end_date($dt_frmt = '') {
402
+		$this->_show_datetime('D', 'end', $dt_frmt, NULL, TRUE);
403 403
 	}
404 404
 
405 405
 
@@ -414,11 +414,11 @@  discard block
 block discarded – undo
414 414
 	 * @return mixed        string on success, FALSE on fail
415 415
 	 * @throws \EE_Error
416 416
 	 */
417
-	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
418
-		$dt_frmt = ! empty( $dt_frmt ) ? $dt_frmt : $this->_dt_frmt;
419
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $dt_frmt ) );
420
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end', $dt_frmt ) );
421
-		return $start !== $end ? $start . $conjunction . $end : $start;
417
+	public function date_range($dt_frmt = '', $conjunction = ' - ') {
418
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
419
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt));
420
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt));
421
+		return $start !== $end ? $start.$conjunction.$end : $start;
422 422
 	}
423 423
 
424 424
 
@@ -428,8 +428,8 @@  discard block
 block discarded – undo
428 428
 	 * @param string $conjunction
429 429
 	 * @throws \EE_Error
430 430
 	 */
431
-	public function e_date_range( $dt_frmt = '', $conjunction = ' - ' ) {
432
-		echo $this->date_range( $dt_frmt, $conjunction );
431
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ') {
432
+		echo $this->date_range($dt_frmt, $conjunction);
433 433
 	}
434 434
 
435 435
 
@@ -440,8 +440,8 @@  discard block
 block discarded – undo
440 440
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
441 441
 	 * @return mixed        string on success, FALSE on fail
442 442
 	 */
443
-	public function start_time( $tm_format = '' ) {
444
-		return $this->_show_datetime( 'T', 'start', NULL, $tm_format );
443
+	public function start_time($tm_format = '') {
444
+		return $this->_show_datetime('T', 'start', NULL, $tm_format);
445 445
 	}
446 446
 
447 447
 
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
 	/**
450 450
 	 * @param string $tm_format
451 451
 	 */
452
-	public function e_start_time( $tm_format = '' ) {
453
-		$this->_show_datetime( 'T', 'start', NULL, $tm_format, TRUE );
452
+	public function e_start_time($tm_format = '') {
453
+		$this->_show_datetime('T', 'start', NULL, $tm_format, TRUE);
454 454
 	}
455 455
 
456 456
 
@@ -461,8 +461,8 @@  discard block
 block discarded – undo
461 461
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
462 462
 	 * @return mixed        string on success, FALSE on fail
463 463
 	 */
464
-	public function end_time( $tm_format = '' ) {
465
-		return $this->_show_datetime( 'T', 'end', NULL, $tm_format );
464
+	public function end_time($tm_format = '') {
465
+		return $this->_show_datetime('T', 'end', NULL, $tm_format);
466 466
 	}
467 467
 
468 468
 
@@ -470,8 +470,8 @@  discard block
 block discarded – undo
470 470
 	/**
471 471
 	 * @param string $tm_format
472 472
 	 */
473
-	public function e_end_time( $tm_format = '' ) {
474
-		$this->_show_datetime( 'T', 'end', NULL, $tm_format, TRUE );
473
+	public function e_end_time($tm_format = '') {
474
+		$this->_show_datetime('T', 'end', NULL, $tm_format, TRUE);
475 475
 	}
476 476
 
477 477
 
@@ -486,11 +486,11 @@  discard block
 block discarded – undo
486 486
 	 * @return mixed              string on success, FALSE on fail
487 487
 	 * @throws \EE_Error
488 488
 	 */
489
-	public function time_range( $tm_format = '', $conjunction = ' - ' ) {
490
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
491
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $tm_format ) );
492
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end',  $tm_format ) );
493
-		return $start !== $end ? $start . $conjunction . $end : $start;
489
+	public function time_range($tm_format = '', $conjunction = ' - ') {
490
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
491
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $tm_format));
492
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $tm_format));
493
+		return $start !== $end ? $start.$conjunction.$end : $start;
494 494
 	}
495 495
 
496 496
 
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param string $conjunction
501 501
 	 * @throws \EE_Error
502 502
 	 */
503
-	public function e_time_range( $tm_format = '', $conjunction = ' - ' ) {
504
-		echo $this->time_range( $tm_format, $conjunction );
503
+	public function e_time_range($tm_format = '', $conjunction = ' - ') {
504
+		echo $this->time_range($tm_format, $conjunction);
505 505
 	}
506 506
 
507 507
 
@@ -523,30 +523,30 @@  discard block
 block discarded – undo
523 523
 	public function date_and_time_range(
524 524
 	    $dt_format = '',
525 525
         $tm_format = '',
526
-        $conjunction = ' - ' ,
526
+        $conjunction = ' - ',
527 527
         $separator = ' '
528 528
     ) {
529
-		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531
-		$full_format = $dt_format . $separator . $tm_format;
529
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
530
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
531
+		$full_format = $dt_format.$separator.$tm_format;
532 532
 
533 533
 		//the range output depends on various conditions
534
-		switch ( true ) {
534
+		switch (true) {
535 535
 			//start date timestamp and end date timestamp are the same.
536
-			case ( $this->get_raw( 'DTT_EVT_start' ) === $this->get_raw( 'DTT_EVT_end' ) ) :
537
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format );
536
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')) :
537
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
538 538
 				break;
539 539
 			//start and end date are the same but times are different
540
-			case ( $this->start_date() === $this->end_date() ) :
541
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
540
+			case ($this->start_date() === $this->end_date()) :
541
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
542 542
 				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
543
+				          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
547
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
548 548
 				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
549
+				          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -564,8 +564,8 @@  discard block
 block discarded – undo
564 564
 	 * @return void
565 565
 	 * @throws \EE_Error
566 566
 	 */
567
-	public function e_date_and_time_range( $dt_format = '', $tm_format = '', $conjunction = ' - ' ) {
568
-		echo $this->date_and_time_range( $dt_format, $tm_format, $conjunction );
567
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ') {
568
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
569 569
 	}
570 570
 
571 571
 
@@ -577,8 +577,8 @@  discard block
 block discarded – undo
577 577
 	 * @param 	string 	$tm_format - string representation of time format defaults to 'g:i a'
578 578
 	 * @return 	mixed 	string on success, FALSE on fail
579 579
 	 */
580
-	public function start_date_and_time( $dt_format = '', $tm_format = '' ) {
581
-		return $this->_show_datetime( '', 'start', $dt_format, $tm_format );
580
+	public function start_date_and_time($dt_format = '', $tm_format = '') {
581
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
582 582
 	}
583 583
 
584 584
 
@@ -587,8 +587,8 @@  discard block
 block discarded – undo
587 587
 	 * @param string $dt_frmt
588 588
 	 * @param string $tm_format
589 589
 	 */
590
-	public function e_start_date_and_time( $dt_frmt = '', $tm_format = '' ) {
591
-		$this->_show_datetime( '', 'start', $dt_frmt, $tm_format, TRUE );
590
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '') {
591
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, TRUE);
592 592
 	}
593 593
 
594 594
 
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
 	 * @param bool   $round_up
603 603
 	 * @return float|int|mixed
604 604
 	 */
605
-	public function length( $units = 'seconds', $round_up = FALSE ) {
606
-		$start = $this->get_raw( 'DTT_EVT_start' );
607
-		$end = $this->get_raw( 'DTT_EVT_end' );
605
+	public function length($units = 'seconds', $round_up = FALSE) {
606
+		$start = $this->get_raw('DTT_EVT_start');
607
+		$end = $this->get_raw('DTT_EVT_end');
608 608
 		$length_in_units = $end - $start;
609
-		switch ( $units ) {
609
+		switch ($units) {
610 610
 			//NOTE: We purposefully don't use "break;" in order to chain the divisions
611 611
 			/** @noinspection PhpMissingBreakStatementInspection */
612 612
 			case 'days':
@@ -619,10 +619,10 @@  discard block
 block discarded – undo
619 619
 				$length_in_units /= 60;
620 620
 			case 'seconds':
621 621
 			default:
622
-				$length_in_units = ceil( $length_in_units );
622
+				$length_in_units = ceil($length_in_units);
623 623
 		}
624
-		if ( $round_up ) {
625
-			$length_in_units = max( $length_in_units, 1 );
624
+		if ($round_up) {
625
+			$length_in_units = max($length_in_units, 1);
626 626
 		}
627 627
 		return $length_in_units;
628 628
 	}
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
      * @return    mixed                string on success, FALSE on fail
638 638
      */
639 639
     public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640
-		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
640
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
641 641
 	}
642 642
 
643 643
 
@@ -646,8 +646,8 @@  discard block
 block discarded – undo
646 646
 	 * @param string $dt_frmt
647 647
 	 * @param string $tm_format
648 648
 	 */
649
-	public function e_end_date_and_time( $dt_frmt = '', $tm_format = '' ) {
650
-		$this->_show_datetime( '', 'end', $dt_frmt, $tm_format, TRUE );
649
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '') {
650
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, TRUE);
651 651
 	}
652 652
 
653 653
 
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 	 * @return        int
659 659
 	 */
660 660
 	public function start() {
661
-		return $this->get_raw( 'DTT_EVT_start' );
661
+		return $this->get_raw('DTT_EVT_start');
662 662
 	}
663 663
 
664 664
 
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 	 * @return        int
670 670
 	 */
671 671
 	public function end() {
672
-		return $this->get_raw( 'DTT_EVT_end' );
672
+		return $this->get_raw('DTT_EVT_end');
673 673
 	}
674 674
 
675 675
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 	 * @return        mixed        int on success, FALSE on fail
681 681
 	 */
682 682
 	public function reg_limit() {
683
-		return $this->get_raw( 'DTT_reg_limit' );
683
+		return $this->get_raw('DTT_reg_limit');
684 684
 	}
685 685
 
686 686
 
@@ -708,15 +708,15 @@  discard block
 block discarded – undo
708 708
 	 * 																	the spaces remaining for this particular datetime, hence the flag.
709 709
 	 * @return 	int
710 710
 	 */
711
-	public function spaces_remaining( $consider_tickets = FALSE ) {
711
+	public function spaces_remaining($consider_tickets = FALSE) {
712 712
 		// tickets remaining available for purchase
713 713
 		//no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
714 714
 		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
715
-		if ( ! $consider_tickets ) {
715
+		if ( ! $consider_tickets) {
716 716
 			return $dtt_remaining;
717 717
 		}
718 718
 		$tickets_remaining = $this->tickets_remaining();
719
-		return min( $dtt_remaining, $tickets_remaining );
719
+		return min($dtt_remaining, $tickets_remaining);
720 720
 	}
721 721
 
722 722
 
@@ -727,19 +727,19 @@  discard block
 block discarded – undo
727 727
 	 * @param array $query_params like EEM_Base::get_all's
728 728
 	 * @return int
729 729
 	 */
730
-	public function tickets_remaining( $query_params = array() ) {
730
+	public function tickets_remaining($query_params = array()) {
731 731
 		$sum = 0;
732
-		$tickets = $this->tickets( $query_params );
733
-		if ( ! empty( $tickets ) ) {
734
-			foreach ( $tickets as $ticket ) {
735
-				if ( $ticket instanceof EE_Ticket ) {
732
+		$tickets = $this->tickets($query_params);
733
+		if ( ! empty($tickets)) {
734
+			foreach ($tickets as $ticket) {
735
+				if ($ticket instanceof EE_Ticket) {
736 736
 					// get the actual amount of tickets that can be sold
737
-					$qty = $ticket->qty( 'saleable' );
738
-					if ( $qty === EE_INF ) {
737
+					$qty = $ticket->qty('saleable');
738
+					if ($qty === EE_INF) {
739 739
 						return EE_INF;
740 740
 					}
741 741
 					// no negative ticket quantities plz
742
-					if ( $qty > 0 ) {
742
+					if ($qty > 0) {
743 743
 						$sum += $qty;
744 744
 					}
745 745
 				}
@@ -756,8 +756,8 @@  discard block
 block discarded – undo
756 756
 	 * @param array $query_params like EEM_Base::get_all's
757 757
 	 * @return int
758 758
 	 */
759
-	public function sum_tickets_initially_available( $query_params = array() ) {
760
-		return $this->sum_related( 'Ticket', $query_params, 'TKT_qty' );
759
+	public function sum_tickets_initially_available($query_params = array()) {
760
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
761 761
 	}
762 762
 
763 763
 
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
 	 * @return int
770 770
 	 */
771 771
 	public function total_tickets_available_at_this_datetime() {
772
-		return $this->spaces_remaining( true );
772
+		return $this->spaces_remaining(true);
773 773
 	}
774 774
 
775 775
 
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 	 * @return boolean
781 781
 	 */
782 782
 	public function is_upcoming() {
783
-		return ( $this->get_raw( 'DTT_EVT_start' ) > time() );
783
+		return ($this->get_raw('DTT_EVT_start') > time());
784 784
 	}
785 785
 
786 786
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
 	 * @return boolean
791 791
 	 */
792 792
 	public function is_active() {
793
-		return ( $this->get_raw( 'DTT_EVT_start' ) < time() && $this->get_raw( 'DTT_EVT_end' ) > time() );
793
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
794 794
 	}
795 795
 
796 796
 
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 	 * @return boolean
801 801
 	 */
802 802
 	public function is_expired() {
803
-		return ( $this->get_raw( 'DTT_EVT_end' ) < time() );
803
+		return ($this->get_raw('DTT_EVT_end') < time());
804 804
 	}
805 805
 
806 806
 
@@ -811,16 +811,16 @@  discard block
 block discarded – undo
811 811
 	 */
812 812
 	public function get_active_status() {
813 813
 		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
814
-		if ( $total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1 ) {
814
+		if ($total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1) {
815 815
 			return EE_Datetime::sold_out;
816 816
 		}
817
-		if ( $this->is_expired() ) {
817
+		if ($this->is_expired()) {
818 818
 			return EE_Datetime::expired;
819 819
 		}
820
-		if ( $this->is_upcoming() ) {
820
+		if ($this->is_upcoming()) {
821 821
 			return EE_Datetime::upcoming;
822 822
 		}
823
-		if ( $this->is_active() ) {
823
+		if ($this->is_active()) {
824 824
 			return EE_Datetime::active;
825 825
 		}
826 826
 		return NULL;
@@ -834,24 +834,24 @@  discard block
 block discarded – undo
834 834
 	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
835 835
 	 * @return string
836 836
 	 */
837
-	public function get_dtt_display_name( $use_dtt_name = FALSE ) {
838
-		if ( $use_dtt_name ) {
837
+	public function get_dtt_display_name($use_dtt_name = FALSE) {
838
+		if ($use_dtt_name) {
839 839
 			$dtt_name = $this->name();
840
-			if ( !empty( $dtt_name ) ) {
840
+			if ( ! empty($dtt_name)) {
841 841
 				return $dtt_name;
842 842
 			}
843 843
 		}
844 844
 		//first condition is to see if the months are different
845
-		if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) ) {
846
-			$display_date = $this->start_date( 'M j\, Y g:i a' ) . ' - ' . $this->end_date( 'M j\, Y g:i a' );
845
+		if (date('m', $this->get_raw('DTT_EVT_start')) != date('m', $this->get_raw('DTT_EVT_end'))) {
846
+			$display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
847 847
 			//next condition is if its the same month but different day
848 848
 		}
849 849
 		else {
850
-			if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) == date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) && date( 'd', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'd', $this->get_raw( 'DTT_EVT_end' ) ) ) {
851
-				$display_date = $this->start_date( 'M j\, g:i a' ) . ' - ' . $this->end_date( 'M j\, g:i a Y' );
850
+			if (date('m', $this->get_raw('DTT_EVT_start')) == date('m', $this->get_raw('DTT_EVT_end')) && date('d', $this->get_raw('DTT_EVT_start')) != date('d', $this->get_raw('DTT_EVT_end'))) {
851
+				$display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
852 852
 			}
853 853
 			else {
854
-				$display_date = $this->start_date( 'F j\, Y' ) . ' @ ' . $this->start_date( 'g:i a' ) . ' - ' . $this->end_date( 'g:i a' );
854
+				$display_date = $this->start_date('F j\, Y').' @ '.$this->start_date('g:i a').' - '.$this->end_date('g:i a');
855 855
 			}
856 856
 		}
857 857
 		return $display_date;
@@ -865,8 +865,8 @@  discard block
 block discarded – undo
865 865
 *@param array $query_params see EEM_Base::get_all()
866 866
 	 * @return EE_Ticket[]
867 867
 	 */
868
-	public function tickets( $query_params = array() ) {
869
-		return $this->get_many_related( 'Ticket', $query_params );
868
+	public function tickets($query_params = array()) {
869
+		return $this->get_many_related('Ticket', $query_params);
870 870
 	}
871 871
 
872 872
 
@@ -876,21 +876,21 @@  discard block
 block discarded – undo
876 876
 	 * @param array $query_params like EEM_Base::get_all's
877 877
 	 * @return EE_Ticket[]
878 878
 	 */
879
-	public function ticket_types_available_for_purchase( $query_params = array() ) {
879
+	public function ticket_types_available_for_purchase($query_params = array()) {
880 880
 		// first check if datetime is valid
881
-		if ( ! ( $this->is_upcoming() || $this->is_active() ) || $this->sold_out() ) {
881
+		if ( ! ($this->is_upcoming() || $this->is_active()) || $this->sold_out()) {
882 882
 			return array();
883 883
 		}
884
-		if ( empty( $query_params ) ) {
884
+		if (empty($query_params)) {
885 885
 			$query_params = array(
886 886
 				array(
887
-					'TKT_start_date' => array( '<=', EEM_Ticket::instance()->current_time_for_query( 'TKT_start_date' ) ),
888
-					'TKT_end_date'   => array( '>=', EEM_Ticket::instance()->current_time_for_query( 'TKT_end_date' ) ),
887
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
888
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
889 889
 					'TKT_deleted'    => false
890 890
 				)
891 891
 			);
892 892
 		}
893
-		return $this->tickets( $query_params );
893
+		return $this->tickets($query_params);
894 894
 	}
895 895
 
896 896
 
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 	 * @return EE_Event
901 901
 	 */
902 902
 	public function event() {
903
-		return $this->get_first_related( 'Event' );
903
+		return $this->get_first_related('Event');
904 904
 	}
905 905
 
906 906
 
@@ -912,13 +912,13 @@  discard block
 block discarded – undo
912 912
 	 */
913 913
 	public function update_sold() {
914 914
 		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
915
-			array( array(
915
+			array(array(
916 916
 				'STS_ID' 					=> EEM_Registration::status_id_approved,
917 917
 				'REG_deleted' 				=> 0,
918 918
 				'Ticket.Datetime.DTT_ID' 	=> $this->ID(),
919
-			) )
919
+			))
920 920
 		);
921
-		$this->set( 'DTT_sold', $count_regs_for_this_datetime );
921
+		$this->set('DTT_sold', $count_regs_for_this_datetime);
922 922
 		$this->save();
923 923
 		return $count_regs_for_this_datetime;
924 924
 	}
Please login to merge, or discard this patch.
core/helpers/EEH_Schema.helper.php 2 patches
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
4
-	exit( 'No direct script access allowed' );
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
             $VNU_ID
70 70
         );
71 71
         extract($template_args, EXTR_OVERWRITE);
72
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
72
+        include EE_TEMPLATES.'json_linked_data_for_event.template.php';
73 73
     }
74 74
 
75 75
 
@@ -82,8 +82,8 @@  discard block
 block discarded – undo
82 82
 	 * @param string $location
83 83
 	 * @return string
84 84
 	 */
85
-	public static function location( $location = null ) {
86
-		return ! empty( $location ) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
85
+	public static function location($location = null) {
86
+		return ! empty($location) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
87 87
 		                              . $location
88 88
 		                              . '</div>' : '';
89 89
 	}
@@ -98,8 +98,8 @@  discard block
 block discarded – undo
98 98
 	 * @param string $name
99 99
 	 * @return string
100 100
 	 */
101
-	public static function name( $name = null ) {
102
-		return ! empty( $name ) ? '<span itemprop="name">' . $name . '</span>' : '';
101
+	public static function name($name = null) {
102
+		return ! empty($name) ? '<span itemprop="name">'.$name.'</span>' : '';
103 103
 	}
104 104
 
105 105
 
@@ -112,9 +112,9 @@  discard block
 block discarded – undo
112 112
 	 * @param EEI_Address $obj_with_address
113 113
 	 * @return string
114 114
 	 */
115
-	public static function streetAddress( EEI_Address $obj_with_address = null ) {
115
+	public static function streetAddress(EEI_Address $obj_with_address = null) {
116 116
 		return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
117
-			? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
117
+			? '<span itemprop="streetAddress">'.$obj_with_address->address().'</span>' : '';
118 118
 	}
119 119
 
120 120
 
@@ -127,14 +127,14 @@  discard block
 block discarded – undo
127 127
 	 * @param EEI_Address $obj_with_address
128 128
 	 * @return string
129 129
 	 */
130
-	public static function postOfficeBoxNumber( EEI_Address $obj_with_address = null ) {
130
+	public static function postOfficeBoxNumber(EEI_Address $obj_with_address = null) {
131 131
 		// regex check for some form of PO Box or P.O. Box, etc, etc, etc
132
-		if ( preg_match(
132
+		if (preg_match(
133 133
 			"/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i",
134 134
 			$obj_with_address->address2()
135
-		) ) {
135
+		)) {
136 136
 			return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
137
-				? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
137
+				? '<span itemprop="postOfficeBoxNumber">'.$obj_with_address->address2().'</span>' : '';
138 138
 		} else {
139 139
 			return $obj_with_address->address2();
140 140
 		}
@@ -150,9 +150,9 @@  discard block
 block discarded – undo
150 150
 	 * @param EEI_Address $obj_with_address
151 151
 	 * @return string
152 152
 	 */
153
-	public static function addressLocality( EEI_Address $obj_with_address = null ) {
153
+	public static function addressLocality(EEI_Address $obj_with_address = null) {
154 154
 		return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
155
-			? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
155
+			? '<span itemprop="addressLocality">'.$obj_with_address->city().'</span>' : '';
156 156
 	}
157 157
 
158 158
 
@@ -165,10 +165,10 @@  discard block
 block discarded – undo
165 165
 	 * @param EEI_Address $obj_with_address
166 166
 	 * @return string
167 167
 	 */
168
-	public static function addressRegion( EEI_Address $obj_with_address = null ) {
168
+	public static function addressRegion(EEI_Address $obj_with_address = null) {
169 169
 		$state = $obj_with_address->state_name();
170
-		if ( ! empty( $state ) ) {
171
-			return '<span itemprop="addressRegion">' . $state . '</span>';
170
+		if ( ! empty($state)) {
171
+			return '<span itemprop="addressRegion">'.$state.'</span>';
172 172
 		} else {
173 173
 			return '';
174 174
 		}
@@ -184,10 +184,10 @@  discard block
 block discarded – undo
184 184
 	 * @param EEI_Address $obj_with_address
185 185
 	 * @return string
186 186
 	 */
187
-	public static function addressCountry( EEI_Address $obj_with_address = null ) {
187
+	public static function addressCountry(EEI_Address $obj_with_address = null) {
188 188
 		$country = $obj_with_address->country_name();
189
-		if ( ! empty( $country ) ) {
190
-			return '<span itemprop="addressCountry">' . $country . '</span>';
189
+		if ( ! empty($country)) {
190
+			return '<span itemprop="addressCountry">'.$country.'</span>';
191 191
 		} else {
192 192
 			return '';
193 193
 		}
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 	 * @param EEI_Address $obj_with_address
204 204
 	 * @return string
205 205
 	 */
206
-	public static function postalCode( EEI_Address $obj_with_address = null ) {
206
+	public static function postalCode(EEI_Address $obj_with_address = null) {
207 207
 		return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
208 208
 		                                                                              . $obj_with_address->zip()
209 209
 		                                                                              . '</span>' : '';
@@ -219,8 +219,8 @@  discard block
 block discarded – undo
219 219
 	 * @param string $phone_nmbr
220 220
 	 * @return string
221 221
 	 */
222
-	public static function telephone( $phone_nmbr = null ) {
223
-		return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
222
+	public static function telephone($phone_nmbr = null) {
223
+		return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">'.$phone_nmbr.'</span>'
224 224
 			: '';
225 225
 	}
226 226
 
@@ -236,13 +236,13 @@  discard block
 block discarded – undo
236 236
 	 * @param array  $attributes - array of additional link attributes in  attribute_name => value pairs. ie: array( 'title' => 'click here', 'class' => 'link-class' )
237 237
 	 * @return string (link)
238 238
 	 */
239
-	public static function url( $url = null, $text = null, $attributes = array() ) {
239
+	public static function url($url = null, $text = null, $attributes = array()) {
240 240
 		$atts = '';
241
-		foreach ( $attributes as $attribute => $value ) {
242
-			$atts .= ' ' . $attribute . '="' . $value . '"';
241
+		foreach ($attributes as $attribute => $value) {
242
+			$atts .= ' '.$attribute.'="'.$value.'"';
243 243
 		}
244 244
 		$text = $text !== null && $text !== '' ? $text : $url;
245
-		return $url !== null && $url !== '' ? '<a itemprop="url" href="' . $url . '"' . $atts . '>' . $text . '</a>'
245
+		return $url !== null && $url !== '' ? '<a itemprop="url" href="'.$url.'"'.$atts.'>'.$text.'</a>'
246 246
 			: '';
247 247
 	}
248 248
 
Please login to merge, or discard this patch.
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -17,62 +17,62 @@  discard block
 block discarded – undo
17 17
 class EEH_Schema {
18 18
 
19 19
 
20
-    /**
21
-     * generates JSON-based linked data for an event
22
-     *
23
-     * @param \EE_Event $event
24
-     */
25
-    public static function add_json_linked_data_for_event(\EE_Event $event)
26
-    {
27
-        $template_args = array(
28
-            'event_permalink' => '',
29
-            'event_name' => '',
30
-            'event_description' => '',
31
-            'event_start' => '',
32
-            'event_end' => '',
33
-            'currency' => '',
34
-            'event_tickets' => array(),
35
-            'venue_name' => '',
36
-            'venue_url' => '',
37
-            'venue_locality' => '',
38
-            'venue_region' => '',
39
-            'event_image' => '',
40
-        );
41
-        $template_args['event_permalink'] = $event->get_permalink();
42
-        $template_args['event_name'] = $event->name();
43
-        $template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
44
-        $template_args['event_start'] = $event->primary_datetime()->start_date(DateTime::ATOM);
45
-        $template_args['event_end'] = $event->primary_datetime()->end_date(DateTime::ATOM);
46
-        $template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
47
-        foreach ($event->tickets() as $ticket) {
48
-            $ID = $ticket->ID();
49
-            $template_args['event_tickets'][$ID]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
50
-            $template_args['event_tickets'][$ID]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
51
-            $template_args['event_tickets'][$ID]['price'] = number_format(
52
-                $ticket->price(),
53
-                EE_Registry::instance()->CFG->currency->dec_plc,
54
-                EE_Registry::instance()->CFG->currency->dec_mrk,
55
-                EE_Registry::instance()->CFG->currency->thsnds
56
-            );
57
-        }
58
-        $VNU_ID = espresso_venue_id();
59
-        if ( ! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
60
-            $venue = EEH_Venue_View::get_venue($VNU_ID);
61
-            $template_args['venue_name'] = get_the_title($VNU_ID);
62
-            $template_args['venue_url'] = get_permalink($VNU_ID);
63
-            $template_args['venue_locality'] = $venue->city();
64
-            $template_args['venue_region'] = $venue->state_name();
65
-        }
66
-        $template_args['event_image'] = $event->feature_image_url();
67
-        $template_args = apply_filters(
68
-            'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
69
-            $template_args,
70
-            $event,
71
-            $VNU_ID
72
-        );
73
-        extract($template_args, EXTR_OVERWRITE);
74
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
75
-    }
20
+	/**
21
+	 * generates JSON-based linked data for an event
22
+	 *
23
+	 * @param \EE_Event $event
24
+	 */
25
+	public static function add_json_linked_data_for_event(\EE_Event $event)
26
+	{
27
+		$template_args = array(
28
+			'event_permalink' => '',
29
+			'event_name' => '',
30
+			'event_description' => '',
31
+			'event_start' => '',
32
+			'event_end' => '',
33
+			'currency' => '',
34
+			'event_tickets' => array(),
35
+			'venue_name' => '',
36
+			'venue_url' => '',
37
+			'venue_locality' => '',
38
+			'venue_region' => '',
39
+			'event_image' => '',
40
+		);
41
+		$template_args['event_permalink'] = $event->get_permalink();
42
+		$template_args['event_name'] = $event->name();
43
+		$template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
44
+		$template_args['event_start'] = $event->primary_datetime()->start_date(DateTime::ATOM);
45
+		$template_args['event_end'] = $event->primary_datetime()->end_date(DateTime::ATOM);
46
+		$template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
47
+		foreach ($event->tickets() as $ticket) {
48
+			$ID = $ticket->ID();
49
+			$template_args['event_tickets'][$ID]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
50
+			$template_args['event_tickets'][$ID]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
51
+			$template_args['event_tickets'][$ID]['price'] = number_format(
52
+				$ticket->price(),
53
+				EE_Registry::instance()->CFG->currency->dec_plc,
54
+				EE_Registry::instance()->CFG->currency->dec_mrk,
55
+				EE_Registry::instance()->CFG->currency->thsnds
56
+			);
57
+		}
58
+		$VNU_ID = espresso_venue_id();
59
+		if ( ! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
60
+			$venue = EEH_Venue_View::get_venue($VNU_ID);
61
+			$template_args['venue_name'] = get_the_title($VNU_ID);
62
+			$template_args['venue_url'] = get_permalink($VNU_ID);
63
+			$template_args['venue_locality'] = $venue->city();
64
+			$template_args['venue_region'] = $venue->state_name();
65
+		}
66
+		$template_args['event_image'] = $event->feature_image_url();
67
+		$template_args = apply_filters(
68
+			'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
69
+			$template_args,
70
+			$event,
71
+			$VNU_ID
72
+		);
73
+		extract($template_args, EXTR_OVERWRITE);
74
+		include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
75
+	}
76 76
 
77 77
 
78 78
 	/**
@@ -86,8 +86,8 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	public static function location( $location = null ) {
88 88
 		return ! empty( $location ) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
89
-		                              . $location
90
-		                              . '</div>' : '';
89
+									  . $location
90
+									  . '</div>' : '';
91 91
 	}
92 92
 
93 93
 
@@ -207,8 +207,8 @@  discard block
 block discarded – undo
207 207
 	 */
208 208
 	public static function postalCode( EEI_Address $obj_with_address = null ) {
209 209
 		return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
210
-		                                                                              . $obj_with_address->zip()
211
-		                                                                              . '</span>' : '';
210
+																					  . $obj_with_address->zip()
211
+																					  . '</span>' : '';
212 212
 	}
213 213
 
214 214
 
Please login to merge, or discard this patch.
caffeinated/payment_methods/Paypal_Pro/EEG_Paypal_Pro.gateway.php 3 patches
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -90,19 +90,19 @@  discard block
 block discarded – undo
90 90
 	 */
91 91
 	public function do_direct_payment($payment,$billing_info = null){
92 92
 		$transaction = $payment->transaction();
93
-        if (! $transaction instanceof EEI_Transaction) {
94
-            throw new EE_Error(esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso'));
95
-        }
96
-        $primary_registrant = $transaction->primary_registration();
97
-        if (! $primary_registrant instanceof EEI_Registration) {
98
-            throw new EE_Error(esc_html__('No primary registration on transaction while paying with PayPal Pro.',
99
-                'event_espresso'));
100
-        }
101
-        $attendee = $primary_registrant->attendee();
102
-        if (! $attendee instanceof EEI_Attendee) {
103
-            throw new EE_Error(esc_html__('No attendee on primary registration while paying with PayPal Pro.',
104
-                'event_espresso'));
105
-        }
93
+		if (! $transaction instanceof EEI_Transaction) {
94
+			throw new EE_Error(esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso'));
95
+		}
96
+		$primary_registrant = $transaction->primary_registration();
97
+		if (! $primary_registrant instanceof EEI_Registration) {
98
+			throw new EE_Error(esc_html__('No primary registration on transaction while paying with PayPal Pro.',
99
+				'event_espresso'));
100
+		}
101
+		$attendee = $primary_registrant->attendee();
102
+		if (! $attendee instanceof EEI_Attendee) {
103
+			throw new EE_Error(esc_html__('No attendee on primary registration while paying with PayPal Pro.',
104
+				'event_espresso'));
105
+		}
106 106
 		$order_description  = $this->_format_order_description( $payment );
107 107
 		//charge for the full amount. Show itemized list
108 108
 		if( $this->_can_easily_itemize_transaction_for( $payment ) ){
@@ -232,23 +232,23 @@  discard block
 block discarded – undo
232 232
 			'zip' => $billing_info['zip'],
233 233
 		);
234 234
 
235
-        //check if the registration info contains the needed fields for paypal pro (see https://developer.paypal.com/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/)
236
-        if($attendee->address() && $attendee->city() && $attendee->country_ID()){
237
-            $use_registration_address_info = true;
238
-        } else {
239
-            $use_registration_address_info = false;
240
-        }
241
-        //so if the attendee has enough data to fill out PayPal Pro's shipping info, use it. If not, use the billing info again
242
-        $ShippingAddress = array(
243
-            'shiptoname' => substr($use_registration_address_info ? $attendee->full_name() : $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
244
-            'shiptostreet' => substr($use_registration_address_info ? $attendee->address() : $billing_info['address'], 0, 100),
245
-            'shiptostreet2' => substr($use_registration_address_info ? $attendee->address2() : $billing_info['address2'],0,100),
246
-            'shiptocity' => substr($use_registration_address_info ? $attendee->city() : $billing_info['city'],0,40),
247
-            'state' => substr($use_registration_address_info ? $attendee->state_name() : $billing_info['state'],0,40),
248
-            'shiptocountry' => $use_registration_address_info ? $attendee->country_ID() : $billing_info['country'],
249
-            'shiptozip' => substr($use_registration_address_info ? $attendee->zip() : $billing_info['zip'],0,20),
250
-            'shiptophonenum' => substr($use_registration_address_info ? $attendee->phone() : $billing_info['phone'],0,20),
251
-        );
235
+		//check if the registration info contains the needed fields for paypal pro (see https://developer.paypal.com/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/)
236
+		if($attendee->address() && $attendee->city() && $attendee->country_ID()){
237
+			$use_registration_address_info = true;
238
+		} else {
239
+			$use_registration_address_info = false;
240
+		}
241
+		//so if the attendee has enough data to fill out PayPal Pro's shipping info, use it. If not, use the billing info again
242
+		$ShippingAddress = array(
243
+			'shiptoname' => substr($use_registration_address_info ? $attendee->full_name() : $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
244
+			'shiptostreet' => substr($use_registration_address_info ? $attendee->address() : $billing_info['address'], 0, 100),
245
+			'shiptostreet2' => substr($use_registration_address_info ? $attendee->address2() : $billing_info['address2'],0,100),
246
+			'shiptocity' => substr($use_registration_address_info ? $attendee->city() : $billing_info['city'],0,40),
247
+			'state' => substr($use_registration_address_info ? $attendee->state_name() : $billing_info['state'],0,40),
248
+			'shiptocountry' => $use_registration_address_info ? $attendee->country_ID() : $billing_info['country'],
249
+			'shiptozip' => substr($use_registration_address_info ? $attendee->zip() : $billing_info['zip'],0,20),
250
+			'shiptophonenum' => substr($use_registration_address_info ? $attendee->phone() : $billing_info['phone'],0,20),
251
+		);
252 252
 
253 253
 		$PaymentDetails = array(
254 254
 			// Required.  Total amount of order, including shipping, handling, and tax.
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 				'PayerInfo' => $PayerInfo,
281 281
 				'PayerName' => $PayerName,
282 282
 				'BillingAddress' => $BillingAddress,
283
-                'ShippingAddress' => $ShippingAddress,
283
+				'ShippingAddress' => $ShippingAddress,
284 284
 				'PaymentDetails' => $PaymentDetails,
285 285
 				'OrderItems' => $order_items,
286 286
 		);
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION'))
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('No direct script access allowed');
5 5
 
6 6
 /**
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
  *
26 26
  * ------------------------------------------------------------------------
27 27
  */
28
-class EEG_Paypal_Pro extends EE_Onsite_Gateway{
28
+class EEG_Paypal_Pro extends EE_Onsite_Gateway {
29 29
 	/**
30 30
 	 *
31 31
 	 * @var $_paypal_api_username string
@@ -88,42 +88,42 @@  discard block
 block discarded – undo
88 88
 	 * } @see parent::do_direct_payment for more info
89 89
 	 * @return \EE_Payment|\EEI_Payment
90 90
 	 */
91
-	public function do_direct_payment($payment,$billing_info = null){
91
+	public function do_direct_payment($payment, $billing_info = null) {
92 92
 		$transaction = $payment->transaction();
93
-        if (! $transaction instanceof EEI_Transaction) {
93
+        if ( ! $transaction instanceof EEI_Transaction) {
94 94
             throw new EE_Error(esc_html__('No transaction for payment while paying with PayPal Pro.', 'event_espresso'));
95 95
         }
96 96
         $primary_registrant = $transaction->primary_registration();
97
-        if (! $primary_registrant instanceof EEI_Registration) {
97
+        if ( ! $primary_registrant instanceof EEI_Registration) {
98 98
             throw new EE_Error(esc_html__('No primary registration on transaction while paying with PayPal Pro.',
99 99
                 'event_espresso'));
100 100
         }
101 101
         $attendee = $primary_registrant->attendee();
102
-        if (! $attendee instanceof EEI_Attendee) {
102
+        if ( ! $attendee instanceof EEI_Attendee) {
103 103
             throw new EE_Error(esc_html__('No attendee on primary registration while paying with PayPal Pro.',
104 104
                 'event_espresso'));
105 105
         }
106
-		$order_description  = $this->_format_order_description( $payment );
106
+		$order_description = $this->_format_order_description($payment);
107 107
 		//charge for the full amount. Show itemized list
108
-		if( $this->_can_easily_itemize_transaction_for( $payment ) ){
108
+		if ($this->_can_easily_itemize_transaction_for($payment)) {
109 109
 			$item_num = 1;
110 110
 			$total_line_item = $transaction->total_line_item();
111 111
 			$order_items = array();
112 112
 			foreach ($total_line_item->get_items() as $line_item) {
113 113
 				//ignore line items with a quantity of 0
114
-				if( $line_item->quantity() == 0 ) {
114
+				if ($line_item->quantity() == 0) {
115 115
 					continue;
116 116
 				}
117 117
 				$item = array(
118 118
 						// Item Name.  127 char max.
119 119
 						'l_name' => substr(
120
-							$this->_format_line_item_name( $line_item, $payment ),
120
+							$this->_format_line_item_name($line_item, $payment),
121 121
 							0,
122 122
 							127
123 123
 						),
124 124
 						// Item description.  127 char max.
125 125
 						'l_desc' => substr( 
126
-							$this->_format_line_item_desc( $line_item, $payment ),
126
+							$this->_format_line_item_desc($line_item, $payment),
127 127
 							0,
128 128
 							127
129 129
 						),
@@ -147,20 +147,20 @@  discard block
 block discarded – undo
147 147
 			}
148 148
 			$item_amount = $total_line_item->get_items_total();
149 149
 			$tax_amount = $total_line_item->get_total_tax();
150
-		}else{
150
+		} else {
151 151
 			$order_items = array();
152 152
 			$item_amount = $payment->amount();
153 153
 			$tax_amount = 0;
154
-			array_push($order_items,array(
154
+			array_push($order_items, array(
155 155
 				// Item Name.  127 char max.
156 156
 				'l_name' => substr(
157
-					$this->_format_partial_payment_line_item_name( $payment ),
157
+					$this->_format_partial_payment_line_item_name($payment),
158 158
 					0,
159 159
 					127
160 160
 				),
161 161
 				// Item description.  127 char max.
162 162
 				'l_desc' => substr( 
163
-					$this->_format_partial_payment_line_item_desc( $payment ),
163
+					$this->_format_partial_payment_line_item_desc($payment),
164 164
 					0,
165 165
 					127
166 166
 				),
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 			// Payer's salutation.  20 char max.
209 209
 			'salutation' => '',
210 210
 			// Payer's first name.  25 char max.
211
-			'firstname' => substr($billing_info['first_name'],0,25),
211
+			'firstname' => substr($billing_info['first_name'], 0, 25),
212 212
 			// Payer's middle name.  25 char max.
213 213
 			'middlename' => '',
214 214
 			// Payer's last name.  25 char max.
215
-			'lastname' => substr($billing_info['last_name'],0,25),
215
+			'lastname' => substr($billing_info['last_name'], 0, 25),
216 216
 			// Payer's suffix.  12 char max.
217 217
 			'suffix' => ''
218 218
 		);
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 			// Required.  Name of City.
226 226
 			'city' => $billing_info['city'],
227 227
 			// Required. Name of State or Province.
228
-			'state' => substr( $billing_info['state'], 0, 40 ),
228
+			'state' => substr($billing_info['state'], 0, 40),
229 229
 			// Required.  Country code.
230 230
 			'countrycode' => $billing_info['country'],
231 231
 			// Required.  Postal code of payer.
@@ -233,21 +233,21 @@  discard block
 block discarded – undo
233 233
 		);
234 234
 
235 235
         //check if the registration info contains the needed fields for paypal pro (see https://developer.paypal.com/docs/classic/api/merchant/DoDirectPayment_API_Operation_NVP/)
236
-        if($attendee->address() && $attendee->city() && $attendee->country_ID()){
236
+        if ($attendee->address() && $attendee->city() && $attendee->country_ID()) {
237 237
             $use_registration_address_info = true;
238 238
         } else {
239 239
             $use_registration_address_info = false;
240 240
         }
241 241
         //so if the attendee has enough data to fill out PayPal Pro's shipping info, use it. If not, use the billing info again
242 242
         $ShippingAddress = array(
243
-            'shiptoname' => substr($use_registration_address_info ? $attendee->full_name() : $billing_info['first_name'] . ' ' . $billing_info['last_name'], 0, 32),
243
+            'shiptoname' => substr($use_registration_address_info ? $attendee->full_name() : $billing_info['first_name'].' '.$billing_info['last_name'], 0, 32),
244 244
             'shiptostreet' => substr($use_registration_address_info ? $attendee->address() : $billing_info['address'], 0, 100),
245
-            'shiptostreet2' => substr($use_registration_address_info ? $attendee->address2() : $billing_info['address2'],0,100),
246
-            'shiptocity' => substr($use_registration_address_info ? $attendee->city() : $billing_info['city'],0,40),
247
-            'state' => substr($use_registration_address_info ? $attendee->state_name() : $billing_info['state'],0,40),
245
+            'shiptostreet2' => substr($use_registration_address_info ? $attendee->address2() : $billing_info['address2'], 0, 100),
246
+            'shiptocity' => substr($use_registration_address_info ? $attendee->city() : $billing_info['city'], 0, 40),
247
+            'state' => substr($use_registration_address_info ? $attendee->state_name() : $billing_info['state'], 0, 40),
248 248
             'shiptocountry' => $use_registration_address_info ? $attendee->country_ID() : $billing_info['country'],
249
-            'shiptozip' => substr($use_registration_address_info ? $attendee->zip() : $billing_info['zip'],0,20),
250
-            'shiptophonenum' => substr($use_registration_address_info ? $attendee->phone() : $billing_info['phone'],0,20),
249
+            'shiptozip' => substr($use_registration_address_info ? $attendee->zip() : $billing_info['zip'], 0, 20),
250
+            'shiptophonenum' => substr($use_registration_address_info ? $attendee->phone() : $billing_info['phone'], 0, 20),
251 251
         );
252 252
 
253 253
 		$PaymentDetails = array(
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 			// Required.  Three-letter currency code.  Default is USD.
257 257
 			'currencycode' => $payment->currency_code(),
258 258
 			// Required if you include itemized cart details. (L_AMTn, etc.)  Subtotal of items not including S&H, or tax.
259
-			'itemamt' => $this->format_currency($item_amount),//
259
+			'itemamt' => $this->format_currency($item_amount), //
260 260
 			// Total shipping costs for the order.  If you specify shippingamt, you must also specify itemamt.
261 261
 			'shippingamt' => '',
262 262
 			// Total handling costs for the order.  If you specify handlingamt, you must also specify itemamt.
@@ -268,10 +268,10 @@  discard block
 block discarded – undo
268 268
 			// Free-form field for your own use.  256 char max.
269 269
 			'custom' => $primary_registrant ? $primary_registrant->ID() : '',
270 270
 			// Your own invoice or tracking number
271
-			'invnum' => wp_generate_password(12,false),//$transaction->ID(),
271
+			'invnum' => wp_generate_password(12, false), //$transaction->ID(),
272 272
 			// URL for receiving Instant Payment Notifications.  This overrides what your profile is set to use.
273 273
 			'notifyurl' => '',
274
-			'buttonsource' => 'EventEspresso_SP',//EE will blow up if you change this
274
+			'buttonsource' => 'EventEspresso_SP', //EE will blow up if you change this
275 275
 		);
276 276
 		// Wrap all data arrays into a single, "master" array which will be passed into the class function.
277 277
 		$PayPalRequestData = array(
@@ -285,32 +285,32 @@  discard block
 block discarded – undo
285 285
 				'OrderItems' => $order_items,
286 286
 		);
287 287
 		$this->_log_clean_request($PayPalRequestData, $payment);
288
-		try{
288
+		try {
289 289
 			$PayPalResult = $this->prep_and_curl_request($PayPalRequestData);
290 290
 			//remove PCI-sensitive data so it doesn't get stored
291
-			$PayPalResult = $this->_log_clean_response($PayPalResult,$payment);
291
+			$PayPalResult = $this->_log_clean_response($PayPalResult, $payment);
292 292
 
293 293
 			$message = isset($PayPalResult['L_LONGMESSAGE0']) ? $PayPalResult['L_LONGMESSAGE0'] : $PayPalResult['ACK'];
294
-			if( empty($PayPalResult[ 'RAWRESPONSE' ] ) ) {
295
-				$payment->set_status( $this->_pay_model->failed_status() ) ;
296
-				$payment->set_gateway_response( __( 'No response received from Paypal Pro', 'event_espresso' ) );
294
+			if (empty($PayPalResult['RAWRESPONSE'])) {
295
+				$payment->set_status($this->_pay_model->failed_status());
296
+				$payment->set_gateway_response(__('No response received from Paypal Pro', 'event_espresso'));
297 297
 				$payment->set_details($PayPalResult);
298
-			}else{
299
-				if($this->_APICallSuccessful($PayPalResult)){
298
+			} else {
299
+				if ($this->_APICallSuccessful($PayPalResult)) {
300 300
 					$payment->set_status($this->_pay_model->approved_status());
301
-				}else{
301
+				} else {
302 302
 					$payment->set_status($this->_pay_model->declined_status());
303 303
 				}
304 304
 				//make sure we interpret the AMT as a float, not an international string (where periods are thousand separators)
305
-				$payment->set_amount(isset($PayPalResult['AMT']) ? floatval( $PayPalResult['AMT'] ) : 0);
305
+				$payment->set_amount(isset($PayPalResult['AMT']) ? floatval($PayPalResult['AMT']) : 0);
306 306
 				$payment->set_gateway_response($message);
307
-				$payment->set_txn_id_chq_nmbr(isset( $PayPalResult['TRANSACTIONID'] )? $PayPalResult['TRANSACTIONID'] : null);
307
+				$payment->set_txn_id_chq_nmbr(isset($PayPalResult['TRANSACTIONID']) ? $PayPalResult['TRANSACTIONID'] : null);
308 308
 
309 309
 				$primary_registration_code = $primary_registrant instanceof EE_Registration ? $primary_registrant->reg_code() : '';
310 310
 				$payment->set_extra_accntng($primary_registration_code);
311 311
 				$payment->set_details($PayPalResult);
312 312
 			}
313
-		}catch(Exception $e){
313
+		} catch (Exception $e) {
314 314
 			$payment->set_status($this->_pay_model->failed_status());
315 315
 			$payment->set_gateway_response($e->getMessage());
316 316
 		}
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 	 * @param EEI_Payment $payment
328 328
 	 * @return array
329 329
 	 */
330
-	private function _log_clean_request($request,$payment){
330
+	private function _log_clean_request($request, $payment) {
331 331
 		$cleaned_request_data = $request;
332 332
 		unset($cleaned_request_data['CCDetails']['acct']);
333 333
 		unset($cleaned_request_data['CCDetails']['cvv2']);
@@ -343,13 +343,13 @@  discard block
 block discarded – undo
343 343
 	 * @param EEI_Payment $payment
344 344
 	 * @return array cleaned
345 345
 	 */
346
-	private function _log_clean_response($response,$payment){
346
+	private function _log_clean_response($response, $payment) {
347 347
 		unset($response['REQUESTDATA']['CREDITCARDTYPE']);
348 348
 		unset($response['REQUESTDATA']['ACCT']);
349 349
 		unset($response['REQUESTDATA']['EXPDATE']);
350 350
 		unset($response['REQUESTDATA']['CVV2']);
351 351
 		unset($response['RAWREQUEST']);
352
-		$this->log(array('Paypal Response'=>$response),$payment);
352
+		$this->log(array('Paypal Response'=>$response), $payment);
353 353
 		return $response;
354 354
 	}
355 355
 
@@ -374,32 +374,32 @@  discard block
 block discarded – undo
374 374
 		// DP Fields
375 375
 		$DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array();
376 376
 		foreach ($DPFields as $DPFieldsVar => $DPFieldsVal)
377
-			$DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
377
+			$DPFieldsNVP .= '&'.strtoupper($DPFieldsVar).'='.urlencode($DPFieldsVal);
378 378
 
379 379
 		// CC Details Fields
380 380
 		$CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array();
381 381
 		foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal)
382
-			$CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
382
+			$CCDetailsNVP .= '&'.strtoupper($CCDetailsVar).'='.urlencode($CCDetailsVal);
383 383
 
384 384
 		// PayerInfo Type Fields
385 385
 		$PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array();
386 386
 		foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal)
387
-			$PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
387
+			$PayerInfoNVP .= '&'.strtoupper($PayerInfoVar).'='.urlencode($PayerInfoVal);
388 388
 
389 389
 		// Payer Name Fields
390 390
 		$PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array();
391 391
 		foreach ($PayerName as $PayerNameVar => $PayerNameVal)
392
-			$PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
392
+			$PayerNameNVP .= '&'.strtoupper($PayerNameVar).'='.urlencode($PayerNameVal);
393 393
 
394 394
 		// Address Fields (Billing)
395 395
 		$BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
396 396
 		foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal)
397
-			$BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
397
+			$BillingAddressNVP .= '&'.strtoupper($BillingAddressVar).'='.urlencode($BillingAddressVal);
398 398
 
399 399
 		// Payment Details Type Fields
400 400
 		$PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array();
401 401
 		foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal)
402
-			$PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
402
+			$PaymentDetailsNVP .= '&'.strtoupper($PaymentDetailsVar).'='.urlencode($PaymentDetailsVal);
403 403
 
404 404
 		// Payment Details Item Type Fields
405 405
 		$OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array();
@@ -407,22 +407,22 @@  discard block
 block discarded – undo
407 407
 		foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) {
408 408
 			$CurrentItem = $OrderItems[$OrderItemsVar];
409 409
 			foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal)
410
-				$OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
410
+				$OrderItemsNVP .= '&'.strtoupper($CurrentItemVar).$n.'='.urlencode($CurrentItemVal);
411 411
 			$n++;
412 412
 		}
413 413
 
414 414
 		// Ship To Address Fields
415 415
 		$ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array();
416 416
 		foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal)
417
-			$ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
417
+			$ShippingAddressNVP .= '&'.strtoupper($ShippingAddressVar).'='.urlencode($ShippingAddressVal);
418 418
 
419 419
 		// 3D Secure Fields
420 420
 		$Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array();
421 421
 		foreach ($Secure3D as $Secure3DVar => $Secure3DVal)
422
-			$Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
422
+			$Secure3DNVP .= '&'.strtoupper($Secure3DVar).'='.urlencode($Secure3DVal);
423 423
 
424 424
 		// Now that we have each chunk we need to go ahead and append them all together for our entire NVP string
425
-		$NVPRequest = 'USER=' . $this->_username . '&PWD=' . $this->_password . '&VERSION=64.0' . '&SIGNATURE=' . $this->_signature . $DPFieldsNVP . $CCDetailsNVP . $PayerInfoNVP . $PayerNameNVP . $BillingAddressNVP . $PaymentDetailsNVP . $OrderItemsNVP . $ShippingAddressNVP . $Secure3DNVP;
425
+		$NVPRequest = 'USER='.$this->_username.'&PWD='.$this->_password.'&VERSION=64.0'.'&SIGNATURE='.$this->_signature.$DPFieldsNVP.$CCDetailsNVP.$PayerInfoNVP.$PayerNameNVP.$BillingAddressNVP.$PaymentDetailsNVP.$OrderItemsNVP.$ShippingAddressNVP.$Secure3DNVP;
426 426
 		$NVPResponse = $this->_CURLRequest($NVPRequest);
427 427
 		$NVPRequestArray = $this->_NVPToArray($NVPRequest);
428 428
 		$NVPResponseArray = $this->_NVPToArray($NVPResponse);
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 	private function _CURLRequest($Request) {
447 447
 		$EndPointURL = $this->_debug_mode ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
448 448
 		$curl = curl_init();
449
-		curl_setopt($curl, CURLOPT_VERBOSE, apply_filters('FHEE__EEG_Paypal_Pro__CurlRequest__CURLOPT_VERBOSE', TRUE ) );
449
+		curl_setopt($curl, CURLOPT_VERBOSE, apply_filters('FHEE__EEG_Paypal_Pro__CurlRequest__CURLOPT_VERBOSE', TRUE));
450 450
 		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
451 451
 		curl_setopt($curl, CURLOPT_TIMEOUT, 60);
452 452
 		curl_setopt($curl, CURLOPT_URL, $EndPointURL);
@@ -496,9 +496,9 @@  discard block
 block discarded – undo
496 496
 	private function _APICallSuccessful($PayPalResult) {
497 497
 		$approved = false;
498 498
 		// check main response message from PayPal
499
-		if (isset($PayPalResult['ACK']) && !empty($PayPalResult['ACK'])) {
499
+		if (isset($PayPalResult['ACK']) && ! empty($PayPalResult['ACK'])) {
500 500
 			$ack = strtoupper($PayPalResult['ACK']);
501
-			$approved = ( $ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING' || $ack == 'PARTIALSUCCESS' ) ? true : false;
501
+			$approved = ($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING' || $ack == 'PARTIALSUCCESS') ? true : false;
502 502
 		}
503 503
 
504 504
 		return $approved;
@@ -514,11 +514,11 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$Errors = array();
516 516
 		$n = 0;
517
-		while (isset($DataArray['L_ERRORCODE' . $n . ''])) {
518
-			$LErrorCode = isset($DataArray['L_ERRORCODE' . $n . '']) ? $DataArray['L_ERRORCODE' . $n . ''] : '';
519
-			$LShortMessage = isset($DataArray['L_SHORTMESSAGE' . $n . '']) ? $DataArray['L_SHORTMESSAGE' . $n . ''] : '';
520
-			$LLongMessage = isset($DataArray['L_LONGMESSAGE' . $n . '']) ? $DataArray['L_LONGMESSAGE' . $n . ''] : '';
521
-			$LSeverityCode = isset($DataArray['L_SEVERITYCODE' . $n . '']) ? $DataArray['L_SEVERITYCODE' . $n . ''] : '';
517
+		while (isset($DataArray['L_ERRORCODE'.$n.''])) {
518
+			$LErrorCode = isset($DataArray['L_ERRORCODE'.$n.'']) ? $DataArray['L_ERRORCODE'.$n.''] : '';
519
+			$LShortMessage = isset($DataArray['L_SHORTMESSAGE'.$n.'']) ? $DataArray['L_SHORTMESSAGE'.$n.''] : '';
520
+			$LLongMessage = isset($DataArray['L_LONGMESSAGE'.$n.'']) ? $DataArray['L_LONGMESSAGE'.$n.''] : '';
521
+			$LSeverityCode = isset($DataArray['L_SEVERITYCODE'.$n.'']) ? $DataArray['L_SEVERITYCODE'.$n.''] : '';
522 522
 
523 523
 			$CurrentItem = array(
524 524
 					'L_ERRORCODE' => $LErrorCode,
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 				elseif ($CurrentErrorVar == 'L_SEVERITYCODE')
559 559
 					$CurrentVarName = 'Severity Code';
560 560
 
561
-				$error .= '<br />' . $CurrentVarName . ': ' . $CurrentErrorVal;
561
+				$error .= '<br />'.$CurrentVarName.': '.$CurrentErrorVal;
562 562
 			}
563 563
 		}
564 564
 		return $error;
Please login to merge, or discard this patch.
Braces   +42 added lines, -31 removed lines patch added patch discarded remove patch
@@ -1,7 +1,8 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION'))
3
+if (!defined('EVENT_ESPRESSO_VERSION')) {
4 4
 	exit('No direct script access allowed');
5
+}
5 6
 
6 7
 /**
7 8
  * Event Espresso
@@ -147,7 +148,7 @@  discard block
 block discarded – undo
147 148
 			}
148 149
 			$item_amount = $total_line_item->get_items_total();
149 150
 			$tax_amount = $total_line_item->get_total_tax();
150
-		}else{
151
+		} else{
151 152
 			$order_items = array();
152 153
 			$item_amount = $payment->amount();
153 154
 			$tax_amount = 0;
@@ -295,10 +296,10 @@  discard block
 block discarded – undo
295 296
 				$payment->set_status( $this->_pay_model->failed_status() ) ;
296 297
 				$payment->set_gateway_response( __( 'No response received from Paypal Pro', 'event_espresso' ) );
297 298
 				$payment->set_details($PayPalResult);
298
-			}else{
299
+			} else{
299 300
 				if($this->_APICallSuccessful($PayPalResult)){
300 301
 					$payment->set_status($this->_pay_model->approved_status());
301
-				}else{
302
+				} else{
302 303
 					$payment->set_status($this->_pay_model->declined_status());
303 304
 				}
304 305
 				//make sure we interpret the AMT as a float, not an international string (where periods are thousand separators)
@@ -310,7 +311,7 @@  discard block
 block discarded – undo
310 311
 				$payment->set_extra_accntng($primary_registration_code);
311 312
 				$payment->set_details($PayPalResult);
312 313
 			}
313
-		}catch(Exception $e){
314
+		} catch(Exception $e){
314 315
 			$payment->set_status($this->_pay_model->failed_status());
315 316
 			$payment->set_gateway_response($e->getMessage());
316 317
 		}
@@ -373,53 +374,62 @@  discard block
 block discarded – undo
373 374
 
374 375
 		// DP Fields
375 376
 		$DPFields = isset($DataArray['DPFields']) ? $DataArray['DPFields'] : array();
376
-		foreach ($DPFields as $DPFieldsVar => $DPFieldsVal)
377
-			$DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
377
+		foreach ($DPFields as $DPFieldsVar => $DPFieldsVal) {
378
+					$DPFieldsNVP .= '&' . strtoupper($DPFieldsVar) . '=' . urlencode($DPFieldsVal);
379
+		}
378 380
 
379 381
 		// CC Details Fields
380 382
 		$CCDetails = isset($DataArray['CCDetails']) ? $DataArray['CCDetails'] : array();
381
-		foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal)
382
-			$CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
383
+		foreach ($CCDetails as $CCDetailsVar => $CCDetailsVal) {
384
+					$CCDetailsNVP .= '&' . strtoupper($CCDetailsVar) . '=' . urlencode($CCDetailsVal);
385
+		}
383 386
 
384 387
 		// PayerInfo Type Fields
385 388
 		$PayerInfo = isset($DataArray['PayerInfo']) ? $DataArray['PayerInfo'] : array();
386
-		foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal)
387
-			$PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
389
+		foreach ($PayerInfo as $PayerInfoVar => $PayerInfoVal) {
390
+					$PayerInfoNVP .= '&' . strtoupper($PayerInfoVar) . '=' . urlencode($PayerInfoVal);
391
+		}
388 392
 
389 393
 		// Payer Name Fields
390 394
 		$PayerName = isset($DataArray['PayerName']) ? $DataArray['PayerName'] : array();
391
-		foreach ($PayerName as $PayerNameVar => $PayerNameVal)
392
-			$PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
395
+		foreach ($PayerName as $PayerNameVar => $PayerNameVal) {
396
+					$PayerNameNVP .= '&' . strtoupper($PayerNameVar) . '=' . urlencode($PayerNameVal);
397
+		}
393 398
 
394 399
 		// Address Fields (Billing)
395 400
 		$BillingAddress = isset($DataArray['BillingAddress']) ? $DataArray['BillingAddress'] : array();
396
-		foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal)
397
-			$BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
401
+		foreach ($BillingAddress as $BillingAddressVar => $BillingAddressVal) {
402
+					$BillingAddressNVP .= '&' . strtoupper($BillingAddressVar) . '=' . urlencode($BillingAddressVal);
403
+		}
398 404
 
399 405
 		// Payment Details Type Fields
400 406
 		$PaymentDetails = isset($DataArray['PaymentDetails']) ? $DataArray['PaymentDetails'] : array();
401
-		foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal)
402
-			$PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
407
+		foreach ($PaymentDetails as $PaymentDetailsVar => $PaymentDetailsVal) {
408
+					$PaymentDetailsNVP .= '&' . strtoupper($PaymentDetailsVar) . '=' . urlencode($PaymentDetailsVal);
409
+		}
403 410
 
404 411
 		// Payment Details Item Type Fields
405 412
 		$OrderItems = isset($DataArray['OrderItems']) ? $DataArray['OrderItems'] : array();
406 413
 		$n = 0;
407 414
 		foreach ($OrderItems as $OrderItemsVar => $OrderItemsVal) {
408 415
 			$CurrentItem = $OrderItems[$OrderItemsVar];
409
-			foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal)
410
-				$OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
416
+			foreach ($CurrentItem as $CurrentItemVar => $CurrentItemVal) {
417
+							$OrderItemsNVP .= '&' . strtoupper($CurrentItemVar) . $n . '=' . urlencode($CurrentItemVal);
418
+			}
411 419
 			$n++;
412 420
 		}
413 421
 
414 422
 		// Ship To Address Fields
415 423
 		$ShippingAddress = isset($DataArray['ShippingAddress']) ? $DataArray['ShippingAddress'] : array();
416
-		foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal)
417
-			$ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
424
+		foreach ($ShippingAddress as $ShippingAddressVar => $ShippingAddressVal) {
425
+					$ShippingAddressNVP .= '&' . strtoupper($ShippingAddressVar) . '=' . urlencode($ShippingAddressVal);
426
+		}
418 427
 
419 428
 		// 3D Secure Fields
420 429
 		$Secure3D = isset($DataArray['Secure3D']) ? $DataArray['Secure3D'] : array();
421
-		foreach ($Secure3D as $Secure3DVar => $Secure3DVal)
422
-			$Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
430
+		foreach ($Secure3D as $Secure3DVar => $Secure3DVal) {
431
+					$Secure3DNVP .= '&' . strtoupper($Secure3DVar) . '=' . urlencode($Secure3DVal);
432
+		}
423 433
 
424 434
 		// Now that we have each chunk we need to go ahead and append them all together for our entire NVP string
425 435
 		$NVPRequest = 'USER=' . $this->_username . '&PWD=' . $this->_password . '&VERSION=64.0' . '&SIGNATURE=' . $this->_signature . $DPFieldsNVP . $CCDetailsNVP . $PayerInfoNVP . $PayerNameNVP . $BillingAddressNVP . $PaymentDetailsNVP . $OrderItemsNVP . $ShippingAddressNVP . $Secure3DNVP;
@@ -549,14 +559,15 @@  discard block
 block discarded – undo
549 559
 			$CurrentError = $Errors[$ErrorVar];
550 560
 			foreach ($CurrentError as $CurrentErrorVar => $CurrentErrorVal) {
551 561
 				$CurrentVarName = '';
552
-				if ($CurrentErrorVar == 'L_ERRORCODE')
553
-					$CurrentVarName = 'Error Code';
554
-				elseif ($CurrentErrorVar == 'L_SHORTMESSAGE')
555
-					$CurrentVarName = 'Short Message';
556
-				elseif ($CurrentErrorVar == 'L_LONGMESSAGE')
557
-					$CurrentVarName = 'Long Message';
558
-				elseif ($CurrentErrorVar == 'L_SEVERITYCODE')
559
-					$CurrentVarName = 'Severity Code';
562
+				if ($CurrentErrorVar == 'L_ERRORCODE') {
563
+									$CurrentVarName = 'Error Code';
564
+				} elseif ($CurrentErrorVar == 'L_SHORTMESSAGE') {
565
+									$CurrentVarName = 'Short Message';
566
+				} elseif ($CurrentErrorVar == 'L_LONGMESSAGE') {
567
+									$CurrentVarName = 'Long Message';
568
+				} elseif ($CurrentErrorVar == 'L_SEVERITYCODE') {
569
+									$CurrentVarName = 'Severity Code';
570
+				}
560 571
 
561 572
 				$error .= '<br />' . $CurrentVarName . ': ' . $CurrentErrorVal;
562 573
 			}
Please login to merge, or discard this patch.