Completed
Branch FET/datetime-and-event-status (270044)
by
unknown
04:26 queued 14s
created
core/db_classes/EE_Extra_Meta.class.php 1 patch
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -10,115 +10,115 @@
 block discarded – undo
10 10
 class EE_Extra_Meta extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Extra_Meta|mixed
16
-     */
17
-    public static function new_instance($props_n_values = array())
18
-    {
19
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
-        return $has_object ? $has_object : new self($props_n_values);
21
-    }
22
-
23
-
24
-    /**
25
-     * @param array $props_n_values
26
-     * @return EE_Extra_Meta
27
-     */
28
-    public static function new_instance_from_db($props_n_values = array())
29
-    {
30
-        return new self($props_n_values, true);
31
-    }
32
-
33
-
34
-    /**
35
-     * Gets FK_ID
36
-     *
37
-     * @return int
38
-     */
39
-    public function FK_ID()
40
-    {
41
-        return $this->get('FK_ID');
42
-    }
43
-
44
-
45
-    /**
46
-     * Sets FK_ID
47
-     *
48
-     * @param int $FK_ID
49
-     * @return boolean
50
-     */
51
-    public function set_FK_ID($FK_ID)
52
-    {
53
-        $this->set('FK_ID', $FK_ID);
54
-    }
55
-
56
-
57
-    /**
58
-     * Gets model
59
-     *
60
-     * @return string
61
-     */
62
-    public function model()
63
-    {
64
-        return $this->get('EXM_model');
65
-    }
66
-
67
-
68
-    /**
69
-     * Sets model
70
-     *
71
-     * @param string $model
72
-     * @return boolean
73
-     */
74
-    public function set_model($model)
75
-    {
76
-        $this->set('EXM_model', $model);
77
-    }
78
-
79
-
80
-    /**
81
-     * Gets key
82
-     *
83
-     * @return string
84
-     */
85
-    public function key()
86
-    {
87
-        return $this->get('EXM_key');
88
-    }
89
-
90
-
91
-    /**
92
-     * Sets key
93
-     *
94
-     * @param string $key
95
-     * @return boolean
96
-     */
97
-    public function set_key($key)
98
-    {
99
-        $this->set('EXM_key', $key);
100
-    }
101
-
102
-
103
-    /**
104
-     * Gets value
105
-     *
106
-     * @return string
107
-     */
108
-    public function value()
109
-    {
110
-        return $this->get('EXM_value');
111
-    }
112
-
113
-
114
-    /**
115
-     * Sets value
116
-     *
117
-     * @param string $value
118
-     * @return boolean
119
-     */
120
-    public function set_value($value)
121
-    {
122
-        $this->set('EXM_value', $value);
123
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Extra_Meta|mixed
16
+	 */
17
+	public static function new_instance($props_n_values = array())
18
+	{
19
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
+		return $has_object ? $has_object : new self($props_n_values);
21
+	}
22
+
23
+
24
+	/**
25
+	 * @param array $props_n_values
26
+	 * @return EE_Extra_Meta
27
+	 */
28
+	public static function new_instance_from_db($props_n_values = array())
29
+	{
30
+		return new self($props_n_values, true);
31
+	}
32
+
33
+
34
+	/**
35
+	 * Gets FK_ID
36
+	 *
37
+	 * @return int
38
+	 */
39
+	public function FK_ID()
40
+	{
41
+		return $this->get('FK_ID');
42
+	}
43
+
44
+
45
+	/**
46
+	 * Sets FK_ID
47
+	 *
48
+	 * @param int $FK_ID
49
+	 * @return boolean
50
+	 */
51
+	public function set_FK_ID($FK_ID)
52
+	{
53
+		$this->set('FK_ID', $FK_ID);
54
+	}
55
+
56
+
57
+	/**
58
+	 * Gets model
59
+	 *
60
+	 * @return string
61
+	 */
62
+	public function model()
63
+	{
64
+		return $this->get('EXM_model');
65
+	}
66
+
67
+
68
+	/**
69
+	 * Sets model
70
+	 *
71
+	 * @param string $model
72
+	 * @return boolean
73
+	 */
74
+	public function set_model($model)
75
+	{
76
+		$this->set('EXM_model', $model);
77
+	}
78
+
79
+
80
+	/**
81
+	 * Gets key
82
+	 *
83
+	 * @return string
84
+	 */
85
+	public function key()
86
+	{
87
+		return $this->get('EXM_key');
88
+	}
89
+
90
+
91
+	/**
92
+	 * Sets key
93
+	 *
94
+	 * @param string $key
95
+	 * @return boolean
96
+	 */
97
+	public function set_key($key)
98
+	{
99
+		$this->set('EXM_key', $key);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Gets value
105
+	 *
106
+	 * @return string
107
+	 */
108
+	public function value()
109
+	{
110
+		return $this->get('EXM_value');
111
+	}
112
+
113
+
114
+	/**
115
+	 * Sets value
116
+	 *
117
+	 * @param string $value
118
+	 * @return boolean
119
+	 */
120
+	public function set_value($value)
121
+	{
122
+		$this->set('EXM_value', $value);
123
+	}
124 124
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Post_Meta.class.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -10,112 +10,112 @@
 block discarded – undo
10 10
 class EE_Post_Meta extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Post_Meta|mixed
16
-     */
17
-    public static function new_instance($props_n_values = array())
18
-    {
19
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
-        return $has_object ? $has_object : new self($props_n_values);
21
-    }
22
-
23
-
24
-    /**
25
-     * @param array $props_n_values
26
-     * @return EE_Post_Meta
27
-     */
28
-    public static function new_instance_from_db($props_n_values = array())
29
-    {
30
-        return new self($props_n_values, true);
31
-    }
32
-
33
-
34
-    /**
35
-     * Gets meta_id
36
-     *
37
-     * @return int
38
-     */
39
-    public function meta_id()
40
-    {
41
-        return $this->get('meta_id');
42
-    }
43
-
44
-
45
-    /**
46
-     * Sets meta_id
47
-     *
48
-     * @param int $meta_id
49
-     * @return boolean
50
-     */
51
-    public function set_meta_id($meta_id)
52
-    {
53
-        return $this->set('meta_id', $meta_id);
54
-    }
55
-
56
-    /**
57
-     * Gets post_id
58
-     *
59
-     * @return int
60
-     */
61
-    public function post_id()
62
-    {
63
-        return $this->get('post_id');
64
-    }
65
-
66
-
67
-    /**
68
-     * Sets post_id
69
-     *
70
-     * @param int $post_id
71
-     * @return boolean
72
-     */
73
-    public function set_post_id($post_id)
74
-    {
75
-        return $this->set('post_id', $post_id);
76
-    }
77
-
78
-    /**
79
-     * Gets meta_key
80
-     *
81
-     * @return string
82
-     */
83
-    public function meta_key()
84
-    {
85
-        return $this->get('meta_key');
86
-    }
87
-
88
-
89
-    /**
90
-     * Sets meta_key
91
-     *
92
-     * @param string $meta_key
93
-     * @return boolean
94
-     */
95
-    public function set_meta_key($meta_key)
96
-    {
97
-        return $this->set('meta_key', $meta_key);
98
-    }
99
-
100
-    /**
101
-     * Gets meta_value
102
-     *
103
-     * @return mixed
104
-     */
105
-    public function meta_value()
106
-    {
107
-        return $this->get('meta_value');
108
-    }
109
-
110
-
111
-    /**
112
-     * Sets meta_value
113
-     *
114
-     * @param mixed $meta_value
115
-     * @return boolean
116
-     */
117
-    public function set_meta_value($meta_value)
118
-    {
119
-        return $this->set('meta_value', $meta_value);
120
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Post_Meta|mixed
16
+	 */
17
+	public static function new_instance($props_n_values = array())
18
+	{
19
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
+		return $has_object ? $has_object : new self($props_n_values);
21
+	}
22
+
23
+
24
+	/**
25
+	 * @param array $props_n_values
26
+	 * @return EE_Post_Meta
27
+	 */
28
+	public static function new_instance_from_db($props_n_values = array())
29
+	{
30
+		return new self($props_n_values, true);
31
+	}
32
+
33
+
34
+	/**
35
+	 * Gets meta_id
36
+	 *
37
+	 * @return int
38
+	 */
39
+	public function meta_id()
40
+	{
41
+		return $this->get('meta_id');
42
+	}
43
+
44
+
45
+	/**
46
+	 * Sets meta_id
47
+	 *
48
+	 * @param int $meta_id
49
+	 * @return boolean
50
+	 */
51
+	public function set_meta_id($meta_id)
52
+	{
53
+		return $this->set('meta_id', $meta_id);
54
+	}
55
+
56
+	/**
57
+	 * Gets post_id
58
+	 *
59
+	 * @return int
60
+	 */
61
+	public function post_id()
62
+	{
63
+		return $this->get('post_id');
64
+	}
65
+
66
+
67
+	/**
68
+	 * Sets post_id
69
+	 *
70
+	 * @param int $post_id
71
+	 * @return boolean
72
+	 */
73
+	public function set_post_id($post_id)
74
+	{
75
+		return $this->set('post_id', $post_id);
76
+	}
77
+
78
+	/**
79
+	 * Gets meta_key
80
+	 *
81
+	 * @return string
82
+	 */
83
+	public function meta_key()
84
+	{
85
+		return $this->get('meta_key');
86
+	}
87
+
88
+
89
+	/**
90
+	 * Sets meta_key
91
+	 *
92
+	 * @param string $meta_key
93
+	 * @return boolean
94
+	 */
95
+	public function set_meta_key($meta_key)
96
+	{
97
+		return $this->set('meta_key', $meta_key);
98
+	}
99
+
100
+	/**
101
+	 * Gets meta_value
102
+	 *
103
+	 * @return mixed
104
+	 */
105
+	public function meta_value()
106
+	{
107
+		return $this->get('meta_value');
108
+	}
109
+
110
+
111
+	/**
112
+	 * Sets meta_value
113
+	 *
114
+	 * @param mixed $meta_value
115
+	 * @return boolean
116
+	 */
117
+	public function set_meta_value($meta_value)
118
+	{
119
+		return $this->set('meta_value', $meta_value);
120
+	}
121 121
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Question.class.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
      */
336 336
     public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
337 337
     {
338
-        if (! $this->ID()) {
338
+        if ( ! $this->ID()) {
339 339
             return array();
340 340
         }
341 341
         $query_params = array();
@@ -509,7 +509,7 @@  discard block
 block discarded – undo
509 509
             ),
510 510
             $input_constructor_args
511 511
         );
512
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
512
+        if ( ! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
513 513
             $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
514 514
         }
515 515
         // has this question been answered ?
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
                     $this,
648 648
                     $input_constructor_args
649 649
                 );
650
-                if (! $default_input) {
650
+                if ( ! $default_input) {
651 651
                     $default_input = new EE_Text_Input($input_constructor_args);
652 652
                 }
653 653
                 $result = $default_input;
Please login to merge, or discard this patch.
Indentation   +664 added lines, -664 removed lines patch added patch discarded remove patch
@@ -14,668 +14,668 @@
 block discarded – undo
14 14
 class EE_Question extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
15 15
 {
16 16
 
17
-    /**
18
-     *
19
-     * @param array  $props_n_values          incoming values
20
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
21
-     *                                        used.)
22
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
23
-     *                                        date_format and the second value is the time format
24
-     * @return EE_Question
25
-     */
26
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
27
-    {
28
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
29
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
30
-    }
31
-
32
-
33
-    /**
34
-     * @param array  $props_n_values  incoming values from the database
35
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
36
-     *                                the website will be used.
37
-     * @return EE_Question
38
-     */
39
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
40
-    {
41
-        return new self($props_n_values, true, $timezone);
42
-    }
43
-
44
-
45
-    /**
46
-     *        Set    Question display text
47
-     *
48
-     * @access        public
49
-     * @param string $QST_display_text
50
-     */
51
-    public function set_display_text($QST_display_text = '')
52
-    {
53
-        $this->set('QST_display_text', $QST_display_text);
54
-    }
55
-
56
-
57
-    /**
58
-     *        Set    Question admin text
59
-     *
60
-     * @access        public
61
-     * @param        string $QST_admin_label
62
-     */
63
-    public function set_admin_label($QST_admin_label = '')
64
-    {
65
-        $this->set('QST_admin_label', $QST_admin_label);
66
-    }
67
-
68
-
69
-    /**
70
-     *        Set    system name
71
-     *
72
-     * @access        public
73
-     * @param        mixed $QST_system
74
-     */
75
-    public function set_system_ID($QST_system = '')
76
-    {
77
-        $this->set('QST_system', $QST_system);
78
-    }
79
-
80
-
81
-    /**
82
-     *        Set    question's type
83
-     *
84
-     * @access        public
85
-     * @param        string $QST_type
86
-     */
87
-    public function set_question_type($QST_type = '')
88
-    {
89
-        $this->set('QST_type', $QST_type);
90
-    }
91
-
92
-
93
-    /**
94
-     *        Sets whether this question must be answered when presented in a form
95
-     *
96
-     * @access        public
97
-     * @param        bool $QST_required
98
-     */
99
-    public function set_required($QST_required = false)
100
-    {
101
-        $this->set('QST_required', $QST_required);
102
-    }
103
-
104
-
105
-    /**
106
-     *        Set    Question display text
107
-     *
108
-     * @access        public
109
-     * @param        string $QST_required_text
110
-     */
111
-    public function set_required_text($QST_required_text = '')
112
-    {
113
-        $this->set('QST_required_text', $QST_required_text);
114
-    }
115
-
116
-
117
-    /**
118
-     *        Sets the order of this question when placed in a sequence of questions
119
-     *
120
-     * @access        public
121
-     * @param        int $QST_order
122
-     */
123
-    public function set_order($QST_order = 0)
124
-    {
125
-        $this->set('QST_order', $QST_order);
126
-    }
127
-
128
-
129
-    /**
130
-     *        Sets whether the question is admin-only
131
-     *
132
-     * @access        public
133
-     * @param        bool $QST_admin_only
134
-     */
135
-    public function set_admin_only($QST_admin_only = false)
136
-    {
137
-        $this->set('QST_admin_only', $QST_admin_only);
138
-    }
139
-
140
-
141
-    /**
142
-     *        Sets the wordpress user ID on the question
143
-     *
144
-     * @access        public
145
-     * @param        int $QST_wp_user
146
-     */
147
-    public function set_wp_user($QST_wp_user = 1)
148
-    {
149
-        $this->set('QST_wp_user', $QST_wp_user);
150
-    }
151
-
152
-
153
-    /**
154
-     *        Sets whether the question has been deleted
155
-     *        (we use this boolean instead of actually
156
-     *        deleting it because when users delete this question
157
-     *        they really want to remove the question from future
158
-     *        forms, BUT keep their old answers which depend
159
-     *        on this record actually existing.
160
-     *
161
-     * @access        public
162
-     * @param    bool $QST_deleted
163
-     */
164
-    public function set_deleted($QST_deleted = false)
165
-    {
166
-        $this->set('QST_deleted', $QST_deleted);
167
-    }
168
-
169
-
170
-    /**
171
-     * returns the text for displaying the question to users
172
-     *
173
-     * @access public
174
-     * @return string
175
-     */
176
-    public function display_text()
177
-    {
178
-        return $this->get('QST_display_text');
179
-    }
180
-
181
-
182
-    /**
183
-     * returns the text for the administrative label
184
-     *
185
-     * @access public
186
-     * @return string
187
-     */
188
-    public function admin_label()
189
-    {
190
-        return $this->get('QST_admin_label');
191
-    }
192
-
193
-
194
-    /**
195
-     * returns the attendee column name for this question
196
-     *
197
-     * @access public
198
-     * @return string
199
-     */
200
-    public function system_ID()
201
-    {
202
-        return $this->get('QST_system');
203
-    }
204
-
205
-
206
-    /**
207
-     * returns either a string of 'text', 'textfield', etc.
208
-     *
209
-     * @access public
210
-     * @return boolean
211
-     */
212
-    public function required()
213
-    {
214
-        return $this->get('QST_required');
215
-    }
216
-
217
-
218
-    /**
219
-     * returns the text which should be displayed when a user
220
-     * doesn't answer this question in a form
221
-     *
222
-     * @access public
223
-     * @return string
224
-     */
225
-    public function required_text()
226
-    {
227
-        return $this->get('QST_required_text');
228
-    }
229
-
230
-
231
-    /**
232
-     * returns the type of this question
233
-     *
234
-     * @access public
235
-     * @return string
236
-     */
237
-    public function type()
238
-    {
239
-        return $this->get('QST_type');
240
-    }
241
-
242
-
243
-    /**
244
-     * returns an integer showing where this question should
245
-     * be placed in a sequence of questions
246
-     *
247
-     * @access public
248
-     * @return int
249
-     */
250
-    public function order()
251
-    {
252
-        return $this->get('QST_order');
253
-    }
254
-
255
-
256
-    /**
257
-     * returns whether this question should only appears to admins,
258
-     * or to everyone
259
-     *
260
-     * @access public
261
-     * @return boolean
262
-     */
263
-    public function admin_only()
264
-    {
265
-        return $this->get('QST_admin_only');
266
-    }
267
-
268
-
269
-    /**
270
-     * returns the id the wordpress user who created this question
271
-     *
272
-     * @access public
273
-     * @return int
274
-     */
275
-    public function wp_user()
276
-    {
277
-        return $this->get('QST_wp_user');
278
-    }
279
-
280
-
281
-    /**
282
-     * returns whether this question has been marked as 'deleted'
283
-     *
284
-     * @access public
285
-     * @return boolean
286
-     */
287
-    public function deleted()
288
-    {
289
-        return $this->get('QST_deleted');
290
-    }
291
-
292
-
293
-    /**
294
-     * Gets an array of related EE_Answer  to this EE_Question
295
-     *
296
-     * @return EE_Answer[]
297
-     */
298
-    public function answers()
299
-    {
300
-        return $this->get_many_related('Answer');
301
-    }
302
-
303
-
304
-    /**
305
-     * Boolean check for if there are answers on this question in th db
306
-     *
307
-     * @return boolean true = has answers, false = no answers.
308
-     */
309
-    public function has_answers()
310
-    {
311
-        return $this->count_related('Answer') > 0 ? true : false;
312
-    }
313
-
314
-
315
-    /**
316
-     * gets an array of EE_Question_Group which relate to this question
317
-     *
318
-     * @return EE_Question_Group[]
319
-     */
320
-    public function question_groups()
321
-    {
322
-        return $this->get_many_related('Question_Group');
323
-    }
324
-
325
-
326
-    /**
327
-     * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
328
-     *
329
-     * @param boolean      $notDeletedOptionsOnly            1
330
-     *                                                       whether to return ALL options, or only the ones which have
331
-     *                                                       not yet been deleleted
332
-     * @param string|array $selected_value_to_always_include , when retrieving options to an ANSWERED question,
333
-     *                                                       we want to usually only show non-deleted options AND the
334
-     *                                                       value that was selected for the answer, whether it was
335
-     *                                                       trashed or not.
336
-     * @return EE_Question_Option[]
337
-     */
338
-    public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
339
-    {
340
-        if (! $this->ID()) {
341
-            return array();
342
-        }
343
-        $query_params = array();
344
-        if ($selected_value_to_always_include) {
345
-            if (is_array($selected_value_to_always_include)) {
346
-                $query_params[0]['OR*options-query']['QSO_value'] = array('IN', $selected_value_to_always_include);
347
-            } else {
348
-                $query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
349
-            }
350
-        }
351
-        if ($notDeletedOptionsOnly) {
352
-            $query_params[0]['OR*options-query']['QSO_deleted'] = false;
353
-        }
354
-        // order by QSO_order
355
-        $query_params['order_by'] = array('QSO_order' => 'ASC');
356
-        return $this->get_many_related('Question_Option', $query_params);
357
-    }
358
-
359
-
360
-    /**
361
-     * returns an array of EE_Question_Options which relate to this question
362
-     *
363
-     * @return \EE_Question_Option[]
364
-     */
365
-    public function temp_options()
366
-    {
367
-        return $this->_model_relations['Question_Option'];
368
-    }
369
-
370
-
371
-    /**
372
-     * Adds an option for this question. Note: if the option were previously associated with a different
373
-     * Question, that relationship will be overwritten.
374
-     *
375
-     * @param EE_Question_Option $option
376
-     * @return boolean success
377
-     */
378
-    public function add_option(EE_Question_Option $option)
379
-    {
380
-        return $this->_add_relation_to($option, 'Question_Option');
381
-    }
382
-
383
-
384
-    /**
385
-     * Adds an option directly to this question without saving to the db
386
-     *
387
-     * @param EE_Question_Option $option
388
-     * @return boolean success
389
-     */
390
-    public function add_temp_option(EE_Question_Option $option)
391
-    {
392
-        $this->_model_relations['Question_Option'][] = $option;
393
-        return true;
394
-    }
395
-
396
-
397
-    /**
398
-     * Marks the option as deleted.
399
-     *
400
-     * @param EE_Question_Option $option
401
-     * @return boolean success
402
-     */
403
-    public function remove_option(EE_Question_Option $option)
404
-    {
405
-        return $this->_remove_relation_to($option, 'Question_Option');
406
-    }
407
-
408
-
409
-    /**
410
-     * @return bool
411
-     */
412
-    public function is_system_question()
413
-    {
414
-        $system_ID = $this->get('QST_system');
415
-        return ! empty($system_ID) ? true : false;
416
-    }
417
-
418
-
419
-    /**
420
-     * The purpose of this method is set the question order this question order to be the max out of all questions
421
-     *
422
-     * @access public
423
-     * @return void
424
-     */
425
-    public function set_order_to_latest()
426
-    {
427
-        $latest_order = $this->get_model()->get_latest_question_order();
428
-        $latest_order++;
429
-        $this->set('QST_order', $latest_order);
430
-    }
431
-
432
-
433
-    /**
434
-     * Retrieves the list of allowed question types from the model.
435
-     *
436
-     * @return string[]
437
-     */
438
-    private function _allowed_question_types()
439
-    {
440
-        $questionModel = $this->get_model();
441
-        /* @var $questionModel EEM_Question */
442
-        return $questionModel->allowed_question_types();
443
-    }
444
-
445
-    /**
446
-     * Duplicates this question and its question options
447
-     *
448
-     * @return \EE_Question
449
-     */
450
-    public function duplicate($options = array())
451
-    {
452
-        $new_question = clone $this;
453
-        $new_question->set('QST_ID', null);
454
-        $new_question->set_display_text(sprintf(__('%s **Duplicate**', 'event_espresso'), $this->display_text()));
455
-        $new_question->set_admin_label(sprintf(__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
456
-        $new_question->set_system_ID(null);
457
-        $new_question->set_wp_user(get_current_user_id());
458
-        // if we're duplicating a trashed question, assume we don't want the new one to be trashed
459
-        $new_question->set_deleted(false);
460
-        $success = $new_question->save();
461
-        if ($success) {
462
-            // we don't totally want to duplicate the question options, because we want them to be for the NEW question
463
-            foreach ($this->options() as $question_option) {
464
-                $question_option->duplicate(array('QST_ID' => $new_question->ID()));
465
-            }
466
-            return $new_question;
467
-        } else {
468
-            return null;
469
-        }
470
-    }
471
-
472
-    /**
473
-     * Returns the question's maximum allowed response size
474
-     *
475
-     * @return int|float
476
-     */
477
-    public function max()
478
-    {
479
-        return $this->get('QST_max');
480
-    }
481
-
482
-    /**
483
-     * Sets the question's maximum allowed response size
484
-     *
485
-     * @param int|float $new_max
486
-     * @return void
487
-     */
488
-    public function set_max($new_max)
489
-    {
490
-        $this->set('QST_max', $new_max);
491
-    }
492
-
493
-
494
-    /**
495
-     * Creates a form input from this question which can be used in HTML forms
496
-     *
497
-     * @param EE_Registration $registration
498
-     * @param EE_Answer       $answer
499
-     * @param array           $input_constructor_args
500
-     * @return EE_Form_Input_Base
501
-     */
502
-    public function generate_form_input($registration = null, $answer = null, $input_constructor_args = array())
503
-    {
504
-        $identifier = $this->is_system_question() ? $this->system_ID() : $this->ID();
505
-
506
-        $input_constructor_args = array_merge(
507
-            array(
508
-                'required'                          => $this->required() ? true : false,
509
-                'html_label_text'                   => $this->display_text(),
510
-                'required_validation_error_message' => $this->required_text(),
511
-            ),
512
-            $input_constructor_args
513
-        );
514
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
515
-            $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
516
-        }
517
-        // has this question been answered ?
518
-        if (
519
-            $answer instanceof EE_Answer
520
-            && $answer->value() !== ''
521
-        ) {
522
-            // answer gets htmlspecialchars called on it, undo that please
523
-            // because the form input's display strategy may call esc_attr too
524
-            // which also does html special characters
525
-            $values_with_html_special_chars = $answer->value();
526
-            if (is_array($values_with_html_special_chars)) {
527
-                $default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
528
-            } else {
529
-                $default_value = htmlspecialchars_decode($values_with_html_special_chars);
530
-            }
531
-            $input_constructor_args['default'] = $default_value;
532
-        }
533
-        $max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
534
-        if (
535
-            in_array(
536
-                $this->type(),
537
-                EEM_Question::instance()->questionTypesWithMaxLength(),
538
-                true
539
-            )
540
-        ) {
541
-            $input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
542
-                null,
543
-                min($max_max_for_question, $this->max())
544
-            );
545
-        }
546
-        $input_constructor_args = apply_filters(
547
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
548
-            $input_constructor_args,
549
-            $registration,
550
-            $this,
551
-            $answer
552
-        );
553
-
554
-        $result = null;
555
-        switch ($this->type()) {
556
-            // Text
557
-            case EEM_Question::QST_type_text:
558
-                $result = new EE_Text_Input($input_constructor_args);
559
-                break;
560
-            // Textarea
561
-            case EEM_Question::QST_type_textarea:
562
-                $result = new EE_Text_Area_Input($input_constructor_args);
563
-                break;
564
-            // Radio Buttons
565
-            case EEM_Question::QST_type_radio:
566
-                $result = new EE_Radio_Button_Input($this->options(), $input_constructor_args);
567
-                break;
568
-            // Dropdown
569
-            case EEM_Question::QST_type_dropdown:
570
-                $result = new EE_Select_Input($this->options(), $input_constructor_args);
571
-                break;
572
-            // State Dropdown
573
-            case EEM_Question::QST_type_state:
574
-                $state_options = apply_filters(
575
-                    'FHEE__EE_Question__generate_form_input__state_options',
576
-                    null,
577
-                    $this,
578
-                    $registration,
579
-                    $answer
580
-                );
581
-                $result = new EE_State_Select_Input($state_options, $input_constructor_args);
582
-                break;
583
-            // Country Dropdown
584
-            case EEM_Question::QST_type_country:
585
-                $country_options = apply_filters(
586
-                    'FHEE__EE_Question__generate_form_input__country_options',
587
-                    null,
588
-                    $this,
589
-                    $registration,
590
-                    $answer
591
-                );
592
-                $result = new EE_Country_Select_Input($country_options, $input_constructor_args);
593
-                break;
594
-            // Checkboxes
595
-            case EEM_Question::QST_type_checkbox:
596
-                $result = new EE_Checkbox_Multi_Input($this->options(), $input_constructor_args);
597
-                break;
598
-            // Date
599
-            case EEM_Question::QST_type_date:
600
-                $result = new EE_Datepicker_Input($input_constructor_args);
601
-                break;
602
-            case EEM_Question::QST_type_html_textarea:
603
-                $input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
604
-                $result = new EE_Text_Area_Input($input_constructor_args);
605
-                $result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
606
-                break;
607
-            case EEM_Question::QST_type_email:
608
-                    $result = new EE_Email_Input($input_constructor_args);
609
-                break;
610
-            // Email confirm
611
-            case EEM_Question::QST_type_email_confirm:
612
-                $result = new EE_Email_Confirm_Input($input_constructor_args);
613
-                break;
614
-            case EEM_Question::QST_type_us_phone:
615
-                $result = new EE_Phone_Input($input_constructor_args);
616
-                break;
617
-            case EEM_Question::QST_type_int:
618
-                $result = new EE_Integer_Input($input_constructor_args);
619
-                break;
620
-            case EEM_Question::QST_type_decimal:
621
-                $result = new EE_Float_Input($input_constructor_args);
622
-                break;
623
-            case EEM_Question::QST_type_url:
624
-                $input_constructor_args['validation_strategies'][] = LoaderFactory::getLoader()->getNew('EE_URL_Validation_Strategy');
625
-                $result = new EE_Text_Input($input_constructor_args);
626
-                break;
627
-            case EEM_Question::QST_type_year:
628
-                $result = new EE_Year_Input(
629
-                    $input_constructor_args,
630
-                    apply_filters(
631
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
632
-                        true,
633
-                        $this
634
-                    ),
635
-                    apply_filters(
636
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
637
-                        100,
638
-                        $this
639
-                    ),
640
-                    apply_filters(
641
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
642
-                        100,
643
-                        $this
644
-                    )
645
-                );
646
-                break;
647
-            case EEM_Question::QST_type_multi_select:
648
-                $result = new EE_Select_Multiple_Input($this->options(), $input_constructor_args);
649
-                break;
650
-            // fallback
651
-            default:
652
-                $default_input = apply_filters(
653
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
654
-                    null,
655
-                    $this->type(),
656
-                    $this,
657
-                    $input_constructor_args
658
-                );
659
-                if (! $default_input) {
660
-                    $default_input = new EE_Text_Input($input_constructor_args);
661
-                }
662
-                $result = $default_input;
663
-        }
664
-        return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
665
-    }
666
-
667
-
668
-    /**
669
-     * Returns whether or not this question type should have question option entries
670
-     *
671
-     * @return bool
672
-     */
673
-    public function should_have_question_options()
674
-    {
675
-        return in_array(
676
-            $this->type(),
677
-            $this->_model->question_types_with_options(),
678
-            true
679
-        );
680
-    }
17
+	/**
18
+	 *
19
+	 * @param array  $props_n_values          incoming values
20
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
21
+	 *                                        used.)
22
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
23
+	 *                                        date_format and the second value is the time format
24
+	 * @return EE_Question
25
+	 */
26
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
27
+	{
28
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
29
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
30
+	}
31
+
32
+
33
+	/**
34
+	 * @param array  $props_n_values  incoming values from the database
35
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
36
+	 *                                the website will be used.
37
+	 * @return EE_Question
38
+	 */
39
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
40
+	{
41
+		return new self($props_n_values, true, $timezone);
42
+	}
43
+
44
+
45
+	/**
46
+	 *        Set    Question display text
47
+	 *
48
+	 * @access        public
49
+	 * @param string $QST_display_text
50
+	 */
51
+	public function set_display_text($QST_display_text = '')
52
+	{
53
+		$this->set('QST_display_text', $QST_display_text);
54
+	}
55
+
56
+
57
+	/**
58
+	 *        Set    Question admin text
59
+	 *
60
+	 * @access        public
61
+	 * @param        string $QST_admin_label
62
+	 */
63
+	public function set_admin_label($QST_admin_label = '')
64
+	{
65
+		$this->set('QST_admin_label', $QST_admin_label);
66
+	}
67
+
68
+
69
+	/**
70
+	 *        Set    system name
71
+	 *
72
+	 * @access        public
73
+	 * @param        mixed $QST_system
74
+	 */
75
+	public function set_system_ID($QST_system = '')
76
+	{
77
+		$this->set('QST_system', $QST_system);
78
+	}
79
+
80
+
81
+	/**
82
+	 *        Set    question's type
83
+	 *
84
+	 * @access        public
85
+	 * @param        string $QST_type
86
+	 */
87
+	public function set_question_type($QST_type = '')
88
+	{
89
+		$this->set('QST_type', $QST_type);
90
+	}
91
+
92
+
93
+	/**
94
+	 *        Sets whether this question must be answered when presented in a form
95
+	 *
96
+	 * @access        public
97
+	 * @param        bool $QST_required
98
+	 */
99
+	public function set_required($QST_required = false)
100
+	{
101
+		$this->set('QST_required', $QST_required);
102
+	}
103
+
104
+
105
+	/**
106
+	 *        Set    Question display text
107
+	 *
108
+	 * @access        public
109
+	 * @param        string $QST_required_text
110
+	 */
111
+	public function set_required_text($QST_required_text = '')
112
+	{
113
+		$this->set('QST_required_text', $QST_required_text);
114
+	}
115
+
116
+
117
+	/**
118
+	 *        Sets the order of this question when placed in a sequence of questions
119
+	 *
120
+	 * @access        public
121
+	 * @param        int $QST_order
122
+	 */
123
+	public function set_order($QST_order = 0)
124
+	{
125
+		$this->set('QST_order', $QST_order);
126
+	}
127
+
128
+
129
+	/**
130
+	 *        Sets whether the question is admin-only
131
+	 *
132
+	 * @access        public
133
+	 * @param        bool $QST_admin_only
134
+	 */
135
+	public function set_admin_only($QST_admin_only = false)
136
+	{
137
+		$this->set('QST_admin_only', $QST_admin_only);
138
+	}
139
+
140
+
141
+	/**
142
+	 *        Sets the wordpress user ID on the question
143
+	 *
144
+	 * @access        public
145
+	 * @param        int $QST_wp_user
146
+	 */
147
+	public function set_wp_user($QST_wp_user = 1)
148
+	{
149
+		$this->set('QST_wp_user', $QST_wp_user);
150
+	}
151
+
152
+
153
+	/**
154
+	 *        Sets whether the question has been deleted
155
+	 *        (we use this boolean instead of actually
156
+	 *        deleting it because when users delete this question
157
+	 *        they really want to remove the question from future
158
+	 *        forms, BUT keep their old answers which depend
159
+	 *        on this record actually existing.
160
+	 *
161
+	 * @access        public
162
+	 * @param    bool $QST_deleted
163
+	 */
164
+	public function set_deleted($QST_deleted = false)
165
+	{
166
+		$this->set('QST_deleted', $QST_deleted);
167
+	}
168
+
169
+
170
+	/**
171
+	 * returns the text for displaying the question to users
172
+	 *
173
+	 * @access public
174
+	 * @return string
175
+	 */
176
+	public function display_text()
177
+	{
178
+		return $this->get('QST_display_text');
179
+	}
180
+
181
+
182
+	/**
183
+	 * returns the text for the administrative label
184
+	 *
185
+	 * @access public
186
+	 * @return string
187
+	 */
188
+	public function admin_label()
189
+	{
190
+		return $this->get('QST_admin_label');
191
+	}
192
+
193
+
194
+	/**
195
+	 * returns the attendee column name for this question
196
+	 *
197
+	 * @access public
198
+	 * @return string
199
+	 */
200
+	public function system_ID()
201
+	{
202
+		return $this->get('QST_system');
203
+	}
204
+
205
+
206
+	/**
207
+	 * returns either a string of 'text', 'textfield', etc.
208
+	 *
209
+	 * @access public
210
+	 * @return boolean
211
+	 */
212
+	public function required()
213
+	{
214
+		return $this->get('QST_required');
215
+	}
216
+
217
+
218
+	/**
219
+	 * returns the text which should be displayed when a user
220
+	 * doesn't answer this question in a form
221
+	 *
222
+	 * @access public
223
+	 * @return string
224
+	 */
225
+	public function required_text()
226
+	{
227
+		return $this->get('QST_required_text');
228
+	}
229
+
230
+
231
+	/**
232
+	 * returns the type of this question
233
+	 *
234
+	 * @access public
235
+	 * @return string
236
+	 */
237
+	public function type()
238
+	{
239
+		return $this->get('QST_type');
240
+	}
241
+
242
+
243
+	/**
244
+	 * returns an integer showing where this question should
245
+	 * be placed in a sequence of questions
246
+	 *
247
+	 * @access public
248
+	 * @return int
249
+	 */
250
+	public function order()
251
+	{
252
+		return $this->get('QST_order');
253
+	}
254
+
255
+
256
+	/**
257
+	 * returns whether this question should only appears to admins,
258
+	 * or to everyone
259
+	 *
260
+	 * @access public
261
+	 * @return boolean
262
+	 */
263
+	public function admin_only()
264
+	{
265
+		return $this->get('QST_admin_only');
266
+	}
267
+
268
+
269
+	/**
270
+	 * returns the id the wordpress user who created this question
271
+	 *
272
+	 * @access public
273
+	 * @return int
274
+	 */
275
+	public function wp_user()
276
+	{
277
+		return $this->get('QST_wp_user');
278
+	}
279
+
280
+
281
+	/**
282
+	 * returns whether this question has been marked as 'deleted'
283
+	 *
284
+	 * @access public
285
+	 * @return boolean
286
+	 */
287
+	public function deleted()
288
+	{
289
+		return $this->get('QST_deleted');
290
+	}
291
+
292
+
293
+	/**
294
+	 * Gets an array of related EE_Answer  to this EE_Question
295
+	 *
296
+	 * @return EE_Answer[]
297
+	 */
298
+	public function answers()
299
+	{
300
+		return $this->get_many_related('Answer');
301
+	}
302
+
303
+
304
+	/**
305
+	 * Boolean check for if there are answers on this question in th db
306
+	 *
307
+	 * @return boolean true = has answers, false = no answers.
308
+	 */
309
+	public function has_answers()
310
+	{
311
+		return $this->count_related('Answer') > 0 ? true : false;
312
+	}
313
+
314
+
315
+	/**
316
+	 * gets an array of EE_Question_Group which relate to this question
317
+	 *
318
+	 * @return EE_Question_Group[]
319
+	 */
320
+	public function question_groups()
321
+	{
322
+		return $this->get_many_related('Question_Group');
323
+	}
324
+
325
+
326
+	/**
327
+	 * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
328
+	 *
329
+	 * @param boolean      $notDeletedOptionsOnly            1
330
+	 *                                                       whether to return ALL options, or only the ones which have
331
+	 *                                                       not yet been deleleted
332
+	 * @param string|array $selected_value_to_always_include , when retrieving options to an ANSWERED question,
333
+	 *                                                       we want to usually only show non-deleted options AND the
334
+	 *                                                       value that was selected for the answer, whether it was
335
+	 *                                                       trashed or not.
336
+	 * @return EE_Question_Option[]
337
+	 */
338
+	public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
339
+	{
340
+		if (! $this->ID()) {
341
+			return array();
342
+		}
343
+		$query_params = array();
344
+		if ($selected_value_to_always_include) {
345
+			if (is_array($selected_value_to_always_include)) {
346
+				$query_params[0]['OR*options-query']['QSO_value'] = array('IN', $selected_value_to_always_include);
347
+			} else {
348
+				$query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
349
+			}
350
+		}
351
+		if ($notDeletedOptionsOnly) {
352
+			$query_params[0]['OR*options-query']['QSO_deleted'] = false;
353
+		}
354
+		// order by QSO_order
355
+		$query_params['order_by'] = array('QSO_order' => 'ASC');
356
+		return $this->get_many_related('Question_Option', $query_params);
357
+	}
358
+
359
+
360
+	/**
361
+	 * returns an array of EE_Question_Options which relate to this question
362
+	 *
363
+	 * @return \EE_Question_Option[]
364
+	 */
365
+	public function temp_options()
366
+	{
367
+		return $this->_model_relations['Question_Option'];
368
+	}
369
+
370
+
371
+	/**
372
+	 * Adds an option for this question. Note: if the option were previously associated with a different
373
+	 * Question, that relationship will be overwritten.
374
+	 *
375
+	 * @param EE_Question_Option $option
376
+	 * @return boolean success
377
+	 */
378
+	public function add_option(EE_Question_Option $option)
379
+	{
380
+		return $this->_add_relation_to($option, 'Question_Option');
381
+	}
382
+
383
+
384
+	/**
385
+	 * Adds an option directly to this question without saving to the db
386
+	 *
387
+	 * @param EE_Question_Option $option
388
+	 * @return boolean success
389
+	 */
390
+	public function add_temp_option(EE_Question_Option $option)
391
+	{
392
+		$this->_model_relations['Question_Option'][] = $option;
393
+		return true;
394
+	}
395
+
396
+
397
+	/**
398
+	 * Marks the option as deleted.
399
+	 *
400
+	 * @param EE_Question_Option $option
401
+	 * @return boolean success
402
+	 */
403
+	public function remove_option(EE_Question_Option $option)
404
+	{
405
+		return $this->_remove_relation_to($option, 'Question_Option');
406
+	}
407
+
408
+
409
+	/**
410
+	 * @return bool
411
+	 */
412
+	public function is_system_question()
413
+	{
414
+		$system_ID = $this->get('QST_system');
415
+		return ! empty($system_ID) ? true : false;
416
+	}
417
+
418
+
419
+	/**
420
+	 * The purpose of this method is set the question order this question order to be the max out of all questions
421
+	 *
422
+	 * @access public
423
+	 * @return void
424
+	 */
425
+	public function set_order_to_latest()
426
+	{
427
+		$latest_order = $this->get_model()->get_latest_question_order();
428
+		$latest_order++;
429
+		$this->set('QST_order', $latest_order);
430
+	}
431
+
432
+
433
+	/**
434
+	 * Retrieves the list of allowed question types from the model.
435
+	 *
436
+	 * @return string[]
437
+	 */
438
+	private function _allowed_question_types()
439
+	{
440
+		$questionModel = $this->get_model();
441
+		/* @var $questionModel EEM_Question */
442
+		return $questionModel->allowed_question_types();
443
+	}
444
+
445
+	/**
446
+	 * Duplicates this question and its question options
447
+	 *
448
+	 * @return \EE_Question
449
+	 */
450
+	public function duplicate($options = array())
451
+	{
452
+		$new_question = clone $this;
453
+		$new_question->set('QST_ID', null);
454
+		$new_question->set_display_text(sprintf(__('%s **Duplicate**', 'event_espresso'), $this->display_text()));
455
+		$new_question->set_admin_label(sprintf(__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
456
+		$new_question->set_system_ID(null);
457
+		$new_question->set_wp_user(get_current_user_id());
458
+		// if we're duplicating a trashed question, assume we don't want the new one to be trashed
459
+		$new_question->set_deleted(false);
460
+		$success = $new_question->save();
461
+		if ($success) {
462
+			// we don't totally want to duplicate the question options, because we want them to be for the NEW question
463
+			foreach ($this->options() as $question_option) {
464
+				$question_option->duplicate(array('QST_ID' => $new_question->ID()));
465
+			}
466
+			return $new_question;
467
+		} else {
468
+			return null;
469
+		}
470
+	}
471
+
472
+	/**
473
+	 * Returns the question's maximum allowed response size
474
+	 *
475
+	 * @return int|float
476
+	 */
477
+	public function max()
478
+	{
479
+		return $this->get('QST_max');
480
+	}
481
+
482
+	/**
483
+	 * Sets the question's maximum allowed response size
484
+	 *
485
+	 * @param int|float $new_max
486
+	 * @return void
487
+	 */
488
+	public function set_max($new_max)
489
+	{
490
+		$this->set('QST_max', $new_max);
491
+	}
492
+
493
+
494
+	/**
495
+	 * Creates a form input from this question which can be used in HTML forms
496
+	 *
497
+	 * @param EE_Registration $registration
498
+	 * @param EE_Answer       $answer
499
+	 * @param array           $input_constructor_args
500
+	 * @return EE_Form_Input_Base
501
+	 */
502
+	public function generate_form_input($registration = null, $answer = null, $input_constructor_args = array())
503
+	{
504
+		$identifier = $this->is_system_question() ? $this->system_ID() : $this->ID();
505
+
506
+		$input_constructor_args = array_merge(
507
+			array(
508
+				'required'                          => $this->required() ? true : false,
509
+				'html_label_text'                   => $this->display_text(),
510
+				'required_validation_error_message' => $this->required_text(),
511
+			),
512
+			$input_constructor_args
513
+		);
514
+		if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
515
+			$answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
516
+		}
517
+		// has this question been answered ?
518
+		if (
519
+			$answer instanceof EE_Answer
520
+			&& $answer->value() !== ''
521
+		) {
522
+			// answer gets htmlspecialchars called on it, undo that please
523
+			// because the form input's display strategy may call esc_attr too
524
+			// which also does html special characters
525
+			$values_with_html_special_chars = $answer->value();
526
+			if (is_array($values_with_html_special_chars)) {
527
+				$default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
528
+			} else {
529
+				$default_value = htmlspecialchars_decode($values_with_html_special_chars);
530
+			}
531
+			$input_constructor_args['default'] = $default_value;
532
+		}
533
+		$max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
534
+		if (
535
+			in_array(
536
+				$this->type(),
537
+				EEM_Question::instance()->questionTypesWithMaxLength(),
538
+				true
539
+			)
540
+		) {
541
+			$input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
542
+				null,
543
+				min($max_max_for_question, $this->max())
544
+			);
545
+		}
546
+		$input_constructor_args = apply_filters(
547
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
548
+			$input_constructor_args,
549
+			$registration,
550
+			$this,
551
+			$answer
552
+		);
553
+
554
+		$result = null;
555
+		switch ($this->type()) {
556
+			// Text
557
+			case EEM_Question::QST_type_text:
558
+				$result = new EE_Text_Input($input_constructor_args);
559
+				break;
560
+			// Textarea
561
+			case EEM_Question::QST_type_textarea:
562
+				$result = new EE_Text_Area_Input($input_constructor_args);
563
+				break;
564
+			// Radio Buttons
565
+			case EEM_Question::QST_type_radio:
566
+				$result = new EE_Radio_Button_Input($this->options(), $input_constructor_args);
567
+				break;
568
+			// Dropdown
569
+			case EEM_Question::QST_type_dropdown:
570
+				$result = new EE_Select_Input($this->options(), $input_constructor_args);
571
+				break;
572
+			// State Dropdown
573
+			case EEM_Question::QST_type_state:
574
+				$state_options = apply_filters(
575
+					'FHEE__EE_Question__generate_form_input__state_options',
576
+					null,
577
+					$this,
578
+					$registration,
579
+					$answer
580
+				);
581
+				$result = new EE_State_Select_Input($state_options, $input_constructor_args);
582
+				break;
583
+			// Country Dropdown
584
+			case EEM_Question::QST_type_country:
585
+				$country_options = apply_filters(
586
+					'FHEE__EE_Question__generate_form_input__country_options',
587
+					null,
588
+					$this,
589
+					$registration,
590
+					$answer
591
+				);
592
+				$result = new EE_Country_Select_Input($country_options, $input_constructor_args);
593
+				break;
594
+			// Checkboxes
595
+			case EEM_Question::QST_type_checkbox:
596
+				$result = new EE_Checkbox_Multi_Input($this->options(), $input_constructor_args);
597
+				break;
598
+			// Date
599
+			case EEM_Question::QST_type_date:
600
+				$result = new EE_Datepicker_Input($input_constructor_args);
601
+				break;
602
+			case EEM_Question::QST_type_html_textarea:
603
+				$input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
604
+				$result = new EE_Text_Area_Input($input_constructor_args);
605
+				$result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
606
+				break;
607
+			case EEM_Question::QST_type_email:
608
+					$result = new EE_Email_Input($input_constructor_args);
609
+				break;
610
+			// Email confirm
611
+			case EEM_Question::QST_type_email_confirm:
612
+				$result = new EE_Email_Confirm_Input($input_constructor_args);
613
+				break;
614
+			case EEM_Question::QST_type_us_phone:
615
+				$result = new EE_Phone_Input($input_constructor_args);
616
+				break;
617
+			case EEM_Question::QST_type_int:
618
+				$result = new EE_Integer_Input($input_constructor_args);
619
+				break;
620
+			case EEM_Question::QST_type_decimal:
621
+				$result = new EE_Float_Input($input_constructor_args);
622
+				break;
623
+			case EEM_Question::QST_type_url:
624
+				$input_constructor_args['validation_strategies'][] = LoaderFactory::getLoader()->getNew('EE_URL_Validation_Strategy');
625
+				$result = new EE_Text_Input($input_constructor_args);
626
+				break;
627
+			case EEM_Question::QST_type_year:
628
+				$result = new EE_Year_Input(
629
+					$input_constructor_args,
630
+					apply_filters(
631
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
632
+						true,
633
+						$this
634
+					),
635
+					apply_filters(
636
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
637
+						100,
638
+						$this
639
+					),
640
+					apply_filters(
641
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
642
+						100,
643
+						$this
644
+					)
645
+				);
646
+				break;
647
+			case EEM_Question::QST_type_multi_select:
648
+				$result = new EE_Select_Multiple_Input($this->options(), $input_constructor_args);
649
+				break;
650
+			// fallback
651
+			default:
652
+				$default_input = apply_filters(
653
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
654
+					null,
655
+					$this->type(),
656
+					$this,
657
+					$input_constructor_args
658
+				);
659
+				if (! $default_input) {
660
+					$default_input = new EE_Text_Input($input_constructor_args);
661
+				}
662
+				$result = $default_input;
663
+		}
664
+		return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
665
+	}
666
+
667
+
668
+	/**
669
+	 * Returns whether or not this question type should have question option entries
670
+	 *
671
+	 * @return bool
672
+	 */
673
+	public function should_have_question_options()
674
+	{
675
+		return in_array(
676
+			$this->type(),
677
+			$this->_model->question_types_with_options(),
678
+			true
679
+		);
680
+	}
681 681
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Term_Relationship.class.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -10,23 +10,23 @@
 block discarded – undo
10 10
 class EE_Term_Relationship extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Term_Relationship
16
-     */
17
-    public static function new_instance($props_n_values = array())
18
-    {
19
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
-        return $has_object ? $has_object : new self($props_n_values);
21
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Term_Relationship
16
+	 */
17
+	public static function new_instance($props_n_values = array())
18
+	{
19
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
+		return $has_object ? $has_object : new self($props_n_values);
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * @param array $props_n_values
26
-     * @return EE_Term_Relationship
27
-     */
28
-    public static function new_instance_from_db($props_n_values = array())
29
-    {
30
-        return new self($props_n_values, true);
31
-    }
24
+	/**
25
+	 * @param array $props_n_values
26
+	 * @return EE_Term_Relationship
27
+	 */
28
+	public static function new_instance_from_db($props_n_values = array())
29
+	{
30
+		return new self($props_n_values, true);
31
+	}
32 32
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Export.class.php 2 patches
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
     {
45 45
         $this->_req_data = $request_data;
46 46
         $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
47
+        require_once(EE_CLASSES.'EE_CSV.class.php');
48 48
         $this->EE_CSV = EE_CSV::instance();
49 49
     }
50 50
 
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
                 $value_to_equal = $EVT_ID;
168 168
                 $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169 169
 
170
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
170
+                $filename = 'event-'.($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171 171
             }
172 172
             $event_query_params[0]['EVT_ID'] = $value_to_equal;
173 173
             $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
         $filename = $this->generate_filename($filename);
218 218
 
219
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
219
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220 220
             EE_Error::add_error(
221 221
                 __(
222 222
                     "'An error occurred and the Event details could not be exported from the database.'",
@@ -243,16 +243,16 @@  discard block
 block discarded – undo
243 243
             foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244 244
                 if ($field_name == 'STA_ID') {
245 245
                     $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
-                    ) ];
246
+                    $csv_row[__('State', 'event_espresso')] = $attendee_row[$state_name_field->get_qualified_column(
247
+                    )];
248 248
                 } elseif ($field_name == 'CNT_ISO') {
249 249
                     $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
-                    $csv_row[ __(
250
+                    $csv_row[__(
251 251
                         'Country',
252 252
                         'event_espresso'
253
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
253
+                    )] = $attendee_row[$country_name_field->get_qualified_column()];
254 254
                 } else {
255
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
255
+                    $csv_row[$field_obj->get_nicename()] = $attendee_row[$field_obj->get_qualified_column()];
256 256
                 }
257 257
             }
258 258
             $csv_data[] = $csv_row;
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         $model_data = $this->_get_export_data_for_models($models_to_export);
292 292
         $filename = $this->generate_filename('all-attendees');
293 293
 
294
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
294
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295 295
             EE_Error::add_error(
296 296
                 __(
297 297
                     'An error occurred and the Attendee data could not be exported from the database.',
@@ -409,9 +409,9 @@  discard block
 block discarded – undo
409 409
         foreach ($registration_rows as $reg_row) {
410 410
             if (is_array($reg_row)) {
411 411
                 $reg_csv_array = array();
412
-                if (! $event_id) {
412
+                if ( ! $event_id) {
413 413
                     // get the event's name and Id
414
-                    $reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
414
+                    $reg_csv_array[__('Event', 'event_espresso')] = sprintf(
415 415
                         __('%1$s (%2$s)', 'event_espresso'),
416 416
                         $this->_prepare_value_from_db_for_display(
417 417
                             EEM_Event::instance(),
@@ -457,13 +457,13 @@  discard block
 block discarded – undo
457 457
                         $value = $this->_prepare_value_from_db_for_display(
458 458
                             $reg_model,
459 459
                             $field_name,
460
-                            $reg_row[ $field->get_qualified_column() ]
460
+                            $reg_row[$field->get_qualified_column()]
461 461
                         );
462 462
                     }
463
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
463
+                    $reg_csv_array[$this->_get_column_name_for_field($field)] = $value;
464 464
                     if ($field_name == 'REG_final_price') {
465 465
                         // add a column named Currency after the final price
466
-                        $reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
466
+                        $reg_csv_array[__("Currency", "event_espresso")] = EE_Config::instance()->currency->code;
467 467
                     }
468 468
                 }
469 469
                 // get pretty status
@@ -475,23 +475,23 @@  discard block
 block discarded – undo
475 475
                     false,
476 476
                     'sentence'
477 477
                 );
478
-                $reg_csv_array[ __(
478
+                $reg_csv_array[__(
479 479
                     "Registration Status",
480 480
                     'event_espresso'
481
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
481
+                )] = $stati[$reg_row['Registration.STS_ID']];
482 482
                 // get pretty trnasaction status
483
-                $reg_csv_array[ __(
483
+                $reg_csv_array[__(
484 484
                     "Transaction Status",
485 485
                     'event_espresso'
486
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
-                $reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
486
+                )] = $stati[$reg_row['TransactionTable.STS_ID']];
487
+                $reg_csv_array[__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
488 488
                     ? $this->_prepare_value_from_db_for_display(
489 489
                         EEM_Transaction::instance(),
490 490
                         'TXN_total',
491 491
                         $reg_row['TransactionTable.TXN_total'],
492 492
                         'localized_float'
493 493
                     ) : '0.00';
494
-                $reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
494
+                $reg_csv_array[__('Amount Paid', 'event_espresso')] = $is_primary_reg
495 495
                     ? $this->_prepare_value_from_db_for_display(
496 496
                         EEM_Transaction::instance(),
497 497
                         'TXN_paid',
@@ -523,15 +523,15 @@  discard block
 block discarded – undo
523 523
                             ? $payment_method_and_gateway_txn_id['payment_time'] : '';
524 524
                     }
525 525
                 }
526
-                $reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
-                $reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
-                $reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
526
+                $reg_csv_array[__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
527
+                $reg_csv_array[__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
528
+                $reg_csv_array[__('Gateway Transaction ID(s)', 'event_espresso')] = implode(
529 529
                     ',',
530 530
                     $gateway_txn_ids_etc
531 531
                 );
532 532
 
533 533
                 // get whether or not the user has checked in
534
-                $reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
534
+                $reg_csv_array[__("Check-Ins", "event_espresso")] = $reg_model->count_related(
535 535
                     $reg_row['Registration.REG_ID'],
536 536
                     'Checkin'
537 537
                 );
@@ -561,8 +561,8 @@  discard block
 block discarded – undo
561 561
                     $ticket_name = __('Unknown', 'event_espresso');
562 562
                     $datetimes_strings = array(__('Unknown', 'event_espresso'));
563 563
                 }
564
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
565
-                $reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
564
+                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
565
+                $reg_csv_array[__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
566 566
                 // get datetime(s) of registration
567 567
 
568 568
                 // add attendee columns
@@ -583,20 +583,20 @@  discard block
 block discarded – undo
583 583
                             $value = $this->_prepare_value_from_db_for_display(
584 584
                                 EEM_Attendee::instance(),
585 585
                                 $att_field_name,
586
-                                $reg_row[ $field_obj->get_qualified_column() ]
586
+                                $reg_row[$field_obj->get_qualified_column()]
587 587
                             );
588 588
                         }
589 589
                     } else {
590 590
                         $value = '';
591 591
                     }
592 592
 
593
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
593
+                    $reg_csv_array[$this->_get_column_name_for_field($field_obj)] = $value;
594 594
                 }
595 595
 
596 596
                 // make sure each registration has the same questions in the same order
597 597
                 foreach ($questions_for_these_regs_rows as $question_row) {
598
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
599
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
598
+                    if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
599
+                        $reg_csv_array[$question_row['Question.QST_admin_label']] = null;
600 600
                     }
601 601
                 }
602 602
                 // now fill out the questions THEY answered
@@ -614,11 +614,11 @@  discard block
 block discarded – undo
614 614
                         $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615 615
                     }
616 616
                     if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
617
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
617
+                        $reg_csv_array[$question_label] = EEM_State::instance()->get_state_name_by_ID(
618 618
                             $answer_row['Answer.ANS_value']
619 619
                         );
620 620
                     } else {
621
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
621
+                        $reg_csv_array[$question_label] = $this->_prepare_value_from_db_for_display(
622 622
                             EEM_Answer::instance(),
623 623
                             'ANS_value',
624 624
                             $answer_row['Answer.ANS_value']
@@ -644,16 +644,16 @@  discard block
 block discarded – undo
644 644
                 $model = EE_Registry::instance()->load_model($model_name);
645 645
                 foreach ($field_list as $field_name) {
646 646
                     $field = $model->field_settings_for($field_name);
647
-                    $reg_csv_array[ $this->_get_column_name_for_field(
647
+                    $reg_csv_array[$this->_get_column_name_for_field(
648 648
                         $field
649
-                    ) ] = null;// $registration->get($field->get_name());
649
+                    )] = null; // $registration->get($field->get_name());
650 650
                 }
651 651
             }
652 652
             $registrations_csv_ready_array [] = $reg_csv_array;
653 653
         }
654 654
         if ($event_id) {
655 655
             $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
-            if (! $event_slug) {
656
+            if ( ! $event_slug) {
657 657
                 $event_slug = __('unknown', 'event_espresso');
658 658
             }
659 659
         } else {
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
      */
675 675
     protected function _get_column_name_for_field(EE_Model_Field_Base $field)
676 676
     {
677
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
677
+        return $field->get_nicename()."[".$field->get_name()."]";
678 678
     }
679 679
 
680 680
 
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
             } else {
698 698
                 // generate regular where = clause
699 699
                 $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
-                $filename = 'event-category#' . $EVT_CAT_ID;
700
+                $filename = 'event-category#'.$EVT_CAT_ID;
701 701
                 $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702 702
             }
703 703
         } else {
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
         $table_data = $this->_get_export_data_for_models($tables_to_export);
713 713
         $filename = $this->generate_filename($filename);
714 714
 
715
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
715
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716 716
             EE_Error::add_error(
717 717
                 __(
718 718
                     'An error occurred and the Category details could not be exported from the database.',
@@ -735,8 +735,8 @@  discard block
 block discarded – undo
735 735
     private function generate_filename($export_name = '')
736 736
     {
737 737
         if ($export_name != '') {
738
-            $filename = get_bloginfo('name') . '-' . $export_name;
739
-            $filename = sanitize_key($filename) . '-' . $this->today;
738
+            $filename = get_bloginfo('name').'-'.$export_name;
739
+            $filename = sanitize_key($filename).'-'.$this->today;
740 740
             return $filename;
741 741
         } else {
742 742
             EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
@@ -765,25 +765,25 @@  discard block
 block discarded – undo
765 765
                 $model = EE_Registry::instance()->load_model($model_name);
766 766
                 $model_objects = $model->get_all($query_params);
767 767
 
768
-                $table_data[ $model_name ] = array();
768
+                $table_data[$model_name] = array();
769 769
                 foreach ($model_objects as $model_object) {
770 770
                     $model_data_array = array();
771 771
                     $fields = $model->field_settings();
772 772
                     foreach ($fields as $field) {
773
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
773
+                        $column_name = $field->get_nicename()."[".$field->get_name()."]";
774 774
                         if ($field instanceof EE_Datetime_Field) {
775 775
                             // $field->set_date_format('Y-m-d');
776 776
                             // $field->set_time_format('H:i:s');
777
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
777
+                            $model_data_array[$column_name] = $model_object->get_datetime(
778 778
                                 $field->get_name(),
779 779
                                 'Y-m-d',
780 780
                                 'H:i:s'
781 781
                             );
782 782
                         } else {
783
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
783
+                            $model_data_array[$column_name] = $model_object->get($field->get_name());
784 784
                         }
785 785
                     }
786
-                    $table_data[ $model_name ][] = $model_data_array;
786
+                    $table_data[$model_name][] = $model_data_array;
787 787
                 }
788 788
             }
789 789
         }
Please login to merge, or discard this patch.
Indentation   +777 added lines, -777 removed lines patch added patch discarded remove patch
@@ -16,781 +16,781 @@
 block discarded – undo
16 16
 class EE_Export
17 17
 {
18 18
 
19
-    const option_prefix = 'ee_report_job_';
20
-
21
-
22
-    // instance of the EE_Export object
23
-    private static $_instance = null;
24
-
25
-    // instance of the EE_CSV object
26
-    /**
27
-     *
28
-     * @var EE_CSV
29
-     */
30
-    public $EE_CSV = null;
31
-
32
-
33
-    private $_req_data = array();
34
-
35
-
36
-    /**
37
-     *        private constructor to prevent direct creation
38
-     *
39
-     * @Constructor
40
-     * @access private
41
-     * @param array $request_data
42
-     */
43
-    private function __construct($request_data = array())
44
-    {
45
-        $this->_req_data = $request_data;
46
-        $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
48
-        $this->EE_CSV = EE_CSV::instance();
49
-    }
50
-
51
-
52
-    /**
53
-     *        @ singleton method used to instantiate class object
54
-     *        @ access public
55
-     *
56
-     * @param array $request_data
57
-     * @return \EE_Export
58
-     */
59
-    public static function instance($request_data = array())
60
-    {
61
-        // check if class object is instantiated
62
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
63
-            self::$_instance = new self($request_data);
64
-        }
65
-        return self::$_instance;
66
-    }
67
-
68
-
69
-    /**
70
-     * @Export Event Espresso data - routes export requests
71
-     * @access public
72
-     * @return void | bool
73
-     */
74
-    public function export()
75
-    {
76
-        // in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
77
-        if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
78
-            // check if action2 has export action
79
-            if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
80
-                // whoop! there it is!
81
-                $this->_req_data['action'] = $this->_req_data['action2'];
82
-            }
83
-        }
84
-
85
-        $this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
86
-
87
-        switch ($this->_req_data['export']) {
88
-            case 'report':
89
-                switch ($this->_req_data['action']) {
90
-                    case "event":
91
-                    case "export_events":
92
-                    case 'all_event_data':
93
-                        $this->export_all_event_data();
94
-                        break;
95
-
96
-                    case 'registrations_report_for_event':
97
-                        $this->report_registrations_for_event($this->_req_data['EVT_ID']);
98
-                        break;
99
-
100
-                    case 'attendees':
101
-                        $this->export_attendees();
102
-                        break;
103
-
104
-                    case 'categories':
105
-                        $this->export_categories();
106
-                        break;
107
-
108
-                    default:
109
-                        EE_Error::add_error(
110
-                            __('An error occurred! The requested export report could not be found.', 'event_espresso'),
111
-                            __FILE__,
112
-                            __FUNCTION__,
113
-                            __LINE__
114
-                        );
115
-                        return false;
116
-                        break;
117
-                }
118
-                break; // end of switch export : report
119
-            default:
120
-                break;
121
-        } // end of switch export
122
-
123
-        exit;
124
-    }
125
-
126
-    /**
127
-     * Downloads a CSV file with all the columns, but no data. This should be used for importing
128
-     *
129
-     * @return null kills execution
130
-     */
131
-    public function export_sample()
132
-    {
133
-        $event = EEM_Event::instance()->get_one();
134
-        $this->_req_data['EVT_ID'] = $event->ID();
135
-        $this->export_all_event_data();
136
-    }
137
-
138
-
139
-    /**
140
-     * @Export data for ALL events
141
-     * @access public
142
-     * @return void
143
-     */
144
-    public function export_all_event_data()
145
-    {
146
-        // are any Event IDs set?
147
-        $event_query_params = array();
148
-        $related_models_query_params = array();
149
-        $related_through_reg_query_params = array();
150
-        $datetime_ticket_query_params = array();
151
-        $price_query_params = array();
152
-        $price_type_query_params = array();
153
-        $term_query_params = array();
154
-        $state_country_query_params = array();
155
-        $question_group_query_params = array();
156
-        $question_query_params = array();
157
-        if (isset($this->_req_data['EVT_ID'])) {
158
-            // do we have an array of IDs ?
159
-
160
-            if (is_array($this->_req_data['EVT_ID'])) {
161
-                $EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
162
-                $value_to_equal = array('IN', $EVT_IDs);
163
-                $filename = 'events';
164
-            } else {
165
-                // generate regular where = clause
166
-                $EVT_ID = absint($this->_req_data['EVT_ID']);
167
-                $value_to_equal = $EVT_ID;
168
-                $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169
-
170
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171
-            }
172
-            $event_query_params[0]['EVT_ID'] = $value_to_equal;
173
-            $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
174
-            $related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
175
-            $datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
176
-            $price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
177
-            $price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
-            $term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
179
-            $state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
180
-            $question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
181
-            $question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
182
-        } else {
183
-            $filename = 'all-events';
184
-        }
185
-
186
-
187
-        // array in the format:  table name =>  query where clause
188
-        $models_to_export = array(
189
-            'Event'                   => $event_query_params,
190
-            'Datetime'                => $related_models_query_params,
191
-            'Ticket_Template'         => $price_query_params,
192
-            'Ticket'                  => $datetime_ticket_query_params,
193
-            'Datetime_Ticket'         => $datetime_ticket_query_params,
194
-            'Price_Type'              => $price_type_query_params,
195
-            'Price'                   => $price_query_params,
196
-            'Ticket_Price'            => $price_query_params,
197
-            'Term'                    => $term_query_params,
198
-            'Term_Taxonomy'           => $related_models_query_params,
199
-            'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
200
-            'Country'                 => $state_country_query_params,
201
-            'State'                   => $state_country_query_params,
202
-            'Venue'                   => $related_models_query_params,
203
-            'Event_Venue'             => $related_models_query_params,
204
-            'Question_Group'          => $question_group_query_params,
205
-            'Event_Question_Group'    => $question_group_query_params,
206
-            'Question'                => $question_query_params,
207
-            'Question_Group_Question' => $question_query_params,
208
-            // 'Transaction'=>$related_through_reg_query_params,
209
-            // 'Registration'=>$related_models_query_params,
210
-            // 'Attendee'=>$related_through_reg_query_params,
211
-            // 'Line_Item'=>
212
-
213
-        );
214
-
215
-        $model_data = $this->_get_export_data_for_models($models_to_export);
216
-
217
-        $filename = $this->generate_filename($filename);
218
-
219
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220
-            EE_Error::add_error(
221
-                __(
222
-                    "'An error occurred and the Event details could not be exported from the database.'",
223
-                    "event_espresso"
224
-                ),
225
-                __FILE__,
226
-                __FUNCTION__,
227
-                __LINE__
228
-            );
229
-        }
230
-    }
231
-
232
-    public function report_attendees()
233
-    {
234
-        $attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
235
-            array(
236
-                'force_join' => array('State', 'Country'),
237
-                'caps'       => EEM_Base::caps_read_admin,
238
-            )
239
-        );
240
-        $csv_data = array();
241
-        foreach ($attendee_rows as $attendee_row) {
242
-            $csv_row = array();
243
-            foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244
-                if ($field_name == 'STA_ID') {
245
-                    $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
-                    $csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
-                    ) ];
248
-                } elseif ($field_name == 'CNT_ISO') {
249
-                    $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
-                    $csv_row[ __(
251
-                        'Country',
252
-                        'event_espresso'
253
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
254
-                } else {
255
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
256
-                }
257
-            }
258
-            $csv_data[] = $csv_row;
259
-        }
260
-
261
-        $filename = $this->generate_filename('contact-list-report');
262
-
263
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
264
-        $this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
265
-        $this->EE_CSV->end_sending_csv($handle);
266
-    }
267
-
268
-
269
-    /**
270
-     * @Export data for ALL attendees
271
-     * @access public
272
-     * @return void
273
-     */
274
-    public function export_attendees()
275
-    {
276
-
277
-        $states_that_have_an_attendee = EEM_State::instance()->get_all(
278
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
279
-        );
280
-        $countries_that_have_an_attendee = EEM_Country::instance()->get_all(
281
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
282
-        );
283
-        // $states_to_export_query_params
284
-        $models_to_export = array(
285
-            'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
286
-            'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
287
-            'Attendee' => array(),
288
-        );
289
-
290
-
291
-        $model_data = $this->_get_export_data_for_models($models_to_export);
292
-        $filename = $this->generate_filename('all-attendees');
293
-
294
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295
-            EE_Error::add_error(
296
-                __(
297
-                    'An error occurred and the Attendee data could not be exported from the database.',
298
-                    'event_espresso'
299
-                ),
300
-                __FILE__,
301
-                __FUNCTION__,
302
-                __LINE__
303
-            );
304
-        }
305
-    }
306
-
307
-    /**
308
-     * Shortcut for preparing a database result for display
309
-     *
310
-     * @param EEM_Base       $model
311
-     * @param string         $field_name
312
-     * @param string         $raw_db_value
313
-     * @param boolean|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
314
-     *                                      NOT display pretty
315
-     * @return string
316
-     */
317
-    protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
318
-    {
319
-        $field_obj = $model->field_settings_for($field_name);
320
-        $value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
321
-        if ($field_obj instanceof EE_Datetime_Field) {
322
-            $field_obj->set_date_format(
323
-                EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
324
-                $pretty_schema
325
-            );
326
-            $field_obj->set_time_format(
327
-                EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
328
-                $pretty_schema
329
-            );
330
-        }
331
-        if ($pretty_schema === true) {
332
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
333
-        } elseif (is_string($pretty_schema)) {
334
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
335
-        } else {
336
-            return $field_obj->prepare_for_get($value_on_model_obj);
337
-        }
338
-    }
339
-
340
-    /**
341
-     * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
342
-     * name, and the questions associated with the registrations
343
-     *
344
-     * @param int $event_id
345
-     */
346
-    public function report_registrations_for_event($event_id = null)
347
-    {
348
-        $reg_fields_to_include = array(
349
-            'TXN_ID',
350
-            'ATT_ID',
351
-            'REG_ID',
352
-            'REG_date',
353
-            'REG_code',
354
-            'REG_count',
355
-            'REG_final_price',
356
-
357
-        );
358
-        $att_fields_to_include = array(
359
-            'ATT_fname',
360
-            'ATT_lname',
361
-            'ATT_email',
362
-            'ATT_address',
363
-            'ATT_address2',
364
-            'ATT_city',
365
-            'STA_ID',
366
-            'CNT_ISO',
367
-            'ATT_zip',
368
-            'ATT_phone',
369
-        );
370
-
371
-        $registrations_csv_ready_array = array();
372
-        $reg_model = EE_Registry::instance()->load_model('Registration');
373
-        $query_params = apply_filters(
374
-            'FHEE__EE_Export__report_registration_for_event',
375
-            array(
376
-                array(
377
-                    'OR'                 => array(
378
-                        // don't include registrations from failed or abandoned transactions...
379
-                        'Transaction.STS_ID' => array(
380
-                            'NOT IN',
381
-                            array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
382
-                        ),
383
-                        // unless the registration is approved, in which case include it regardless of transaction status
384
-                        'STS_ID'             => EEM_Registration::status_id_approved,
385
-                    ),
386
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
387
-                ),
388
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
389
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
390
-                'caps'       => EEM_Base::caps_read_admin,
391
-            ),
392
-            $event_id
393
-        );
394
-        if ($event_id) {
395
-            $query_params[0]['EVT_ID'] = $event_id;
396
-        } else {
397
-            $query_params['force_join'][] = 'Event';
398
-        }
399
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
400
-        // get all questions which relate to someone in this group
401
-        $registration_ids = array();
402
-        foreach ($registration_rows as $reg_row) {
403
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
404
-        }
405
-        // EEM_Question::instance()->show_next_x_db_queries();
406
-        $questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
407
-            array(array('Answer.REG_ID' => array('IN', $registration_ids)))
408
-        );
409
-        foreach ($registration_rows as $reg_row) {
410
-            if (is_array($reg_row)) {
411
-                $reg_csv_array = array();
412
-                if (! $event_id) {
413
-                    // get the event's name and Id
414
-                    $reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
415
-                        __('%1$s (%2$s)', 'event_espresso'),
416
-                        $this->_prepare_value_from_db_for_display(
417
-                            EEM_Event::instance(),
418
-                            'EVT_name',
419
-                            $reg_row['Event_CPT.post_title']
420
-                        ),
421
-                        $reg_row['Event_CPT.ID']
422
-                    );
423
-                }
424
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
425
-                /*@var $reg_row EE_Registration */
426
-                foreach ($reg_fields_to_include as $field_name) {
427
-                    $field = $reg_model->field_settings_for($field_name);
428
-                    if ($field_name == 'REG_final_price') {
429
-                        $value = $this->_prepare_value_from_db_for_display(
430
-                            $reg_model,
431
-                            $field_name,
432
-                            $reg_row['Registration.REG_final_price'],
433
-                            'localized_float'
434
-                        );
435
-                    } elseif ($field_name == 'REG_count') {
436
-                        $value = sprintf(
437
-                            __('%s of %s', 'event_espresso'),
438
-                            $this->_prepare_value_from_db_for_display(
439
-                                $reg_model,
440
-                                'REG_count',
441
-                                $reg_row['Registration.REG_count']
442
-                            ),
443
-                            $this->_prepare_value_from_db_for_display(
444
-                                $reg_model,
445
-                                'REG_group_size',
446
-                                $reg_row['Registration.REG_group_size']
447
-                            )
448
-                        );
449
-                    } elseif ($field_name == 'REG_date') {
450
-                        $value = $this->_prepare_value_from_db_for_display(
451
-                            $reg_model,
452
-                            $field_name,
453
-                            $reg_row['Registration.REG_date'],
454
-                            'no_html'
455
-                        );
456
-                    } else {
457
-                        $value = $this->_prepare_value_from_db_for_display(
458
-                            $reg_model,
459
-                            $field_name,
460
-                            $reg_row[ $field->get_qualified_column() ]
461
-                        );
462
-                    }
463
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
464
-                    if ($field_name == 'REG_final_price') {
465
-                        // add a column named Currency after the final price
466
-                        $reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
467
-                    }
468
-                }
469
-                // get pretty status
470
-                $stati = EEM_Status::instance()->localized_status(
471
-                    array(
472
-                        $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
473
-                        $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
474
-                    ),
475
-                    false,
476
-                    'sentence'
477
-                );
478
-                $reg_csv_array[ __(
479
-                    "Registration Status",
480
-                    'event_espresso'
481
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
482
-                // get pretty trnasaction status
483
-                $reg_csv_array[ __(
484
-                    "Transaction Status",
485
-                    'event_espresso'
486
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
-                $reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
488
-                    ? $this->_prepare_value_from_db_for_display(
489
-                        EEM_Transaction::instance(),
490
-                        'TXN_total',
491
-                        $reg_row['TransactionTable.TXN_total'],
492
-                        'localized_float'
493
-                    ) : '0.00';
494
-                $reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
495
-                    ? $this->_prepare_value_from_db_for_display(
496
-                        EEM_Transaction::instance(),
497
-                        'TXN_paid',
498
-                        $reg_row['TransactionTable.TXN_paid'],
499
-                        'localized_float'
500
-                    ) : '0.00';
501
-                $payment_methods = array();
502
-                $gateway_txn_ids_etc = array();
503
-                $payment_times = array();
504
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
505
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
506
-                        array(
507
-                            array(
508
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
509
-                                'STS_ID' => EEM_Payment::status_id_approved,
510
-                            ),
511
-                            'force_join' => array('Payment_Method'),
512
-                        ),
513
-                        ARRAY_A,
514
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
515
-                    );
516
-
517
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
518
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
519
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
520
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
521
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
522
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
523
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
524
-                    }
525
-                }
526
-                $reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
-                $reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
-                $reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
529
-                    ',',
530
-                    $gateway_txn_ids_etc
531
-                );
532
-
533
-                // get whether or not the user has checked in
534
-                $reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
535
-                    $reg_row['Registration.REG_ID'],
536
-                    'Checkin'
537
-                );
538
-                // get ticket of registration and its price
539
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
540
-                if ($reg_row['Ticket.TKT_ID']) {
541
-                    $ticket_name = $this->_prepare_value_from_db_for_display(
542
-                        $ticket_model,
543
-                        'TKT_name',
544
-                        $reg_row['Ticket.TKT_name']
545
-                    );
546
-                    $datetimes_strings = array();
547
-                    foreach (
548
-                        EEM_Datetime::instance()->get_all_wpdb_results(
549
-                            array(
550
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
551
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
552
-                            'default_where_conditions' => 'none',
553
-                            )
554
-                        ) as $datetime
555
-                    ) {
556
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
557
-                            EEM_Datetime::instance(),
558
-                            'DTT_EVT_start',
559
-                            $datetime['Datetime.DTT_EVT_start']
560
-                        );
561
-                    }
562
-                } else {
563
-                    $ticket_name = __('Unknown', 'event_espresso');
564
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
565
-                }
566
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
567
-                $reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
568
-                // get datetime(s) of registration
569
-
570
-                // add attendee columns
571
-                foreach ($att_fields_to_include as $att_field_name) {
572
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
573
-                    if ($reg_row['Attendee_CPT.ID']) {
574
-                        if ($att_field_name == 'STA_ID') {
575
-                            $value = EEM_State::instance()->get_var(
576
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
577
-                                'STA_name'
578
-                            );
579
-                        } elseif ($att_field_name == 'CNT_ISO') {
580
-                            $value = EEM_Country::instance()->get_var(
581
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
582
-                                'CNT_name'
583
-                            );
584
-                        } else {
585
-                            $value = $this->_prepare_value_from_db_for_display(
586
-                                EEM_Attendee::instance(),
587
-                                $att_field_name,
588
-                                $reg_row[ $field_obj->get_qualified_column() ]
589
-                            );
590
-                        }
591
-                    } else {
592
-                        $value = '';
593
-                    }
594
-
595
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
596
-                }
597
-
598
-                // make sure each registration has the same questions in the same order
599
-                foreach ($questions_for_these_regs_rows as $question_row) {
600
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
601
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
602
-                    }
603
-                }
604
-                // now fill out the questions THEY answered
605
-                foreach (
606
-                    EEM_Answer::instance()->get_all_wpdb_results(
607
-                        array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
608
-                    ) as $answer_row
609
-                ) {
610
-                    /* @var $answer EE_Answer */
611
-                    if ($answer_row['Question.QST_ID']) {
612
-                        $question_label = $this->_prepare_value_from_db_for_display(
613
-                            EEM_Question::instance(),
614
-                            'QST_admin_label',
615
-                            $answer_row['Question.QST_admin_label']
616
-                        );
617
-                    } else {
618
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
619
-                    }
620
-                    if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
621
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
622
-                            $answer_row['Answer.ANS_value']
623
-                        );
624
-                    } else {
625
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
626
-                            EEM_Answer::instance(),
627
-                            'ANS_value',
628
-                            $answer_row['Answer.ANS_value']
629
-                        );
630
-                    }
631
-                }
632
-                $registrations_csv_ready_array[] = apply_filters(
633
-                    'FHEE__EE_Export__report_registrations__reg_csv_array',
634
-                    $reg_csv_array,
635
-                    $reg_row
636
-                );
637
-            }
638
-        }
639
-
640
-        // if we couldn't export anything, we want to at least show the column headers
641
-        if (empty($registrations_csv_ready_array)) {
642
-            $reg_csv_array = array();
643
-            $model_and_fields_to_include = array(
644
-                'Registration' => $reg_fields_to_include,
645
-                'Attendee'     => $att_fields_to_include,
646
-            );
647
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
648
-                $model = EE_Registry::instance()->load_model($model_name);
649
-                foreach ($field_list as $field_name) {
650
-                    $field = $model->field_settings_for($field_name);
651
-                    $reg_csv_array[ $this->_get_column_name_for_field(
652
-                        $field
653
-                    ) ] = null;// $registration->get($field->get_name());
654
-                }
655
-            }
656
-            $registrations_csv_ready_array [] = $reg_csv_array;
657
-        }
658
-        if ($event_id) {
659
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
660
-            if (! $event_slug) {
661
-                $event_slug = __('unknown', 'event_espresso');
662
-            }
663
-        } else {
664
-            $event_slug = __('all', 'event_espresso');
665
-        }
666
-        $filename = sprintf("registrations-for-%s", $event_slug);
667
-
668
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
669
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
670
-        $this->EE_CSV->end_sending_csv($handle);
671
-    }
672
-
673
-    /**
674
-     * Gets the 'normal' column named for fields
675
-     *
676
-     * @param EE_Model_Field_Base $field
677
-     * @return string
678
-     */
679
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
680
-    {
681
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
682
-    }
683
-
684
-
685
-    /**
686
-     * @Export data for ALL events
687
-     * @access public
688
-     * @return void
689
-     */
690
-    public function export_categories()
691
-    {
692
-        // are any Event IDs set?
693
-        $query_params = array();
694
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
695
-            // do we have an array of IDs ?
696
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
697
-                // generate an "IN (CSV)" where clause
698
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
699
-                $filename = 'event-categories';
700
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
701
-            } else {
702
-                // generate regular where = clause
703
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
704
-                $filename = 'event-category#' . $EVT_CAT_ID;
705
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
706
-            }
707
-        } else {
708
-            // no IDs means we will d/l the entire table
709
-            $filename = 'all-categories';
710
-        }
711
-
712
-        $tables_to_export = array(
713
-            'Term_Taxonomy' => $query_params,
714
-        );
715
-
716
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
717
-        $filename = $this->generate_filename($filename);
718
-
719
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
720
-            EE_Error::add_error(
721
-                __(
722
-                    'An error occurred and the Category details could not be exported from the database.',
723
-                    'event_espresso'
724
-                ),
725
-                __FILE__,
726
-                __FUNCTION__,
727
-                __LINE__
728
-            );
729
-        }
730
-    }
731
-
732
-
733
-    /**
734
-     * @process export name to create a suitable filename
735
-     * @access  private
736
-     * @param string - export_name
737
-     * @return string on success, FALSE on fail
738
-     */
739
-    private function generate_filename($export_name = '')
740
-    {
741
-        if ($export_name != '') {
742
-            $filename = get_bloginfo('name') . '-' . $export_name;
743
-            $filename = sanitize_key($filename) . '-' . $this->today;
744
-            return $filename;
745
-        } else {
746
-            EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
747
-        }
748
-        return false;
749
-    }
750
-
751
-
752
-    /**
753
-     * @recursive function for exporting table data and merging the results with the next results
754
-     * @access    private
755
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
756
-     *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
757
-     * @return array on success, FALSE on fail
758
-     */
759
-    private function _get_export_data_for_models($models_to_export = array())
760
-    {
761
-        $table_data = false;
762
-        if (is_array($models_to_export)) {
763
-            foreach ($models_to_export as $model_name => $query_params) {
764
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
765
-                if (is_int($model_name)) {
766
-                    $model_name = $query_params;
767
-                    $query_params = array();
768
-                }
769
-                $model = EE_Registry::instance()->load_model($model_name);
770
-                $model_objects = $model->get_all($query_params);
771
-
772
-                $table_data[ $model_name ] = array();
773
-                foreach ($model_objects as $model_object) {
774
-                    $model_data_array = array();
775
-                    $fields = $model->field_settings();
776
-                    foreach ($fields as $field) {
777
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
778
-                        if ($field instanceof EE_Datetime_Field) {
779
-                            // $field->set_date_format('Y-m-d');
780
-                            // $field->set_time_format('H:i:s');
781
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
782
-                                $field->get_name(),
783
-                                'Y-m-d',
784
-                                'H:i:s'
785
-                            );
786
-                        } else {
787
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
788
-                        }
789
-                    }
790
-                    $table_data[ $model_name ][] = $model_data_array;
791
-                }
792
-            }
793
-        }
794
-        return $table_data;
795
-    }
19
+	const option_prefix = 'ee_report_job_';
20
+
21
+
22
+	// instance of the EE_Export object
23
+	private static $_instance = null;
24
+
25
+	// instance of the EE_CSV object
26
+	/**
27
+	 *
28
+	 * @var EE_CSV
29
+	 */
30
+	public $EE_CSV = null;
31
+
32
+
33
+	private $_req_data = array();
34
+
35
+
36
+	/**
37
+	 *        private constructor to prevent direct creation
38
+	 *
39
+	 * @Constructor
40
+	 * @access private
41
+	 * @param array $request_data
42
+	 */
43
+	private function __construct($request_data = array())
44
+	{
45
+		$this->_req_data = $request_data;
46
+		$this->today = date("Y-m-d", time());
47
+		require_once(EE_CLASSES . 'EE_CSV.class.php');
48
+		$this->EE_CSV = EE_CSV::instance();
49
+	}
50
+
51
+
52
+	/**
53
+	 *        @ singleton method used to instantiate class object
54
+	 *        @ access public
55
+	 *
56
+	 * @param array $request_data
57
+	 * @return \EE_Export
58
+	 */
59
+	public static function instance($request_data = array())
60
+	{
61
+		// check if class object is instantiated
62
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
63
+			self::$_instance = new self($request_data);
64
+		}
65
+		return self::$_instance;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @Export Event Espresso data - routes export requests
71
+	 * @access public
72
+	 * @return void | bool
73
+	 */
74
+	public function export()
75
+	{
76
+		// in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
77
+		if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
78
+			// check if action2 has export action
79
+			if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
80
+				// whoop! there it is!
81
+				$this->_req_data['action'] = $this->_req_data['action2'];
82
+			}
83
+		}
84
+
85
+		$this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
86
+
87
+		switch ($this->_req_data['export']) {
88
+			case 'report':
89
+				switch ($this->_req_data['action']) {
90
+					case "event":
91
+					case "export_events":
92
+					case 'all_event_data':
93
+						$this->export_all_event_data();
94
+						break;
95
+
96
+					case 'registrations_report_for_event':
97
+						$this->report_registrations_for_event($this->_req_data['EVT_ID']);
98
+						break;
99
+
100
+					case 'attendees':
101
+						$this->export_attendees();
102
+						break;
103
+
104
+					case 'categories':
105
+						$this->export_categories();
106
+						break;
107
+
108
+					default:
109
+						EE_Error::add_error(
110
+							__('An error occurred! The requested export report could not be found.', 'event_espresso'),
111
+							__FILE__,
112
+							__FUNCTION__,
113
+							__LINE__
114
+						);
115
+						return false;
116
+						break;
117
+				}
118
+				break; // end of switch export : report
119
+			default:
120
+				break;
121
+		} // end of switch export
122
+
123
+		exit;
124
+	}
125
+
126
+	/**
127
+	 * Downloads a CSV file with all the columns, but no data. This should be used for importing
128
+	 *
129
+	 * @return null kills execution
130
+	 */
131
+	public function export_sample()
132
+	{
133
+		$event = EEM_Event::instance()->get_one();
134
+		$this->_req_data['EVT_ID'] = $event->ID();
135
+		$this->export_all_event_data();
136
+	}
137
+
138
+
139
+	/**
140
+	 * @Export data for ALL events
141
+	 * @access public
142
+	 * @return void
143
+	 */
144
+	public function export_all_event_data()
145
+	{
146
+		// are any Event IDs set?
147
+		$event_query_params = array();
148
+		$related_models_query_params = array();
149
+		$related_through_reg_query_params = array();
150
+		$datetime_ticket_query_params = array();
151
+		$price_query_params = array();
152
+		$price_type_query_params = array();
153
+		$term_query_params = array();
154
+		$state_country_query_params = array();
155
+		$question_group_query_params = array();
156
+		$question_query_params = array();
157
+		if (isset($this->_req_data['EVT_ID'])) {
158
+			// do we have an array of IDs ?
159
+
160
+			if (is_array($this->_req_data['EVT_ID'])) {
161
+				$EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
162
+				$value_to_equal = array('IN', $EVT_IDs);
163
+				$filename = 'events';
164
+			} else {
165
+				// generate regular where = clause
166
+				$EVT_ID = absint($this->_req_data['EVT_ID']);
167
+				$value_to_equal = $EVT_ID;
168
+				$event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
169
+
170
+				$filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : __('unknown', 'event_espresso'));
171
+			}
172
+			$event_query_params[0]['EVT_ID'] = $value_to_equal;
173
+			$related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
174
+			$related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
175
+			$datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
176
+			$price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
177
+			$price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
+			$term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
179
+			$state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
180
+			$question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
181
+			$question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
182
+		} else {
183
+			$filename = 'all-events';
184
+		}
185
+
186
+
187
+		// array in the format:  table name =>  query where clause
188
+		$models_to_export = array(
189
+			'Event'                   => $event_query_params,
190
+			'Datetime'                => $related_models_query_params,
191
+			'Ticket_Template'         => $price_query_params,
192
+			'Ticket'                  => $datetime_ticket_query_params,
193
+			'Datetime_Ticket'         => $datetime_ticket_query_params,
194
+			'Price_Type'              => $price_type_query_params,
195
+			'Price'                   => $price_query_params,
196
+			'Ticket_Price'            => $price_query_params,
197
+			'Term'                    => $term_query_params,
198
+			'Term_Taxonomy'           => $related_models_query_params,
199
+			'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
200
+			'Country'                 => $state_country_query_params,
201
+			'State'                   => $state_country_query_params,
202
+			'Venue'                   => $related_models_query_params,
203
+			'Event_Venue'             => $related_models_query_params,
204
+			'Question_Group'          => $question_group_query_params,
205
+			'Event_Question_Group'    => $question_group_query_params,
206
+			'Question'                => $question_query_params,
207
+			'Question_Group_Question' => $question_query_params,
208
+			// 'Transaction'=>$related_through_reg_query_params,
209
+			// 'Registration'=>$related_models_query_params,
210
+			// 'Attendee'=>$related_through_reg_query_params,
211
+			// 'Line_Item'=>
212
+
213
+		);
214
+
215
+		$model_data = $this->_get_export_data_for_models($models_to_export);
216
+
217
+		$filename = $this->generate_filename($filename);
218
+
219
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220
+			EE_Error::add_error(
221
+				__(
222
+					"'An error occurred and the Event details could not be exported from the database.'",
223
+					"event_espresso"
224
+				),
225
+				__FILE__,
226
+				__FUNCTION__,
227
+				__LINE__
228
+			);
229
+		}
230
+	}
231
+
232
+	public function report_attendees()
233
+	{
234
+		$attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
235
+			array(
236
+				'force_join' => array('State', 'Country'),
237
+				'caps'       => EEM_Base::caps_read_admin,
238
+			)
239
+		);
240
+		$csv_data = array();
241
+		foreach ($attendee_rows as $attendee_row) {
242
+			$csv_row = array();
243
+			foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
244
+				if ($field_name == 'STA_ID') {
245
+					$state_name_field = EEM_State::instance()->field_settings_for('STA_name');
246
+					$csv_row[ __('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
247
+					) ];
248
+				} elseif ($field_name == 'CNT_ISO') {
249
+					$country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
250
+					$csv_row[ __(
251
+						'Country',
252
+						'event_espresso'
253
+					) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
254
+				} else {
255
+					$csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
256
+				}
257
+			}
258
+			$csv_data[] = $csv_row;
259
+		}
260
+
261
+		$filename = $this->generate_filename('contact-list-report');
262
+
263
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
264
+		$this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
265
+		$this->EE_CSV->end_sending_csv($handle);
266
+	}
267
+
268
+
269
+	/**
270
+	 * @Export data for ALL attendees
271
+	 * @access public
272
+	 * @return void
273
+	 */
274
+	public function export_attendees()
275
+	{
276
+
277
+		$states_that_have_an_attendee = EEM_State::instance()->get_all(
278
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
279
+		);
280
+		$countries_that_have_an_attendee = EEM_Country::instance()->get_all(
281
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
282
+		);
283
+		// $states_to_export_query_params
284
+		$models_to_export = array(
285
+			'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
286
+			'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
287
+			'Attendee' => array(),
288
+		);
289
+
290
+
291
+		$model_data = $this->_get_export_data_for_models($models_to_export);
292
+		$filename = $this->generate_filename('all-attendees');
293
+
294
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295
+			EE_Error::add_error(
296
+				__(
297
+					'An error occurred and the Attendee data could not be exported from the database.',
298
+					'event_espresso'
299
+				),
300
+				__FILE__,
301
+				__FUNCTION__,
302
+				__LINE__
303
+			);
304
+		}
305
+	}
306
+
307
+	/**
308
+	 * Shortcut for preparing a database result for display
309
+	 *
310
+	 * @param EEM_Base       $model
311
+	 * @param string         $field_name
312
+	 * @param string         $raw_db_value
313
+	 * @param boolean|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
314
+	 *                                      NOT display pretty
315
+	 * @return string
316
+	 */
317
+	protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
318
+	{
319
+		$field_obj = $model->field_settings_for($field_name);
320
+		$value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
321
+		if ($field_obj instanceof EE_Datetime_Field) {
322
+			$field_obj->set_date_format(
323
+				EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
324
+				$pretty_schema
325
+			);
326
+			$field_obj->set_time_format(
327
+				EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
328
+				$pretty_schema
329
+			);
330
+		}
331
+		if ($pretty_schema === true) {
332
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
333
+		} elseif (is_string($pretty_schema)) {
334
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
335
+		} else {
336
+			return $field_obj->prepare_for_get($value_on_model_obj);
337
+		}
338
+	}
339
+
340
+	/**
341
+	 * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
342
+	 * name, and the questions associated with the registrations
343
+	 *
344
+	 * @param int $event_id
345
+	 */
346
+	public function report_registrations_for_event($event_id = null)
347
+	{
348
+		$reg_fields_to_include = array(
349
+			'TXN_ID',
350
+			'ATT_ID',
351
+			'REG_ID',
352
+			'REG_date',
353
+			'REG_code',
354
+			'REG_count',
355
+			'REG_final_price',
356
+
357
+		);
358
+		$att_fields_to_include = array(
359
+			'ATT_fname',
360
+			'ATT_lname',
361
+			'ATT_email',
362
+			'ATT_address',
363
+			'ATT_address2',
364
+			'ATT_city',
365
+			'STA_ID',
366
+			'CNT_ISO',
367
+			'ATT_zip',
368
+			'ATT_phone',
369
+		);
370
+
371
+		$registrations_csv_ready_array = array();
372
+		$reg_model = EE_Registry::instance()->load_model('Registration');
373
+		$query_params = apply_filters(
374
+			'FHEE__EE_Export__report_registration_for_event',
375
+			array(
376
+				array(
377
+					'OR'                 => array(
378
+						// don't include registrations from failed or abandoned transactions...
379
+						'Transaction.STS_ID' => array(
380
+							'NOT IN',
381
+							array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
382
+						),
383
+						// unless the registration is approved, in which case include it regardless of transaction status
384
+						'STS_ID'             => EEM_Registration::status_id_approved,
385
+					),
386
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
387
+				),
388
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
389
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
390
+				'caps'       => EEM_Base::caps_read_admin,
391
+			),
392
+			$event_id
393
+		);
394
+		if ($event_id) {
395
+			$query_params[0]['EVT_ID'] = $event_id;
396
+		} else {
397
+			$query_params['force_join'][] = 'Event';
398
+		}
399
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
400
+		// get all questions which relate to someone in this group
401
+		$registration_ids = array();
402
+		foreach ($registration_rows as $reg_row) {
403
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
404
+		}
405
+		// EEM_Question::instance()->show_next_x_db_queries();
406
+		$questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
407
+			array(array('Answer.REG_ID' => array('IN', $registration_ids)))
408
+		);
409
+		foreach ($registration_rows as $reg_row) {
410
+			if (is_array($reg_row)) {
411
+				$reg_csv_array = array();
412
+				if (! $event_id) {
413
+					// get the event's name and Id
414
+					$reg_csv_array[ __('Event', 'event_espresso') ] = sprintf(
415
+						__('%1$s (%2$s)', 'event_espresso'),
416
+						$this->_prepare_value_from_db_for_display(
417
+							EEM_Event::instance(),
418
+							'EVT_name',
419
+							$reg_row['Event_CPT.post_title']
420
+						),
421
+						$reg_row['Event_CPT.ID']
422
+					);
423
+				}
424
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
425
+				/*@var $reg_row EE_Registration */
426
+				foreach ($reg_fields_to_include as $field_name) {
427
+					$field = $reg_model->field_settings_for($field_name);
428
+					if ($field_name == 'REG_final_price') {
429
+						$value = $this->_prepare_value_from_db_for_display(
430
+							$reg_model,
431
+							$field_name,
432
+							$reg_row['Registration.REG_final_price'],
433
+							'localized_float'
434
+						);
435
+					} elseif ($field_name == 'REG_count') {
436
+						$value = sprintf(
437
+							__('%s of %s', 'event_espresso'),
438
+							$this->_prepare_value_from_db_for_display(
439
+								$reg_model,
440
+								'REG_count',
441
+								$reg_row['Registration.REG_count']
442
+							),
443
+							$this->_prepare_value_from_db_for_display(
444
+								$reg_model,
445
+								'REG_group_size',
446
+								$reg_row['Registration.REG_group_size']
447
+							)
448
+						);
449
+					} elseif ($field_name == 'REG_date') {
450
+						$value = $this->_prepare_value_from_db_for_display(
451
+							$reg_model,
452
+							$field_name,
453
+							$reg_row['Registration.REG_date'],
454
+							'no_html'
455
+						);
456
+					} else {
457
+						$value = $this->_prepare_value_from_db_for_display(
458
+							$reg_model,
459
+							$field_name,
460
+							$reg_row[ $field->get_qualified_column() ]
461
+						);
462
+					}
463
+					$reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
464
+					if ($field_name == 'REG_final_price') {
465
+						// add a column named Currency after the final price
466
+						$reg_csv_array[ __("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
467
+					}
468
+				}
469
+				// get pretty status
470
+				$stati = EEM_Status::instance()->localized_status(
471
+					array(
472
+						$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
473
+						$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
474
+					),
475
+					false,
476
+					'sentence'
477
+				);
478
+				$reg_csv_array[ __(
479
+					"Registration Status",
480
+					'event_espresso'
481
+				) ] = $stati[ $reg_row['Registration.STS_ID'] ];
482
+				// get pretty trnasaction status
483
+				$reg_csv_array[ __(
484
+					"Transaction Status",
485
+					'event_espresso'
486
+				) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
487
+				$reg_csv_array[ __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
488
+					? $this->_prepare_value_from_db_for_display(
489
+						EEM_Transaction::instance(),
490
+						'TXN_total',
491
+						$reg_row['TransactionTable.TXN_total'],
492
+						'localized_float'
493
+					) : '0.00';
494
+				$reg_csv_array[ __('Amount Paid', 'event_espresso') ] = $is_primary_reg
495
+					? $this->_prepare_value_from_db_for_display(
496
+						EEM_Transaction::instance(),
497
+						'TXN_paid',
498
+						$reg_row['TransactionTable.TXN_paid'],
499
+						'localized_float'
500
+					) : '0.00';
501
+				$payment_methods = array();
502
+				$gateway_txn_ids_etc = array();
503
+				$payment_times = array();
504
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
505
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
506
+						array(
507
+							array(
508
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
509
+								'STS_ID' => EEM_Payment::status_id_approved,
510
+							),
511
+							'force_join' => array('Payment_Method'),
512
+						),
513
+						ARRAY_A,
514
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
515
+					);
516
+
517
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
518
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
519
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
520
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
521
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
522
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
523
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
524
+					}
525
+				}
526
+				$reg_csv_array[ __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
527
+				$reg_csv_array[ __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
528
+				$reg_csv_array[ __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
529
+					',',
530
+					$gateway_txn_ids_etc
531
+				);
532
+
533
+				// get whether or not the user has checked in
534
+				$reg_csv_array[ __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
535
+					$reg_row['Registration.REG_ID'],
536
+					'Checkin'
537
+				);
538
+				// get ticket of registration and its price
539
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
540
+				if ($reg_row['Ticket.TKT_ID']) {
541
+					$ticket_name = $this->_prepare_value_from_db_for_display(
542
+						$ticket_model,
543
+						'TKT_name',
544
+						$reg_row['Ticket.TKT_name']
545
+					);
546
+					$datetimes_strings = array();
547
+					foreach (
548
+						EEM_Datetime::instance()->get_all_wpdb_results(
549
+							array(
550
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
551
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
552
+							'default_where_conditions' => 'none',
553
+							)
554
+						) as $datetime
555
+					) {
556
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
557
+							EEM_Datetime::instance(),
558
+							'DTT_EVT_start',
559
+							$datetime['Datetime.DTT_EVT_start']
560
+						);
561
+					}
562
+				} else {
563
+					$ticket_name = __('Unknown', 'event_espresso');
564
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
565
+				}
566
+				$reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
567
+				$reg_csv_array[ __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
568
+				// get datetime(s) of registration
569
+
570
+				// add attendee columns
571
+				foreach ($att_fields_to_include as $att_field_name) {
572
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
573
+					if ($reg_row['Attendee_CPT.ID']) {
574
+						if ($att_field_name == 'STA_ID') {
575
+							$value = EEM_State::instance()->get_var(
576
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
577
+								'STA_name'
578
+							);
579
+						} elseif ($att_field_name == 'CNT_ISO') {
580
+							$value = EEM_Country::instance()->get_var(
581
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
582
+								'CNT_name'
583
+							);
584
+						} else {
585
+							$value = $this->_prepare_value_from_db_for_display(
586
+								EEM_Attendee::instance(),
587
+								$att_field_name,
588
+								$reg_row[ $field_obj->get_qualified_column() ]
589
+							);
590
+						}
591
+					} else {
592
+						$value = '';
593
+					}
594
+
595
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
596
+				}
597
+
598
+				// make sure each registration has the same questions in the same order
599
+				foreach ($questions_for_these_regs_rows as $question_row) {
600
+					if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
601
+						$reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
602
+					}
603
+				}
604
+				// now fill out the questions THEY answered
605
+				foreach (
606
+					EEM_Answer::instance()->get_all_wpdb_results(
607
+						array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
608
+					) as $answer_row
609
+				) {
610
+					/* @var $answer EE_Answer */
611
+					if ($answer_row['Question.QST_ID']) {
612
+						$question_label = $this->_prepare_value_from_db_for_display(
613
+							EEM_Question::instance(),
614
+							'QST_admin_label',
615
+							$answer_row['Question.QST_admin_label']
616
+						);
617
+					} else {
618
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
619
+					}
620
+					if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
621
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
622
+							$answer_row['Answer.ANS_value']
623
+						);
624
+					} else {
625
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
626
+							EEM_Answer::instance(),
627
+							'ANS_value',
628
+							$answer_row['Answer.ANS_value']
629
+						);
630
+					}
631
+				}
632
+				$registrations_csv_ready_array[] = apply_filters(
633
+					'FHEE__EE_Export__report_registrations__reg_csv_array',
634
+					$reg_csv_array,
635
+					$reg_row
636
+				);
637
+			}
638
+		}
639
+
640
+		// if we couldn't export anything, we want to at least show the column headers
641
+		if (empty($registrations_csv_ready_array)) {
642
+			$reg_csv_array = array();
643
+			$model_and_fields_to_include = array(
644
+				'Registration' => $reg_fields_to_include,
645
+				'Attendee'     => $att_fields_to_include,
646
+			);
647
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
648
+				$model = EE_Registry::instance()->load_model($model_name);
649
+				foreach ($field_list as $field_name) {
650
+					$field = $model->field_settings_for($field_name);
651
+					$reg_csv_array[ $this->_get_column_name_for_field(
652
+						$field
653
+					) ] = null;// $registration->get($field->get_name());
654
+				}
655
+			}
656
+			$registrations_csv_ready_array [] = $reg_csv_array;
657
+		}
658
+		if ($event_id) {
659
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
660
+			if (! $event_slug) {
661
+				$event_slug = __('unknown', 'event_espresso');
662
+			}
663
+		} else {
664
+			$event_slug = __('all', 'event_espresso');
665
+		}
666
+		$filename = sprintf("registrations-for-%s", $event_slug);
667
+
668
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
669
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
670
+		$this->EE_CSV->end_sending_csv($handle);
671
+	}
672
+
673
+	/**
674
+	 * Gets the 'normal' column named for fields
675
+	 *
676
+	 * @param EE_Model_Field_Base $field
677
+	 * @return string
678
+	 */
679
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
680
+	{
681
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
682
+	}
683
+
684
+
685
+	/**
686
+	 * @Export data for ALL events
687
+	 * @access public
688
+	 * @return void
689
+	 */
690
+	public function export_categories()
691
+	{
692
+		// are any Event IDs set?
693
+		$query_params = array();
694
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
695
+			// do we have an array of IDs ?
696
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
697
+				// generate an "IN (CSV)" where clause
698
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
699
+				$filename = 'event-categories';
700
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
701
+			} else {
702
+				// generate regular where = clause
703
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
704
+				$filename = 'event-category#' . $EVT_CAT_ID;
705
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
706
+			}
707
+		} else {
708
+			// no IDs means we will d/l the entire table
709
+			$filename = 'all-categories';
710
+		}
711
+
712
+		$tables_to_export = array(
713
+			'Term_Taxonomy' => $query_params,
714
+		);
715
+
716
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
717
+		$filename = $this->generate_filename($filename);
718
+
719
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
720
+			EE_Error::add_error(
721
+				__(
722
+					'An error occurred and the Category details could not be exported from the database.',
723
+					'event_espresso'
724
+				),
725
+				__FILE__,
726
+				__FUNCTION__,
727
+				__LINE__
728
+			);
729
+		}
730
+	}
731
+
732
+
733
+	/**
734
+	 * @process export name to create a suitable filename
735
+	 * @access  private
736
+	 * @param string - export_name
737
+	 * @return string on success, FALSE on fail
738
+	 */
739
+	private function generate_filename($export_name = '')
740
+	{
741
+		if ($export_name != '') {
742
+			$filename = get_bloginfo('name') . '-' . $export_name;
743
+			$filename = sanitize_key($filename) . '-' . $this->today;
744
+			return $filename;
745
+		} else {
746
+			EE_Error::add_error(__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
747
+		}
748
+		return false;
749
+	}
750
+
751
+
752
+	/**
753
+	 * @recursive function for exporting table data and merging the results with the next results
754
+	 * @access    private
755
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
756
+	 *                                query params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
757
+	 * @return array on success, FALSE on fail
758
+	 */
759
+	private function _get_export_data_for_models($models_to_export = array())
760
+	{
761
+		$table_data = false;
762
+		if (is_array($models_to_export)) {
763
+			foreach ($models_to_export as $model_name => $query_params) {
764
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
765
+				if (is_int($model_name)) {
766
+					$model_name = $query_params;
767
+					$query_params = array();
768
+				}
769
+				$model = EE_Registry::instance()->load_model($model_name);
770
+				$model_objects = $model->get_all($query_params);
771
+
772
+				$table_data[ $model_name ] = array();
773
+				foreach ($model_objects as $model_object) {
774
+					$model_data_array = array();
775
+					$fields = $model->field_settings();
776
+					foreach ($fields as $field) {
777
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
778
+						if ($field instanceof EE_Datetime_Field) {
779
+							// $field->set_date_format('Y-m-d');
780
+							// $field->set_time_format('H:i:s');
781
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
782
+								$field->get_name(),
783
+								'Y-m-d',
784
+								'H:i:s'
785
+							);
786
+						} else {
787
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
788
+						}
789
+					}
790
+					$table_data[ $model_name ][] = $model_data_array;
791
+				}
792
+			}
793
+		}
794
+		return $table_data;
795
+	}
796 796
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Answer.class.php 1 patch
Indentation   +138 added lines, -138 removed lines patch added patch discarded remove patch
@@ -10,144 +10,144 @@
 block discarded – undo
10 10
 class EE_Answer extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     *
15
-     * @param array $props_n_values
16
-     * @return EE_Answer
17
-     */
18
-    public static function new_instance($props_n_values = array())
19
-    {
20
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
21
-        return $has_object ? $has_object : new self($props_n_values);
22
-    }
23
-
24
-
25
-    /**
26
-     *
27
-     * @param array $props_n_values
28
-     * @return EE_Answer
29
-     */
30
-    public static function new_instance_from_db($props_n_values = array())
31
-    {
32
-        return new self($props_n_values, true);
33
-    }
34
-
35
-
36
-    /**
37
-     *    Set Question ID
38
-     *
39
-     * @access        public
40
-     * @param int $QST_ID
41
-     */
42
-    public function set_question($QST_ID = 0)
43
-    {
44
-        $this->set('QST_ID', $QST_ID);
45
-    }
46
-
47
-
48
-    /**
49
-     *    Set Registration ID
50
-     *
51
-     * @access        public
52
-     * @param int $REG_ID
53
-     */
54
-    public function set_registration($REG_ID = 0)
55
-    {
56
-        $this->set('REG_ID', $REG_ID);
57
-    }
58
-
59
-
60
-    /**
61
-     *    Set Answer value
62
-     *
63
-     * @access        public
64
-     * @param mixed $ANS_value
65
-     */
66
-    public function set_value($ANS_value = '')
67
-    {
68
-        $this->set('ANS_value', $ANS_value);
69
-    }
70
-
71
-
72
-    /**
73
-     *    get Attendee First Name
74
-     *
75
-     * @access        public
76
-     * @return        int
77
-     */
78
-    public function registration_ID()
79
-    {
80
-        return $this->get('REG_ID');
81
-    }
82
-
83
-
84
-    /**
85
-     *    get Attendee Last Name
86
-     *
87
-     * @access        public
88
-     * @return        int
89
-     */
90
-    public function question_ID()
91
-    {
92
-        return $this->get('QST_ID');
93
-    }
94
-
95
-
96
-    /**
97
-     *    get Attendee Address
98
-     *
99
-     * @access        public
100
-     * @return        string
101
-     */
102
-    public function value()
103
-    {
104
-        return $this->get('ANS_value');
105
-    }
106
-
107
-
108
-    /**
109
-     * Gets a pretty form of the value (mostly applies to answers that have multiple answers)
110
-     *
111
-     * @param null $schema
112
-     * @return string
113
-     */
114
-    public function pretty_value($schema = null)
115
-    {
116
-        return $this->get_pretty('ANS_value', $schema);
117
-    }
118
-
119
-
120
-    /**
121
-     * Echoes out a pretty value (even for multi-choice options)
122
-     *
123
-     * @param string $schema
124
-     */
125
-    public function e_value($schema = null)
126
-    {
127
-        $this->e('ANS_value', $schema);
128
-    }
129
-
130
-
131
-    /**
132
-     * Gets the related EE_Question to this EE_Answer
133
-     *
134
-     * @return EE_Question
135
-     */
136
-    public function question()
137
-    {
138
-        return $this->get_first_related('Question');
139
-    }
140
-
141
-
142
-    /**
143
-     * Gets the related EE_Registration to this EE_Answer
144
-     *
145
-     * @return EE_Registration
146
-     */
147
-    public function registration()
148
-    {
149
-        return $this->get_first_related('Registration');
150
-    }
13
+	/**
14
+	 *
15
+	 * @param array $props_n_values
16
+	 * @return EE_Answer
17
+	 */
18
+	public static function new_instance($props_n_values = array())
19
+	{
20
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
21
+		return $has_object ? $has_object : new self($props_n_values);
22
+	}
23
+
24
+
25
+	/**
26
+	 *
27
+	 * @param array $props_n_values
28
+	 * @return EE_Answer
29
+	 */
30
+	public static function new_instance_from_db($props_n_values = array())
31
+	{
32
+		return new self($props_n_values, true);
33
+	}
34
+
35
+
36
+	/**
37
+	 *    Set Question ID
38
+	 *
39
+	 * @access        public
40
+	 * @param int $QST_ID
41
+	 */
42
+	public function set_question($QST_ID = 0)
43
+	{
44
+		$this->set('QST_ID', $QST_ID);
45
+	}
46
+
47
+
48
+	/**
49
+	 *    Set Registration ID
50
+	 *
51
+	 * @access        public
52
+	 * @param int $REG_ID
53
+	 */
54
+	public function set_registration($REG_ID = 0)
55
+	{
56
+		$this->set('REG_ID', $REG_ID);
57
+	}
58
+
59
+
60
+	/**
61
+	 *    Set Answer value
62
+	 *
63
+	 * @access        public
64
+	 * @param mixed $ANS_value
65
+	 */
66
+	public function set_value($ANS_value = '')
67
+	{
68
+		$this->set('ANS_value', $ANS_value);
69
+	}
70
+
71
+
72
+	/**
73
+	 *    get Attendee First Name
74
+	 *
75
+	 * @access        public
76
+	 * @return        int
77
+	 */
78
+	public function registration_ID()
79
+	{
80
+		return $this->get('REG_ID');
81
+	}
82
+
83
+
84
+	/**
85
+	 *    get Attendee Last Name
86
+	 *
87
+	 * @access        public
88
+	 * @return        int
89
+	 */
90
+	public function question_ID()
91
+	{
92
+		return $this->get('QST_ID');
93
+	}
94
+
95
+
96
+	/**
97
+	 *    get Attendee Address
98
+	 *
99
+	 * @access        public
100
+	 * @return        string
101
+	 */
102
+	public function value()
103
+	{
104
+		return $this->get('ANS_value');
105
+	}
106
+
107
+
108
+	/**
109
+	 * Gets a pretty form of the value (mostly applies to answers that have multiple answers)
110
+	 *
111
+	 * @param null $schema
112
+	 * @return string
113
+	 */
114
+	public function pretty_value($schema = null)
115
+	{
116
+		return $this->get_pretty('ANS_value', $schema);
117
+	}
118
+
119
+
120
+	/**
121
+	 * Echoes out a pretty value (even for multi-choice options)
122
+	 *
123
+	 * @param string $schema
124
+	 */
125
+	public function e_value($schema = null)
126
+	{
127
+		$this->e('ANS_value', $schema);
128
+	}
129
+
130
+
131
+	/**
132
+	 * Gets the related EE_Question to this EE_Answer
133
+	 *
134
+	 * @return EE_Question
135
+	 */
136
+	public function question()
137
+	{
138
+		return $this->get_first_related('Question');
139
+	}
140
+
141
+
142
+	/**
143
+	 * Gets the related EE_Registration to this EE_Answer
144
+	 *
145
+	 * @return EE_Registration
146
+	 */
147
+	public function registration()
148
+	{
149
+		return $this->get_first_related('Registration');
150
+	}
151 151
 }
152 152
 
153 153
 /* End of file EE_Answer.class.php */
Please login to merge, or discard this patch.
core/db_classes/EE_Country.class.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -10,123 +10,123 @@
 block discarded – undo
10 10
 class EE_Country extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Country|mixed
16
-     */
17
-    public static function new_instance($props_n_values = array())
18
-    {
19
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
-        return $has_object ? $has_object : new self($props_n_values);
21
-    }
22
-
23
-
24
-    /**
25
-     * @param array $props_n_values
26
-     * @return EE_Country
27
-     */
28
-    public static function new_instance_from_db($props_n_values = array())
29
-    {
30
-        return new self($props_n_values, true);
31
-    }
32
-
33
-
34
-    /**
35
-     * Gets the country name
36
-     *
37
-     * @return string
38
-     */
39
-    public function name()
40
-    {
41
-        return $this->get('CNT_name');
42
-    }
43
-
44
-
45
-    /**
46
-     * gets the country's currency code
47
-     *
48
-     * @return string
49
-     */
50
-    public function currency_code()
51
-    {
52
-        return $this->get('CNT_cur_code');
53
-    }
54
-
55
-
56
-    /**
57
-     * gets the country's currency sign/symbol
58
-     *
59
-     * @return string
60
-     */
61
-    public function currency_sign()
62
-    {
63
-        $CNT_cur_sign = $this->get('CNT_cur_sign');
64
-        return $CNT_cur_sign ? $CNT_cur_sign : '';
65
-    }
66
-
67
-
68
-    /**
69
-     * Currency name singular
70
-     *
71
-     * @return string
72
-     */
73
-    public function currency_name_single()
74
-    {
75
-        return $this->get('CNT_cur_single');
76
-    }
77
-
78
-
79
-    /**
80
-     * Currency name plural
81
-     *
82
-     * @return string
83
-     */
84
-    public function currency_name_plural()
85
-    {
86
-        return $this->get('CNT_cur_plural');
87
-    }
88
-
89
-
90
-    /**
91
-     * currency_sign_before - ie: $TRUE  or  FALSE$
92
-     *
93
-     * @return boolean
94
-     */
95
-    public function currency_sign_before()
96
-    {
97
-        return $this->get('CNT_cur_sign_b4');
98
-    }
99
-
100
-
101
-    /**
102
-     * currency_decimal_places : 2 = 0.00   3 = 0.000
103
-     *
104
-     * @return integer
105
-     */
106
-    public function currency_decimal_places()
107
-    {
108
-        return $this->get('CNT_cur_dec_plc');
109
-    }
110
-
111
-
112
-    /**
113
-     * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
114
-     *
115
-     * @return string
116
-     */
117
-    public function currency_decimal_mark()
118
-    {
119
-        return $this->get('CNT_cur_dec_mrk');
120
-    }
121
-
122
-
123
-    /**
124
-     * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
125
-     *
126
-     * @return string
127
-     */
128
-    public function currency_thousands_separator()
129
-    {
130
-        return $this->get('CNT_cur_thsnds');
131
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Country|mixed
16
+	 */
17
+	public static function new_instance($props_n_values = array())
18
+	{
19
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
20
+		return $has_object ? $has_object : new self($props_n_values);
21
+	}
22
+
23
+
24
+	/**
25
+	 * @param array $props_n_values
26
+	 * @return EE_Country
27
+	 */
28
+	public static function new_instance_from_db($props_n_values = array())
29
+	{
30
+		return new self($props_n_values, true);
31
+	}
32
+
33
+
34
+	/**
35
+	 * Gets the country name
36
+	 *
37
+	 * @return string
38
+	 */
39
+	public function name()
40
+	{
41
+		return $this->get('CNT_name');
42
+	}
43
+
44
+
45
+	/**
46
+	 * gets the country's currency code
47
+	 *
48
+	 * @return string
49
+	 */
50
+	public function currency_code()
51
+	{
52
+		return $this->get('CNT_cur_code');
53
+	}
54
+
55
+
56
+	/**
57
+	 * gets the country's currency sign/symbol
58
+	 *
59
+	 * @return string
60
+	 */
61
+	public function currency_sign()
62
+	{
63
+		$CNT_cur_sign = $this->get('CNT_cur_sign');
64
+		return $CNT_cur_sign ? $CNT_cur_sign : '';
65
+	}
66
+
67
+
68
+	/**
69
+	 * Currency name singular
70
+	 *
71
+	 * @return string
72
+	 */
73
+	public function currency_name_single()
74
+	{
75
+		return $this->get('CNT_cur_single');
76
+	}
77
+
78
+
79
+	/**
80
+	 * Currency name plural
81
+	 *
82
+	 * @return string
83
+	 */
84
+	public function currency_name_plural()
85
+	{
86
+		return $this->get('CNT_cur_plural');
87
+	}
88
+
89
+
90
+	/**
91
+	 * currency_sign_before - ie: $TRUE  or  FALSE$
92
+	 *
93
+	 * @return boolean
94
+	 */
95
+	public function currency_sign_before()
96
+	{
97
+		return $this->get('CNT_cur_sign_b4');
98
+	}
99
+
100
+
101
+	/**
102
+	 * currency_decimal_places : 2 = 0.00   3 = 0.000
103
+	 *
104
+	 * @return integer
105
+	 */
106
+	public function currency_decimal_places()
107
+	{
108
+		return $this->get('CNT_cur_dec_plc');
109
+	}
110
+
111
+
112
+	/**
113
+	 * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
114
+	 *
115
+	 * @return string
116
+	 */
117
+	public function currency_decimal_mark()
118
+	{
119
+		return $this->get('CNT_cur_dec_mrk');
120
+	}
121
+
122
+
123
+	/**
124
+	 * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
125
+	 *
126
+	 * @return string
127
+	 */
128
+	public function currency_thousands_separator()
129
+	{
130
+		return $this->get('CNT_cur_thsnds');
131
+	}
132 132
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Message.class.php 2 patches
Indentation   +867 added lines, -867 removed lines patch added patch discarded remove patch
@@ -10,875 +10,875 @@
 block discarded – undo
10 10
 class EE_Message extends EE_Base_Class implements EEI_Admin_Links
11 11
 {
12 12
 
13
-    /**
14
-     * @deprecated 4.9.0  Added for backward compat with add-on's
15
-     * @type null
16
-     */
17
-    public $template_pack;
18
-
19
-    /**
20
-     * @deprecated 4.9.0 Added for backward compat with add-on's
21
-     * @type null
22
-     */
23
-    public $template_variation;
24
-
25
-    /**
26
-     * @deprecated 4.9.0 Added for backward compat with add-on's
27
-     * @type string
28
-     */
29
-    public $content = '';
30
-
31
-
32
-    /**
33
-     * @type EE_messenger $_messenger
34
-     */
35
-    protected $_messenger = null;
36
-
37
-    /**
38
-     * @type EE_message_type $_message_type
39
-     */
40
-    protected $_message_type = null;
41
-
42
-
43
-    /**
44
-     * @param array  $props_n_values
45
-     * @param string $timezone
46
-     * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
-     *                             format.
48
-     * @return EE_Message
49
-     */
50
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
-        // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
55
-            EE_Registry::instance()->load_helper('URL');
56
-            $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
-        }
58
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
-    }
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values
64
-     * @param string $timezone
65
-     * @return EE_Message
66
-     */
67
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
68
-    {
69
-        return new self($props_n_values, true, $timezone);
70
-    }
71
-
72
-
73
-    /**
74
-     * Gets MSG_token
75
-     *
76
-     * @return int
77
-     */
78
-    public function MSG_token()
79
-    {
80
-        return $this->get('MSG_token');
81
-    }
82
-
83
-
84
-    /**
85
-     * Sets MSG_token
86
-     *
87
-     * @param int $MSG_token
88
-     */
89
-    public function set_MSG_token($MSG_token)
90
-    {
91
-        $this->set('MSG_token', $MSG_token);
92
-    }
93
-
94
-
95
-    /**
96
-     * Gets GRP_ID
97
-     *
98
-     * @return int
99
-     */
100
-    public function GRP_ID()
101
-    {
102
-        return $this->get('GRP_ID');
103
-    }
104
-
105
-
106
-    /**
107
-     * Sets GRP_ID
108
-     *
109
-     * @param int $GRP_ID
110
-     */
111
-    public function set_GRP_ID($GRP_ID)
112
-    {
113
-        $this->set('GRP_ID', $GRP_ID);
114
-    }
115
-
116
-
117
-    /**
118
-     * Gets TXN_ID
119
-     *
120
-     * @return int
121
-     */
122
-    public function TXN_ID()
123
-    {
124
-        return $this->get('TXN_ID');
125
-    }
126
-
127
-
128
-    /**
129
-     * Sets TXN_ID
130
-     *
131
-     * @param int $TXN_ID
132
-     */
133
-    public function set_TXN_ID($TXN_ID)
134
-    {
135
-        $this->set('TXN_ID', $TXN_ID);
136
-    }
137
-
138
-
139
-    /**
140
-     * Gets messenger
141
-     *
142
-     * @return string
143
-     */
144
-    public function messenger()
145
-    {
146
-        return $this->get('MSG_messenger');
147
-    }
148
-
149
-
150
-    /**
151
-     * Sets messenger
152
-     *
153
-     * @param string $messenger
154
-     */
155
-    public function set_messenger($messenger)
156
-    {
157
-        $this->set('MSG_messenger', $messenger);
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns corresponding messenger object for the set messenger on this message
163
-     *
164
-     * @return EE_messenger | null
165
-     */
166
-    public function messenger_object()
167
-    {
168
-        return $this->_messenger;
169
-    }
170
-
171
-
172
-    /**
173
-     * Sets messenger
174
-     *
175
-     * @param EE_messenger $messenger
176
-     */
177
-    public function set_messenger_object(EE_messenger $messenger)
178
-    {
179
-        $this->_messenger = $messenger;
180
-    }
181
-
182
-
183
-    /**
184
-     * validates messenger
185
-     *
186
-     * @param bool $throw_exceptions
187
-     * @return bool
188
-     * @throws \EE_Error
189
-     */
190
-    public function valid_messenger($throw_exceptions = false)
191
-    {
192
-        if ($this->_messenger instanceof EE_messenger) {
193
-            return true;
194
-        }
195
-        if ($throw_exceptions) {
196
-            throw new EE_Error(
197
-                sprintf(
198
-                    __(
199
-                        'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
-                        'event_espresso'
201
-                    ),
202
-                    $this->messenger()
203
-                )
204
-            );
205
-        }
206
-        return false;
207
-    }
208
-
209
-
210
-    /**
211
-     * This returns the set localized label for the messenger on this message.
212
-     * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
-     * with this message.
214
-     *
215
-     * @param   bool $plural whether to return the plural label or not.
216
-     * @return string
217
-     */
218
-    public function messenger_label($plural = false)
219
-    {
220
-        $label_type = $plural ? 'plural' : 'singular';
221
-        $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
-    }
224
-
225
-
226
-    /**
227
-     * Gets message_type
228
-     *
229
-     * @return string
230
-     */
231
-    public function message_type()
232
-    {
233
-        return $this->get('MSG_message_type');
234
-    }
235
-
236
-
237
-    /**
238
-     * Sets message_type
239
-     *
240
-     * @param string $message_type
241
-     */
242
-    public function set_message_type($message_type)
243
-    {
244
-        $this->set('MSG_message_type', $message_type);
245
-    }
246
-
247
-
248
-    /**
249
-     * Returns the message type object for the set message type on this message
250
-     *
251
-     * @return EE_message_type | null
252
-     */
253
-    public function message_type_object()
254
-    {
255
-        return $this->_message_type;
256
-    }
257
-
258
-
259
-    /**
260
-     * Sets message_type
261
-     *
262
-     * @param EE_message_type $message_type
263
-     * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
-     *                                        the message type or not.
265
-     */
266
-    public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
-    {
268
-        $this->_message_type = $message_type;
269
-        if ($set_priority) {
270
-            $this->set_priority($this->_message_type->get_priority());
271
-        }
272
-    }
273
-
274
-
275
-    /**
276
-     * validates message_type
277
-     *
278
-     * @param bool $throw_exceptions
279
-     * @return bool
280
-     * @throws \EE_Error
281
-     */
282
-    public function valid_message_type($throw_exceptions = false)
283
-    {
284
-        if ($this->_message_type instanceof EE_message_type) {
285
-            return true;
286
-        }
287
-        if ($throw_exceptions) {
288
-            throw new EE_Error(
289
-                sprintf(
290
-                    __(
291
-                        'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
-                        'event_espresso'
293
-                    ),
294
-                    $this->message_type()
295
-                )
296
-            );
297
-        }
298
-        return false;
299
-    }
300
-
301
-
302
-    /**
303
-     * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
-     *
305
-     * @param bool $throw_exceptions
306
-     * @return bool
307
-     * @throws \EE_Error
308
-     */
309
-    public function is_valid($throw_exceptions = false)
310
-    {
311
-        if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
-            return true;
313
-        }
314
-        return false;
315
-    }
316
-
317
-
318
-    /**
319
-     * This validates whether the internal messenger and message type objects are valid for sending.
320
-     * Three checks are done:
321
-     * 1. There is a valid messenger object.
322
-     * 2. There is a valid message type object.
323
-     * 3. The message type object is active for the messenger.
324
-     *
325
-     * @throws EE_Error  But only if $throw_exceptions is set to true.
326
-     * @param bool $throw_exceptions
327
-     * @return bool
328
-     */
329
-    public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
-    {
331
-        $valid = false;
332
-        if ($this->is_valid($throw_exceptions)) {
333
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
334
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
-            $valid = $message_resource_manager->is_message_type_active_for_messenger(
336
-                $this->messenger(),
337
-                $this->message_type()
338
-            );
339
-            if (! $valid && $throw_exceptions) {
340
-                throw new EE_Error(
341
-                    sprintf(
342
-                        __(
343
-                            'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
-                            'event_espresso'
345
-                        ),
346
-                        $this->message_type(),
347
-                        $this->messenger()
348
-                    )
349
-                );
350
-            }
351
-        }
352
-        return $valid;
353
-    }
354
-
355
-
356
-    /**
357
-     * This returns the set localized label for the message type on this message.
358
-     * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
-     * with this message.
360
-     *
361
-     * @param   bool $plural whether to return the plural label or not.
362
-     * @return string
363
-     */
364
-    public function message_type_label($plural = false)
365
-    {
366
-        $label_type = $plural ? 'plural' : 'singular';
367
-        $message_type = $this->message_type_object();
368
-        return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
370
-            : str_replace(
371
-                '_',
372
-                ' ',
373
-                $this->message_type()
374
-            );
375
-    }
376
-
377
-
378
-    /**
379
-     * Gets context
380
-     *
381
-     * @return string
382
-     */
383
-    public function context()
384
-    {
385
-        return $this->get('MSG_context');
386
-    }
387
-
388
-
389
-    /**
390
-     * This returns the corresponding localized label for the given context slug, if possible from installed message
391
-     * types. Otherwise, this will just return the set context slug on this object.
392
-     *
393
-     * @return string
394
-     */
395
-    public function context_label()
396
-    {
397
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
398
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
-        $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
-    }
402
-
403
-
404
-    /**
405
-     * Sets context
406
-     *
407
-     * @param string $context
408
-     */
409
-    public function set_context($context)
410
-    {
411
-        $this->set('MSG_context', $context);
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets recipient_ID
417
-     *
418
-     * @return int
419
-     */
420
-    public function recipient_ID()
421
-    {
422
-        return $this->get('MSG_recipient_ID');
423
-    }
424
-
425
-
426
-    /**
427
-     * Sets recipient_ID
428
-     *
429
-     * @param string $recipient_ID
430
-     */
431
-    public function set_recipient_ID($recipient_ID)
432
-    {
433
-        $this->set('MSG_recipient_ID', $recipient_ID);
434
-    }
435
-
436
-
437
-    /**
438
-     * Gets recipient_type
439
-     *
440
-     * @return string
441
-     */
442
-    public function recipient_type()
443
-    {
444
-        return $this->get('MSG_recipient_type');
445
-    }
446
-
447
-
448
-    /**
449
-     * Return the related object matching the recipient type and ID.
450
-     *
451
-     * @return EE_Base_Class | null
452
-     */
453
-    public function recipient_object()
454
-    {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
-            return null;
457
-        }
458
-
459
-        return $this->get_first_related($this->recipient_type());
460
-    }
461
-
462
-
463
-    /**
464
-     * Sets recipient_type
465
-     *
466
-     * @param string $recipient_type
467
-     */
468
-    public function set_recipient_type($recipient_type)
469
-    {
470
-        $this->set('MSG_recipient_type', $recipient_type);
471
-    }
472
-
473
-
474
-    /**
475
-     * Gets content
476
-     *
477
-     * @return string
478
-     */
479
-    public function content()
480
-    {
481
-        return $this->get('MSG_content');
482
-    }
483
-
484
-
485
-    /**
486
-     * Sets content
487
-     *
488
-     * @param string $content
489
-     */
490
-    public function set_content($content)
491
-    {
492
-        $this->set('MSG_content', $content);
493
-    }
494
-
495
-
496
-    /**
497
-     * Gets subject
498
-     *
499
-     * @return string
500
-     */
501
-    public function subject()
502
-    {
503
-        return $this->get('MSG_subject');
504
-    }
505
-
506
-
507
-    /**
508
-     * Sets subject
509
-     *
510
-     * @param string $subject
511
-     */
512
-    public function set_subject($subject)
513
-    {
514
-        $this->set('MSG_subject', $subject);
515
-    }
516
-
517
-
518
-    /**
519
-     * Gets to
520
-     *
521
-     * @return string
522
-     */
523
-    public function to()
524
-    {
525
-        $to = $this->get('MSG_to');
526
-        return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
-    }
528
-
529
-
530
-    /**
531
-     * Sets to
532
-     *
533
-     * @param string $to
534
-     */
535
-    public function set_to($to)
536
-    {
537
-        $this->set('MSG_to', $to);
538
-    }
539
-
540
-
541
-    /**
542
-     * Gets from
543
-     *
544
-     * @return string
545
-     */
546
-    public function from()
547
-    {
548
-        return $this->get('MSG_from');
549
-    }
550
-
551
-
552
-    /**
553
-     * Sets from
554
-     *
555
-     * @param string $from
556
-     */
557
-    public function set_from($from)
558
-    {
559
-        $this->set('MSG_from', $from);
560
-    }
561
-
562
-
563
-    /**
564
-     * Gets priority
565
-     *
566
-     * @return int
567
-     */
568
-    public function priority()
569
-    {
570
-        return $this->get('MSG_priority');
571
-    }
572
-
573
-
574
-    /**
575
-     * Sets priority
576
-     * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
-     * this method calls the send_now method to verify that.
578
-     *
579
-     * @param int $priority
580
-     */
581
-    public function set_priority($priority)
582
-    {
583
-        $priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
-        parent::set('MSG_priority', $priority);
585
-    }
586
-
587
-
588
-    /**
589
-     * Overrides parent::set method so we can capture any sets for priority.
590
-     *
591
-     * @see parent::set() for phpdocs
592
-     * @param string $field_name
593
-     * @param mixed  $field_value
594
-     * @param bool   $use_default
595
-     * @throws EE_Error
596
-     */
597
-    public function set($field_name, $field_value, $use_default = false)
598
-    {
599
-        if ($field_name === 'MSG_priority') {
600
-            $this->set_priority($field_value);
601
-        }
602
-        parent::set($field_name, $field_value, $use_default);
603
-    }
604
-
605
-
606
-    /**
607
-     * @return bool
608
-     * @throws \EE_Error
609
-     */
610
-    public function send_now()
611
-    {
612
-        $send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
-            : $this->priority();
614
-        return $send_now === EEM_Message::priority_high ? true : false;
615
-    }
616
-
617
-
618
-    /**
619
-     * Gets STS_ID
620
-     *
621
-     * @return string
622
-     */
623
-    public function STS_ID()
624
-    {
625
-        return $this->get('STS_ID');
626
-    }
627
-
628
-
629
-    /**
630
-     * Sets STS_ID
631
-     *
632
-     * @param string $STS_ID
633
-     */
634
-    public function set_STS_ID($STS_ID)
635
-    {
636
-        $this->set('STS_ID', $STS_ID);
637
-    }
638
-
639
-
640
-    /**
641
-     * Gets created
642
-     *
643
-     * @return string
644
-     */
645
-    public function created()
646
-    {
647
-        return $this->get('MSG_created');
648
-    }
649
-
650
-
651
-    /**
652
-     * Sets created
653
-     *
654
-     * @param string $created
655
-     */
656
-    public function set_created($created)
657
-    {
658
-        $this->set('MSG_created', $created);
659
-    }
660
-
661
-
662
-    /**
663
-     * Gets modified
664
-     *
665
-     * @return string
666
-     */
667
-    public function modified()
668
-    {
669
-        return $this->get('MSG_modified');
670
-    }
671
-
672
-
673
-    /**
674
-     * Sets modified
675
-     *
676
-     * @param string $modified
677
-     */
678
-    public function set_modified($modified)
679
-    {
680
-        $this->set('MSG_modified', $modified);
681
-    }
682
-
683
-
684
-    /**
685
-     * Sets generation data for this message.
686
-     *
687
-     * @param mixed $data
688
-     */
689
-    public function set_generation_data($data)
690
-    {
691
-        $this->set_field_or_extra_meta('MSG_generation_data', $data);
692
-    }
693
-
694
-
695
-    /**
696
-     * Returns any set generation data for this message.
697
-     *
698
-     * @return mixed|null
699
-     */
700
-    public function get_generation_data()
701
-    {
702
-        return $this->get_field_or_extra_meta('MSG_generation_data');
703
-    }
704
-
705
-
706
-    /**
707
-     * Gets any error message.
708
-     *
709
-     * @return mixed|null
710
-     */
711
-    public function error_message()
712
-    {
713
-        return $this->get_field_or_extra_meta('MSG_error');
714
-    }
715
-
716
-
717
-    /**
718
-     * Sets an error message.
719
-     *
720
-     * @param $message
721
-     * @return bool|int
722
-     */
723
-    public function set_error_message($message)
724
-    {
725
-        return $this->set_field_or_extra_meta('MSG_error', $message);
726
-    }
727
-
728
-
729
-    /**
730
-     * This retrieves the associated template pack with this message.
731
-     *
732
-     * @return EE_Messages_Template_Pack | null
733
-     */
734
-    public function get_template_pack()
735
-    {
736
-        /**
737
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
-         */
739
-        if (! empty($this->template_pack)) {
740
-            return $this->template_pack;
741
-        }
742
-        /** @type EE_Message_Template_Group $grp */
743
-        $grp = $this->get_first_related('Message_Template_Group');
744
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
746
-            $grp = EEM_Message_Template_Group::instance()->get_one(
747
-                array(
748
-                    array(
749
-                        'MTP_messenger'    => $this->messenger(),
750
-                        'MTP_message_type' => $this->message_type(),
751
-                        'MTP_is_global'    => true,
752
-                    ),
753
-                )
754
-            );
755
-        }
756
-
757
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
-    }
759
-
760
-
761
-    /**
762
-     * Retrieves the variation used for generating this message.
763
-     *
764
-     * @return string
765
-     */
766
-    public function get_template_pack_variation()
767
-    {
768
-        /**
769
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
-         */
771
-        if (! empty($this->template_variation)) {
772
-            return $this->template_variation;
773
-        }
774
-
775
-        /** @type EE_Message_Template_Group $grp */
776
-        $grp = $this->get_first_related('Message_Template_Group');
777
-
778
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
780
-            $grp = EEM_Message_Template_Group::instance()->get_one(
781
-                array(
782
-                    array(
783
-                        'MTP_messenger'    => $this->messenger(),
784
-                        'MTP_message_type' => $this->message_type(),
785
-                        'MTP_is_global'    => true,
786
-                    ),
787
-                )
788
-            );
789
-        }
790
-
791
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
-    }
793
-
794
-    /**
795
-     * Return the link to the admin details for the object.
796
-     *
797
-     * @return string
798
-     */
799
-    public function get_admin_details_link()
800
-    {
801
-        EE_Registry::instance()->load_helper('URL');
802
-        EE_Registry::instance()->load_helper('MSG_Template');
803
-        switch ($this->STS_ID()) {
804
-            case EEM_Message::status_failed:
805
-            case EEM_Message::status_debug_only:
806
-                return EEH_MSG_Template::generate_error_display_trigger($this);
807
-                break;
808
-
809
-            case EEM_Message::status_sent:
810
-                return EEH_MSG_Template::generate_browser_trigger($this);
811
-                break;
812
-
813
-            default:
814
-                return '';
815
-        }
816
-    }
817
-
818
-    /**
819
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
-     *
821
-     * @return string
822
-     */
823
-    public function get_admin_edit_link()
824
-    {
825
-        return $this->get_admin_details_link();
826
-    }
827
-
828
-    /**
829
-     * Returns the link to a settings page for the object.
830
-     *
831
-     * @return string
832
-     */
833
-    public function get_admin_settings_link()
834
-    {
835
-        EE_Registry::instance()->load_helper('URL');
836
-        return EEH_URL::add_query_args_and_nonce(
837
-            array(
838
-                'page'   => 'espresso_messages',
839
-                'action' => 'settings',
840
-            ),
841
-            admin_url('admin.php')
842
-        );
843
-    }
844
-
845
-    /**
846
-     * Returns the link to the "overview" for the object (typically the "list table" view).
847
-     *
848
-     * @return string
849
-     */
850
-    public function get_admin_overview_link()
851
-    {
852
-        EE_Registry::instance()->load_helper('URL');
853
-        return EEH_URL::add_query_args_and_nonce(
854
-            array(
855
-                'page'   => 'espresso_messages',
856
-                'action' => 'default',
857
-            ),
858
-            admin_url('admin.php')
859
-        );
860
-    }
861
-
862
-
863
-    /**
864
-     * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
-     * it.
866
-     * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
-     * status.
868
-     *
869
-     */
870
-    public function set_messenger_is_executing()
871
-    {
872
-        $this->set_STS_ID(EEM_Message::status_messenger_executing);
873
-        $this->set_error_message(
874
-            esc_html__(
875
-                'A message with this status indicates that there was a problem that occurred while the message was being
13
+	/**
14
+	 * @deprecated 4.9.0  Added for backward compat with add-on's
15
+	 * @type null
16
+	 */
17
+	public $template_pack;
18
+
19
+	/**
20
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
21
+	 * @type null
22
+	 */
23
+	public $template_variation;
24
+
25
+	/**
26
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
27
+	 * @type string
28
+	 */
29
+	public $content = '';
30
+
31
+
32
+	/**
33
+	 * @type EE_messenger $_messenger
34
+	 */
35
+	protected $_messenger = null;
36
+
37
+	/**
38
+	 * @type EE_message_type $_message_type
39
+	 */
40
+	protected $_message_type = null;
41
+
42
+
43
+	/**
44
+	 * @param array  $props_n_values
45
+	 * @param string $timezone
46
+	 * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
+	 *                             format.
48
+	 * @return EE_Message
49
+	 */
50
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
+		// if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
+		if (! $has_object) {
55
+			EE_Registry::instance()->load_helper('URL');
56
+			$props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
+		}
58
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
+	}
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values
64
+	 * @param string $timezone
65
+	 * @return EE_Message
66
+	 */
67
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
68
+	{
69
+		return new self($props_n_values, true, $timezone);
70
+	}
71
+
72
+
73
+	/**
74
+	 * Gets MSG_token
75
+	 *
76
+	 * @return int
77
+	 */
78
+	public function MSG_token()
79
+	{
80
+		return $this->get('MSG_token');
81
+	}
82
+
83
+
84
+	/**
85
+	 * Sets MSG_token
86
+	 *
87
+	 * @param int $MSG_token
88
+	 */
89
+	public function set_MSG_token($MSG_token)
90
+	{
91
+		$this->set('MSG_token', $MSG_token);
92
+	}
93
+
94
+
95
+	/**
96
+	 * Gets GRP_ID
97
+	 *
98
+	 * @return int
99
+	 */
100
+	public function GRP_ID()
101
+	{
102
+		return $this->get('GRP_ID');
103
+	}
104
+
105
+
106
+	/**
107
+	 * Sets GRP_ID
108
+	 *
109
+	 * @param int $GRP_ID
110
+	 */
111
+	public function set_GRP_ID($GRP_ID)
112
+	{
113
+		$this->set('GRP_ID', $GRP_ID);
114
+	}
115
+
116
+
117
+	/**
118
+	 * Gets TXN_ID
119
+	 *
120
+	 * @return int
121
+	 */
122
+	public function TXN_ID()
123
+	{
124
+		return $this->get('TXN_ID');
125
+	}
126
+
127
+
128
+	/**
129
+	 * Sets TXN_ID
130
+	 *
131
+	 * @param int $TXN_ID
132
+	 */
133
+	public function set_TXN_ID($TXN_ID)
134
+	{
135
+		$this->set('TXN_ID', $TXN_ID);
136
+	}
137
+
138
+
139
+	/**
140
+	 * Gets messenger
141
+	 *
142
+	 * @return string
143
+	 */
144
+	public function messenger()
145
+	{
146
+		return $this->get('MSG_messenger');
147
+	}
148
+
149
+
150
+	/**
151
+	 * Sets messenger
152
+	 *
153
+	 * @param string $messenger
154
+	 */
155
+	public function set_messenger($messenger)
156
+	{
157
+		$this->set('MSG_messenger', $messenger);
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns corresponding messenger object for the set messenger on this message
163
+	 *
164
+	 * @return EE_messenger | null
165
+	 */
166
+	public function messenger_object()
167
+	{
168
+		return $this->_messenger;
169
+	}
170
+
171
+
172
+	/**
173
+	 * Sets messenger
174
+	 *
175
+	 * @param EE_messenger $messenger
176
+	 */
177
+	public function set_messenger_object(EE_messenger $messenger)
178
+	{
179
+		$this->_messenger = $messenger;
180
+	}
181
+
182
+
183
+	/**
184
+	 * validates messenger
185
+	 *
186
+	 * @param bool $throw_exceptions
187
+	 * @return bool
188
+	 * @throws \EE_Error
189
+	 */
190
+	public function valid_messenger($throw_exceptions = false)
191
+	{
192
+		if ($this->_messenger instanceof EE_messenger) {
193
+			return true;
194
+		}
195
+		if ($throw_exceptions) {
196
+			throw new EE_Error(
197
+				sprintf(
198
+					__(
199
+						'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
+						'event_espresso'
201
+					),
202
+					$this->messenger()
203
+				)
204
+			);
205
+		}
206
+		return false;
207
+	}
208
+
209
+
210
+	/**
211
+	 * This returns the set localized label for the messenger on this message.
212
+	 * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
+	 * with this message.
214
+	 *
215
+	 * @param   bool $plural whether to return the plural label or not.
216
+	 * @return string
217
+	 */
218
+	public function messenger_label($plural = false)
219
+	{
220
+		$label_type = $plural ? 'plural' : 'singular';
221
+		$messenger = $this->messenger_object();
222
+		return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
+	}
224
+
225
+
226
+	/**
227
+	 * Gets message_type
228
+	 *
229
+	 * @return string
230
+	 */
231
+	public function message_type()
232
+	{
233
+		return $this->get('MSG_message_type');
234
+	}
235
+
236
+
237
+	/**
238
+	 * Sets message_type
239
+	 *
240
+	 * @param string $message_type
241
+	 */
242
+	public function set_message_type($message_type)
243
+	{
244
+		$this->set('MSG_message_type', $message_type);
245
+	}
246
+
247
+
248
+	/**
249
+	 * Returns the message type object for the set message type on this message
250
+	 *
251
+	 * @return EE_message_type | null
252
+	 */
253
+	public function message_type_object()
254
+	{
255
+		return $this->_message_type;
256
+	}
257
+
258
+
259
+	/**
260
+	 * Sets message_type
261
+	 *
262
+	 * @param EE_message_type $message_type
263
+	 * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
+	 *                                        the message type or not.
265
+	 */
266
+	public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
+	{
268
+		$this->_message_type = $message_type;
269
+		if ($set_priority) {
270
+			$this->set_priority($this->_message_type->get_priority());
271
+		}
272
+	}
273
+
274
+
275
+	/**
276
+	 * validates message_type
277
+	 *
278
+	 * @param bool $throw_exceptions
279
+	 * @return bool
280
+	 * @throws \EE_Error
281
+	 */
282
+	public function valid_message_type($throw_exceptions = false)
283
+	{
284
+		if ($this->_message_type instanceof EE_message_type) {
285
+			return true;
286
+		}
287
+		if ($throw_exceptions) {
288
+			throw new EE_Error(
289
+				sprintf(
290
+					__(
291
+						'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
+						'event_espresso'
293
+					),
294
+					$this->message_type()
295
+				)
296
+			);
297
+		}
298
+		return false;
299
+	}
300
+
301
+
302
+	/**
303
+	 * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
+	 *
305
+	 * @param bool $throw_exceptions
306
+	 * @return bool
307
+	 * @throws \EE_Error
308
+	 */
309
+	public function is_valid($throw_exceptions = false)
310
+	{
311
+		if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
+			return true;
313
+		}
314
+		return false;
315
+	}
316
+
317
+
318
+	/**
319
+	 * This validates whether the internal messenger and message type objects are valid for sending.
320
+	 * Three checks are done:
321
+	 * 1. There is a valid messenger object.
322
+	 * 2. There is a valid message type object.
323
+	 * 3. The message type object is active for the messenger.
324
+	 *
325
+	 * @throws EE_Error  But only if $throw_exceptions is set to true.
326
+	 * @param bool $throw_exceptions
327
+	 * @return bool
328
+	 */
329
+	public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
+	{
331
+		$valid = false;
332
+		if ($this->is_valid($throw_exceptions)) {
333
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
334
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
+			$valid = $message_resource_manager->is_message_type_active_for_messenger(
336
+				$this->messenger(),
337
+				$this->message_type()
338
+			);
339
+			if (! $valid && $throw_exceptions) {
340
+				throw new EE_Error(
341
+					sprintf(
342
+						__(
343
+							'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
+							'event_espresso'
345
+						),
346
+						$this->message_type(),
347
+						$this->messenger()
348
+					)
349
+				);
350
+			}
351
+		}
352
+		return $valid;
353
+	}
354
+
355
+
356
+	/**
357
+	 * This returns the set localized label for the message type on this message.
358
+	 * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
+	 * with this message.
360
+	 *
361
+	 * @param   bool $plural whether to return the plural label or not.
362
+	 * @return string
363
+	 */
364
+	public function message_type_label($plural = false)
365
+	{
366
+		$label_type = $plural ? 'plural' : 'singular';
367
+		$message_type = $this->message_type_object();
368
+		return $message_type instanceof EE_message_type
369
+			? $message_type->label[ $label_type ]
370
+			: str_replace(
371
+				'_',
372
+				' ',
373
+				$this->message_type()
374
+			);
375
+	}
376
+
377
+
378
+	/**
379
+	 * Gets context
380
+	 *
381
+	 * @return string
382
+	 */
383
+	public function context()
384
+	{
385
+		return $this->get('MSG_context');
386
+	}
387
+
388
+
389
+	/**
390
+	 * This returns the corresponding localized label for the given context slug, if possible from installed message
391
+	 * types. Otherwise, this will just return the set context slug on this object.
392
+	 *
393
+	 * @return string
394
+	 */
395
+	public function context_label()
396
+	{
397
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
398
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
+		$contexts = $message_resource_manager->get_all_contexts();
400
+		return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
+	}
402
+
403
+
404
+	/**
405
+	 * Sets context
406
+	 *
407
+	 * @param string $context
408
+	 */
409
+	public function set_context($context)
410
+	{
411
+		$this->set('MSG_context', $context);
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets recipient_ID
417
+	 *
418
+	 * @return int
419
+	 */
420
+	public function recipient_ID()
421
+	{
422
+		return $this->get('MSG_recipient_ID');
423
+	}
424
+
425
+
426
+	/**
427
+	 * Sets recipient_ID
428
+	 *
429
+	 * @param string $recipient_ID
430
+	 */
431
+	public function set_recipient_ID($recipient_ID)
432
+	{
433
+		$this->set('MSG_recipient_ID', $recipient_ID);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Gets recipient_type
439
+	 *
440
+	 * @return string
441
+	 */
442
+	public function recipient_type()
443
+	{
444
+		return $this->get('MSG_recipient_type');
445
+	}
446
+
447
+
448
+	/**
449
+	 * Return the related object matching the recipient type and ID.
450
+	 *
451
+	 * @return EE_Base_Class | null
452
+	 */
453
+	public function recipient_object()
454
+	{
455
+		if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
+			return null;
457
+		}
458
+
459
+		return $this->get_first_related($this->recipient_type());
460
+	}
461
+
462
+
463
+	/**
464
+	 * Sets recipient_type
465
+	 *
466
+	 * @param string $recipient_type
467
+	 */
468
+	public function set_recipient_type($recipient_type)
469
+	{
470
+		$this->set('MSG_recipient_type', $recipient_type);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Gets content
476
+	 *
477
+	 * @return string
478
+	 */
479
+	public function content()
480
+	{
481
+		return $this->get('MSG_content');
482
+	}
483
+
484
+
485
+	/**
486
+	 * Sets content
487
+	 *
488
+	 * @param string $content
489
+	 */
490
+	public function set_content($content)
491
+	{
492
+		$this->set('MSG_content', $content);
493
+	}
494
+
495
+
496
+	/**
497
+	 * Gets subject
498
+	 *
499
+	 * @return string
500
+	 */
501
+	public function subject()
502
+	{
503
+		return $this->get('MSG_subject');
504
+	}
505
+
506
+
507
+	/**
508
+	 * Sets subject
509
+	 *
510
+	 * @param string $subject
511
+	 */
512
+	public function set_subject($subject)
513
+	{
514
+		$this->set('MSG_subject', $subject);
515
+	}
516
+
517
+
518
+	/**
519
+	 * Gets to
520
+	 *
521
+	 * @return string
522
+	 */
523
+	public function to()
524
+	{
525
+		$to = $this->get('MSG_to');
526
+		return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
+	}
528
+
529
+
530
+	/**
531
+	 * Sets to
532
+	 *
533
+	 * @param string $to
534
+	 */
535
+	public function set_to($to)
536
+	{
537
+		$this->set('MSG_to', $to);
538
+	}
539
+
540
+
541
+	/**
542
+	 * Gets from
543
+	 *
544
+	 * @return string
545
+	 */
546
+	public function from()
547
+	{
548
+		return $this->get('MSG_from');
549
+	}
550
+
551
+
552
+	/**
553
+	 * Sets from
554
+	 *
555
+	 * @param string $from
556
+	 */
557
+	public function set_from($from)
558
+	{
559
+		$this->set('MSG_from', $from);
560
+	}
561
+
562
+
563
+	/**
564
+	 * Gets priority
565
+	 *
566
+	 * @return int
567
+	 */
568
+	public function priority()
569
+	{
570
+		return $this->get('MSG_priority');
571
+	}
572
+
573
+
574
+	/**
575
+	 * Sets priority
576
+	 * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
+	 * this method calls the send_now method to verify that.
578
+	 *
579
+	 * @param int $priority
580
+	 */
581
+	public function set_priority($priority)
582
+	{
583
+		$priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
+		parent::set('MSG_priority', $priority);
585
+	}
586
+
587
+
588
+	/**
589
+	 * Overrides parent::set method so we can capture any sets for priority.
590
+	 *
591
+	 * @see parent::set() for phpdocs
592
+	 * @param string $field_name
593
+	 * @param mixed  $field_value
594
+	 * @param bool   $use_default
595
+	 * @throws EE_Error
596
+	 */
597
+	public function set($field_name, $field_value, $use_default = false)
598
+	{
599
+		if ($field_name === 'MSG_priority') {
600
+			$this->set_priority($field_value);
601
+		}
602
+		parent::set($field_name, $field_value, $use_default);
603
+	}
604
+
605
+
606
+	/**
607
+	 * @return bool
608
+	 * @throws \EE_Error
609
+	 */
610
+	public function send_now()
611
+	{
612
+		$send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
+			: $this->priority();
614
+		return $send_now === EEM_Message::priority_high ? true : false;
615
+	}
616
+
617
+
618
+	/**
619
+	 * Gets STS_ID
620
+	 *
621
+	 * @return string
622
+	 */
623
+	public function STS_ID()
624
+	{
625
+		return $this->get('STS_ID');
626
+	}
627
+
628
+
629
+	/**
630
+	 * Sets STS_ID
631
+	 *
632
+	 * @param string $STS_ID
633
+	 */
634
+	public function set_STS_ID($STS_ID)
635
+	{
636
+		$this->set('STS_ID', $STS_ID);
637
+	}
638
+
639
+
640
+	/**
641
+	 * Gets created
642
+	 *
643
+	 * @return string
644
+	 */
645
+	public function created()
646
+	{
647
+		return $this->get('MSG_created');
648
+	}
649
+
650
+
651
+	/**
652
+	 * Sets created
653
+	 *
654
+	 * @param string $created
655
+	 */
656
+	public function set_created($created)
657
+	{
658
+		$this->set('MSG_created', $created);
659
+	}
660
+
661
+
662
+	/**
663
+	 * Gets modified
664
+	 *
665
+	 * @return string
666
+	 */
667
+	public function modified()
668
+	{
669
+		return $this->get('MSG_modified');
670
+	}
671
+
672
+
673
+	/**
674
+	 * Sets modified
675
+	 *
676
+	 * @param string $modified
677
+	 */
678
+	public function set_modified($modified)
679
+	{
680
+		$this->set('MSG_modified', $modified);
681
+	}
682
+
683
+
684
+	/**
685
+	 * Sets generation data for this message.
686
+	 *
687
+	 * @param mixed $data
688
+	 */
689
+	public function set_generation_data($data)
690
+	{
691
+		$this->set_field_or_extra_meta('MSG_generation_data', $data);
692
+	}
693
+
694
+
695
+	/**
696
+	 * Returns any set generation data for this message.
697
+	 *
698
+	 * @return mixed|null
699
+	 */
700
+	public function get_generation_data()
701
+	{
702
+		return $this->get_field_or_extra_meta('MSG_generation_data');
703
+	}
704
+
705
+
706
+	/**
707
+	 * Gets any error message.
708
+	 *
709
+	 * @return mixed|null
710
+	 */
711
+	public function error_message()
712
+	{
713
+		return $this->get_field_or_extra_meta('MSG_error');
714
+	}
715
+
716
+
717
+	/**
718
+	 * Sets an error message.
719
+	 *
720
+	 * @param $message
721
+	 * @return bool|int
722
+	 */
723
+	public function set_error_message($message)
724
+	{
725
+		return $this->set_field_or_extra_meta('MSG_error', $message);
726
+	}
727
+
728
+
729
+	/**
730
+	 * This retrieves the associated template pack with this message.
731
+	 *
732
+	 * @return EE_Messages_Template_Pack | null
733
+	 */
734
+	public function get_template_pack()
735
+	{
736
+		/**
737
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
+		 */
739
+		if (! empty($this->template_pack)) {
740
+			return $this->template_pack;
741
+		}
742
+		/** @type EE_Message_Template_Group $grp */
743
+		$grp = $this->get_first_related('Message_Template_Group');
744
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
+		if (! $grp instanceof EE_Message_Template_Group) {
746
+			$grp = EEM_Message_Template_Group::instance()->get_one(
747
+				array(
748
+					array(
749
+						'MTP_messenger'    => $this->messenger(),
750
+						'MTP_message_type' => $this->message_type(),
751
+						'MTP_is_global'    => true,
752
+					),
753
+				)
754
+			);
755
+		}
756
+
757
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
+	}
759
+
760
+
761
+	/**
762
+	 * Retrieves the variation used for generating this message.
763
+	 *
764
+	 * @return string
765
+	 */
766
+	public function get_template_pack_variation()
767
+	{
768
+		/**
769
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
+		 */
771
+		if (! empty($this->template_variation)) {
772
+			return $this->template_variation;
773
+		}
774
+
775
+		/** @type EE_Message_Template_Group $grp */
776
+		$grp = $this->get_first_related('Message_Template_Group');
777
+
778
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
+		if (! $grp instanceof EE_Message_Template_Group) {
780
+			$grp = EEM_Message_Template_Group::instance()->get_one(
781
+				array(
782
+					array(
783
+						'MTP_messenger'    => $this->messenger(),
784
+						'MTP_message_type' => $this->message_type(),
785
+						'MTP_is_global'    => true,
786
+					),
787
+				)
788
+			);
789
+		}
790
+
791
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
+	}
793
+
794
+	/**
795
+	 * Return the link to the admin details for the object.
796
+	 *
797
+	 * @return string
798
+	 */
799
+	public function get_admin_details_link()
800
+	{
801
+		EE_Registry::instance()->load_helper('URL');
802
+		EE_Registry::instance()->load_helper('MSG_Template');
803
+		switch ($this->STS_ID()) {
804
+			case EEM_Message::status_failed:
805
+			case EEM_Message::status_debug_only:
806
+				return EEH_MSG_Template::generate_error_display_trigger($this);
807
+				break;
808
+
809
+			case EEM_Message::status_sent:
810
+				return EEH_MSG_Template::generate_browser_trigger($this);
811
+				break;
812
+
813
+			default:
814
+				return '';
815
+		}
816
+	}
817
+
818
+	/**
819
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
+	 *
821
+	 * @return string
822
+	 */
823
+	public function get_admin_edit_link()
824
+	{
825
+		return $this->get_admin_details_link();
826
+	}
827
+
828
+	/**
829
+	 * Returns the link to a settings page for the object.
830
+	 *
831
+	 * @return string
832
+	 */
833
+	public function get_admin_settings_link()
834
+	{
835
+		EE_Registry::instance()->load_helper('URL');
836
+		return EEH_URL::add_query_args_and_nonce(
837
+			array(
838
+				'page'   => 'espresso_messages',
839
+				'action' => 'settings',
840
+			),
841
+			admin_url('admin.php')
842
+		);
843
+	}
844
+
845
+	/**
846
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
847
+	 *
848
+	 * @return string
849
+	 */
850
+	public function get_admin_overview_link()
851
+	{
852
+		EE_Registry::instance()->load_helper('URL');
853
+		return EEH_URL::add_query_args_and_nonce(
854
+			array(
855
+				'page'   => 'espresso_messages',
856
+				'action' => 'default',
857
+			),
858
+			admin_url('admin.php')
859
+		);
860
+	}
861
+
862
+
863
+	/**
864
+	 * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
+	 * it.
866
+	 * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
+	 * status.
868
+	 *
869
+	 */
870
+	public function set_messenger_is_executing()
871
+	{
872
+		$this->set_STS_ID(EEM_Message::status_messenger_executing);
873
+		$this->set_error_message(
874
+			esc_html__(
875
+				'A message with this status indicates that there was a problem that occurred while the message was being
876 876
                 processed by the messenger.  It is still possible that the message was sent successfully, but at some
877 877
                 point during the processing there was a failure.  This usually is indicative of a timeout issue with PHP 
878 878
                 or memory limits being reached.  If you see this repeatedly you may want to consider upgrading the memory 
879 879
                 available to PHP on your server.',
880
-                'event_espresso'
881
-            )
882
-        );
883
-    }
880
+				'event_espresso'
881
+			)
882
+		);
883
+	}
884 884
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
     {
52 52
         $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53 53
         // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
54
+        if ( ! $has_object) {
55 55
             EE_Registry::instance()->load_helper('URL');
56 56
             $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57 57
         }
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     {
220 220
         $label_type = $plural ? 'plural' : 'singular';
221 221
         $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
222
+        return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
223 223
     }
224 224
 
225 225
 
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
                 $this->messenger(),
337 337
                 $this->message_type()
338 338
             );
339
-            if (! $valid && $throw_exceptions) {
339
+            if ( ! $valid && $throw_exceptions) {
340 340
                 throw new EE_Error(
341 341
                     sprintf(
342 342
                         __(
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
         $label_type = $plural ? 'plural' : 'singular';
367 367
         $message_type = $this->message_type_object();
368 368
         return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
369
+            ? $message_type->label[$label_type]
370 370
             : str_replace(
371 371
                 '_',
372 372
                 ' ',
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
         /** @type EE_Message_Resource_Manager $message_resource_manager */
398 398
         $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399 399
         $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
400
+        return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
401 401
     }
402 402
 
403 403
 
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
      */
453 453
     public function recipient_object()
454 454
     {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
455
+        if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
456 456
             return null;
457 457
         }
458 458
 
@@ -736,13 +736,13 @@  discard block
 block discarded – undo
736 736
         /**
737 737
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738 738
          */
739
-        if (! empty($this->template_pack)) {
739
+        if ( ! empty($this->template_pack)) {
740 740
             return $this->template_pack;
741 741
         }
742 742
         /** @type EE_Message_Template_Group $grp */
743 743
         $grp = $this->get_first_related('Message_Template_Group');
744 744
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
745
+        if ( ! $grp instanceof EE_Message_Template_Group) {
746 746
             $grp = EEM_Message_Template_Group::instance()->get_one(
747 747
                 array(
748 748
                     array(
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         /**
769 769
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770 770
          */
771
-        if (! empty($this->template_variation)) {
771
+        if ( ! empty($this->template_variation)) {
772 772
             return $this->template_variation;
773 773
         }
774 774
 
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
         $grp = $this->get_first_related('Message_Template_Group');
777 777
 
778 778
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
779
+        if ( ! $grp instanceof EE_Message_Template_Group) {
780 780
             $grp = EEM_Message_Template_Group::instance()->get_one(
781 781
                 array(
782 782
                     array(
Please login to merge, or discard this patch.
core/db_classes/EE_CSV.class.php 2 patches
Indentation   +669 added lines, -669 removed lines patch added patch discarded remove patch
@@ -16,673 +16,673 @@
 block discarded – undo
16 16
 class EE_CSV
17 17
 {
18 18
 
19
-    // instance of the EE_CSV object
20
-    private static $_instance = null;
21
-
22
-
23
-    // multidimensional array to store update & error messages
24
-    // var $_notices = array( 'updates' => array(), 'errors' => array() );
25
-
26
-
27
-    private $_primary_keys;
28
-
29
-    /**
30
-     *
31
-     * @var EE_Registry
32
-     */
33
-    private $EE;
34
-    /**
35
-     * string used for 1st cell in exports, which indicates that the following 2 rows will be metadata keys and values
36
-     */
37
-    const metadata_header = 'Event Espresso Export Meta Data';
38
-
39
-    /**
40
-     *        private constructor to prevent direct creation
41
-     *
42
-     * @Constructor
43
-     * @access private
44
-     * @return void
45
-     */
46
-    private function __construct()
47
-    {
48
-        global $wpdb;
49
-
50
-        $this->_primary_keys = array(
51
-            $wpdb->prefix . 'esp_answer'                  => array('ANS_ID'),
52
-            $wpdb->prefix . 'esp_attendee'                => array('ATT_ID'),
53
-            $wpdb->prefix . 'esp_datetime'                => array('DTT_ID'),
54
-            $wpdb->prefix . 'esp_event_question_group'    => array('EQG_ID'),
55
-            $wpdb->prefix . 'esp_message_template'        => array('MTP_ID'),
56
-            $wpdb->prefix . 'esp_payment'                 => array('PAY_ID'),
57
-            $wpdb->prefix . 'esp_price'                   => array('PRC_ID'),
58
-            $wpdb->prefix . 'esp_price_type'              => array('PRT_ID'),
59
-            $wpdb->prefix . 'esp_question'                => array('QST_ID'),
60
-            $wpdb->prefix . 'esp_question_group'          => array('QSG_ID'),
61
-            $wpdb->prefix . 'esp_question_group_question' => array('QGQ_ID'),
62
-            $wpdb->prefix . 'esp_question_option'         => array('QSO_ID'),
63
-            $wpdb->prefix . 'esp_registration'            => array('REG_ID'),
64
-            $wpdb->prefix . 'esp_status'                  => array('STS_ID'),
65
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
66
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
67
-            $wpdb->prefix . 'events_detail'               => array('id'),
68
-            $wpdb->prefix . 'events_category_detail'      => array('id'),
69
-            $wpdb->prefix . 'events_category_rel'         => array('id'),
70
-            $wpdb->prefix . 'events_venue'                => array('id'),
71
-            $wpdb->prefix . 'events_venue_rel'            => array('emeta_id'),
72
-            $wpdb->prefix . 'events_locale'               => array('id'),
73
-            $wpdb->prefix . 'events_locale_rel'           => array('id'),
74
-            $wpdb->prefix . 'events_personnel'            => array('id'),
75
-            $wpdb->prefix . 'events_personnel_rel'        => array('id'),
76
-        );
77
-    }
78
-
79
-
80
-    /**
81
-     *        @ singleton method used to instantiate class object
82
-     *        @ access public
83
-     *
84
-     * @return EE_CSV
85
-     */
86
-    public static function instance()
87
-    {
88
-        // check if class object is instantiated
89
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_CSV)) {
90
-            self::$_instance = new self();
91
-        }
92
-        return self::$_instance;
93
-    }
94
-
95
-    /**
96
-     * Opens a unicode or utf file (normal file_get_contents has difficulty readin ga unicode file. @see
97
-     * http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
98
-     *
99
-     * @param string $file_path
100
-     * @return string
101
-     * @throws EE_Error
102
-     */
103
-    private function read_unicode_file($file_path)
104
-    {
105
-        $fc = "";
106
-        $fh = fopen($file_path, "rb");
107
-        if (! $fh) {
108
-            throw new EE_Error(sprintf(__("Cannot open file for read: %s<br>\n", 'event_espresso'), $file_path));
109
-        }
110
-        $flen = filesize($file_path);
111
-        $bc = fread($fh, $flen);
112
-        for ($i = 0; $i < $flen; $i++) {
113
-            $c = substr($bc, $i, 1);
114
-            if ((ord($c) != 0) && (ord($c) != 13)) {
115
-                $fc = $fc . $c;
116
-            }
117
-        }
118
-        if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
119
-            $fc = substr($fc, 2);
120
-        }
121
-        return ($fc);
122
-    }
123
-
124
-
125
-    /**
126
-     * Generic CSV-functionality to turn an entire CSV file into a single array that's
127
-     * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
128
-     * representing each row in the CSV file, and the second-level arrays being each column in that row
129
-     *
130
-     * @param string $path_to_file
131
-     * @return array of arrays. Top-level array has rows, second-level array has each item
132
-     */
133
-    public function import_csv_to_multi_dimensional_array($path_to_file)
134
-    {
135
-        // needed to deal with Mac line endings
136
-        ini_set('auto_detect_line_endings', true);
137
-
138
-        // because fgetcsv does not correctly deal with backslashed quotes such as \"
139
-        // we'll read the file into a string
140
-        $file_contents = $this->read_unicode_file($path_to_file);
141
-        // replace backslashed quotes with CSV enclosures
142
-        $file_contents = str_replace('\\"', '"""', $file_contents);
143
-        // HEY YOU! PUT THAT FILE BACK!!!
144
-        file_put_contents($path_to_file, $file_contents);
145
-
146
-        if (($file_handle = fopen($path_to_file, "r")) !== false) {
147
-            # Set the parent multidimensional array key to 0.
148
-            $nn = 0;
149
-            $csvarray = array();
150
-
151
-            // in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions of fgetcsv choke if passed more than 4 - is that crazy or what?
152
-            if (version_compare(PHP_VERSION, '5.3.0') < 0) {
153
-                //  PHP 5.2- version
154
-                // loop through each row of the file
155
-                while (($data = fgetcsv($file_handle, 0, ',', '"')) !== false) {
156
-                    $csvarray[] = $data;
157
-                }
158
-            } else {
159
-                // loop through each row of the file
160
-                while (($data = fgetcsv($file_handle, 0, ',', '"', '\\')) !== false) {
161
-                    $csvarray[] = $data;
162
-                }
163
-            }
164
-            # Close the File.
165
-            fclose($file_handle);
166
-            return $csvarray;
167
-        } else {
168
-            EE_Error::add_error(
169
-                sprintf(__("An error occurred - the file: %s could not opened.", "event_espresso"), $path_to_file),
170
-                __FILE__,
171
-                __FUNCTION__,
172
-                __LINE__
173
-            );
174
-            return false;
175
-        }
176
-    }
177
-
178
-
179
-    /**
180
-     * @Import contents of csv file and store values in an array to be manipulated by other functions
181
-     * @access public
182
-     * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
183
-     *                                      If $model_name is provided, assumes that each row in the CSV represents a
184
-     *                                      model object for that model If $model_name ISN'T provided, assumes that
185
-     *                                      before model object data, there is a row where the first entry is simply
186
-     *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
187
-     *                                      then maybe a row of headers, and then the model data. Eg.
188
-     *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
189
-     *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
190
-     *                                      Forest
191
-     * @param string  $model_name           model name if we know what model we're importing
192
-     * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
193
-     *                                      data
194
-     * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
195
-     *               error message like the following array('Event'=>array( array('EVT_ID'=>1,'EVT_name'=>'bob
196
-     *               party',...), array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
197
-     *                                      ...
198
-     *                                      )
199
-     *                                      'Venue'=>array(
200
-     *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
201
-     *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
202
-     *                                      ...
203
-     *                                      )
204
-     *                                      ...
205
-     *                                      )
206
-     */
207
-    public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
208
-    {
209
-        $multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
210
-        if (! $multi_dimensional_array) {
211
-            return false;
212
-        }
213
-        // gotta start somewhere
214
-        $row = 1;
215
-        // array to store csv data in
216
-        $ee_formatted_data = array();
217
-        // array to store headers (column names)
218
-        $headers = array();
219
-        foreach ($multi_dimensional_array as $data) {
220
-            // if first cell is MODEL, then second cell is the MODEL name
221
-            if ($data[0] == 'MODEL') {
222
-                $model_name = $data[1];
223
-                // don't bother looking for model data in this row. The rest of this
224
-                // row should be blank
225
-                // AND pretend this is the first row again
226
-                $row = 1;
227
-                // reset headers
228
-                $headers = array();
229
-                continue;
230
-            }
231
-            if (strpos($data[0], EE_CSV::metadata_header) !== false) {
232
-                $model_name = EE_CSV::metadata_header;
233
-                // store like model data, we just won't try importing it etc.
234
-                $row = 1;
235
-                continue;
236
-            }
237
-
238
-
239
-            // how many columns are there?
240
-            $columns = count($data);
241
-
242
-            $model_entry = array();
243
-            // loop through each column
244
-            for ($i = 0; $i < $columns; $i++) {
245
-                // replace csv_enclosures with backslashed quotes
246
-                $data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
247
-                // do we need to grab the column names?
248
-                if ($row === 1) {
249
-                    if ($first_row_is_headers) {
250
-                        // store the column names to use for keys
251
-                        $column_name = $data[ $i ];
252
-                        // check it's not blank... sometimes CSV editign programs adda bunch of empty columns onto the end...
253
-                        if (! $column_name) {
254
-                            continue;
255
-                        }
256
-                        $matches = array();
257
-                        if ($model_name == EE_CSV::metadata_header) {
258
-                            $headers[ $i ] = $column_name;
259
-                        } else {
260
-                            // now get the db table name from it (the part between square brackets)
261
-                            $success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
262
-                            if (! $success) {
263
-                                EE_Error::add_error(
264
-                                    sprintf(
265
-                                        __(
266
-                                            "The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
267
-                                            "event_espresso"
268
-                                        ),
269
-                                        $column_name,
270
-                                        implode(",", $data)
271
-                                    ),
272
-                                    __FILE__,
273
-                                    __FUNCTION__,
274
-                                    __LINE__
275
-                                );
276
-                                return false;
277
-                            }
278
-                            $headers[ $i ] = $matches[2];
279
-                        }
280
-                    } else {
281
-                        // no column names means our final array will just use counters for keys
282
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
283
-                        $headers[ $i ] = $i;
284
-                    }
285
-                    // and we need to store csv data
286
-                } else {
287
-                    // this column isn' ta header, store it if there is a header for it
288
-                    if (isset($headers[ $i ])) {
289
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
290
-                    }
291
-                }
292
-            }
293
-            // save the row's data IF it's a non-header-row
294
-            if (! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
295
-                $ee_formatted_data[ $model_name ][] = $model_entry;
296
-            }
297
-            // advance to next row
298
-            $row++;
299
-        }
300
-
301
-        // delete the uploaded file
302
-        unlink($path_to_file);
303
-        // echo '<pre style="height:auto;border:2px solid lightblue;">' . print_r( $ee_formatted_data, TRUE ) . '</pre><br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>';
304
-        // die();
305
-
306
-        // it's good to give back
307
-        return $ee_formatted_data;
308
-    }
309
-
310
-
311
-    public function save_csv_to_db($csv_data_array, $model_name = false)
312
-    {
313
-        EE_Error::doing_it_wrong(
314
-            'save_csv_to_db',
315
-            __(
316
-                'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
317
-                'event_espresso'
318
-            ),
319
-            '4.6.7'
320
-        );
321
-        return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
322
-    }
323
-
324
-    /**
325
-     * Sends HTTP headers to indicate that the browser should download a file,
326
-     * and starts writing the file to PHP's output. Returns the file handle so other functions can
327
-     * also write to it
328
-     *
329
-     * @param string $new_filename the name of the file that the user will download
330
-     * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
331
-     */
332
-    public function begin_sending_csv($filename)
333
-    {
334
-        // grab file extension
335
-        $ext = substr(strrchr($filename, '.'), 1);
336
-        if ($ext == '.csv' or $ext == '.xls') {
337
-            str_replace($ext, '', $filename);
338
-        }
339
-        $filename .= '.csv';
340
-
341
-        // if somebody's been naughty and already started outputting stuff, trash it
342
-        // and start writing our stuff.
343
-        if (ob_get_length()) {
344
-            @ob_flush();
345
-            @flush();
346
-            @ob_end_flush();
347
-        }
348
-        @ob_start();
349
-        header("Pragma: public");
350
-        header("Expires: 0");
351
-        header("Pragma: no-cache");
352
-        header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
353
-        // header("Content-Type: application/force-download");
354
-        // header("Content-Type: application/octet-stream");
355
-        // header("Content-Type: application/download");
356
-        header('Content-disposition: attachment; filename=' . $filename);
357
-        header("Content-Type: text/csv; charset=utf-8");
358
-        do_action('AHEE__EE_CSV__begin_sending_csv__headers');
359
-        echo apply_filters(
360
-            'FHEE__EE_CSV__begin_sending_csv__start_writing',
361
-            "\xEF\xBB\xBF"
362
-        ); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
363
-        $fh = fopen('php://output', 'w');
364
-        return $fh;
365
-    }
366
-
367
-    /**
368
-     * Writes some meta data to the CSV as a bunch of columns. Initially we're only
369
-     * mentioning the version and timezone
370
-     *
371
-     * @param resource $filehandle
372
-     */
373
-    public function write_metadata_to_csv($filehandle)
374
-    {
375
-        $data_row = array(EE_CSV::metadata_header);// do NOT translate because this exact string is used when importing
376
-        $this->fputcsv2($filehandle, $data_row);
377
-        $meta_data = array(
378
-            0 => array(
379
-                'version'        => espresso_version(),
380
-                'timezone'       => EEH_DTT_Helper::get_timezone(),
381
-                'time_of_export' => current_time('mysql'),
382
-                'site_url'       => site_url(),
383
-            ),
384
-        );
385
-        $this->write_data_array_to_csv($filehandle, $meta_data);
386
-    }
387
-
388
-
389
-    /**
390
-     * Writes $data to the csv file open in $filehandle. uses the array indices of $data for column headers
391
-     *
392
-     * @param array   $data                 2D array, first numerically-indexed, and next-level-down preferably indexed
393
-     *                                      by string
394
-     * @param boolean $add_csv_column_names whether or not we should add the keys in the bottom-most array as a row for
395
-     *                                      headers in the CSV. Eg, if $data looked like
396
-     *                                      array(0=>array('EVT_ID'=>1,'EVT_name'=>'monkey'...), 1=>array(...),...))
397
-     *                                      then the first row we'd write to the CSV would be "EVT_ID,EVT_name,..."
398
-     * @return boolean if we successfully wrote to the CSV or not. If there's no $data, we consider that a success
399
-     *                 (because we wrote everything there was...nothing)
400
-     */
401
-    public function write_data_array_to_csv($filehandle, $data)
402
-    {
403
-
404
-
405
-        // determine if $data is actually a 2d array
406
-        if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
407
-            // make sure top level is numerically indexed,
408
-
409
-            if (EEH_Array::is_associative_array($data)) {
410
-                throw new EE_Error(
411
-                    sprintf(
412
-                        __(
413
-                            "top-level array must be numerically indexed. Does these look like numbers to you? %s",
414
-                            "event_espresso"
415
-                        ),
416
-                        implode(",", array_keys($data))
417
-                    )
418
-                );
419
-            }
420
-            $item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
421
-            // now, is the last item in the top-level array of $data an associative or numeric array?
422
-            if (EEH_Array::is_associative_array($item_in_top_level_array)) {
423
-                // its associative, so we want to output its keys as column headers
424
-                $keys = array_keys($item_in_top_level_array);
425
-                echo $this->fputcsv2($filehandle, $keys);
426
-            }
427
-            // start writing data
428
-            foreach ($data as $data_row) {
429
-                echo $this->fputcsv2($filehandle, $data_row);
430
-            }
431
-            return true;
432
-        } else {
433
-            // no data TO write... so we can assume that's a success
434
-            return true;
435
-        }
436
-        // //if 2nd level is indexed by strings, use those as csv column headers (ie, the first row)
437
-        //
438
-        //
439
-        // $no_table = TRUE;
440
-        //
441
-        // // loop through data and add each row to the file/stream as csv
442
-        // foreach ( $data as $model_name => $model_data ) {
443
-        // // test first row to see if it is data or a model name
444
-        // $model = EE_Registry::instance();->load_model($model_name);
445
-        // //if the model really exists,
446
-        // if ( $model ) {
447
-        //
448
-        // // we have a table name
449
-        // $no_table = FALSE;
450
-        //
451
-        // // put the tablename into an array cuz that's how fputcsv rolls
452
-        // $model_name_row = array( 'MODEL', $model_name );
453
-        //
454
-        // // add table name to csv output
455
-        // echo self::fputcsv2($filehandle, $model_name_row);
456
-        //
457
-        // // now get the rest of the data
458
-        // foreach ( $model_data as $row ) {
459
-        // // output the row
460
-        // echo self::fputcsv2($filehandle, $row);
461
-        // }
462
-        //
463
-        // }
464
-        //
465
-        // if ( $no_table ) {
466
-        // // no table so just put the data
467
-        // echo self::fputcsv2($filehandle, $model_data);
468
-        // }
469
-        //
470
-        // } // END OF foreach ( $data )
471
-    }
472
-
473
-    /**
474
-     * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
475
-     * Calls exit to prevent polluting the CSV file with other junk
476
-     *
477
-     * @param resource $fh filehandle where we're writing the CSV to
478
-     */
479
-    public function end_sending_csv($fh)
480
-    {
481
-        fclose($fh);
482
-        exit(0);
483
-    }
484
-
485
-    /**
486
-     * Given an open file, writes all the model data to it in the format the importer expects.
487
-     * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($filehandle).
488
-     *
489
-     * @param resource $filehandle
490
-     * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
491
-     *                                   next layer is numerically indexed to represent each model object (eg, each
492
-     *                                   individual event), and the last layer has all the attributes o fthat model
493
-     *                                   object (eg, the event's id, name, etc)
494
-     * @return boolean success
495
-     */
496
-    public function write_model_data_to_csv($filehandle, $model_data_array)
497
-    {
498
-        $this->write_metadata_to_csv($filehandle);
499
-        foreach ($model_data_array as $model_name => $model_instance_arrays) {
500
-            // first: output a special row stating the model
501
-            echo $this->fputcsv2($filehandle, array('MODEL', $model_name));
502
-            // if we have items to put in the CSV, do it normally
503
-
504
-            if (! empty($model_instance_arrays)) {
505
-                $this->write_data_array_to_csv($filehandle, $model_instance_arrays);
506
-            } else {
507
-                // echo "no data to write... so just write the headers";
508
-                // so there's actually NO model objects for that model.
509
-                // probably still want to show the columns
510
-                $model = EE_Registry::instance()->load_model($model_name);
511
-                $column_names = array();
512
-                foreach ($model->field_settings() as $field) {
513
-                    $column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
514
-                }
515
-                $this->write_data_array_to_csv($filehandle, array($column_names));
516
-            }
517
-        }
518
-    }
519
-
520
-    /**
521
-     * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
522
-     * and dies (in order to avoid other plugins from messing up the csv output)
523
-     *
524
-     * @param string $filename         the filename you want to give the file
525
-     * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
526
-     * @return bool | void writes CSV file to output and dies
527
-     */
528
-    public function export_multiple_model_data_to_csv($filename, $model_data_array)
529
-    {
530
-        $filehandle = $this->begin_sending_csv($filename);
531
-        $this->write_model_data_to_csv($filehandle, $model_data_array);
532
-        $this->end_sending_csv($filehandle);
533
-    }
534
-
535
-    /**
536
-     * @Export contents of an array to csv file
537
-     * @access public
538
-     * @param array  $data     - the array of data to be converted to csv and exported
539
-     * @param string $filename - name for newly created csv file
540
-     * @return TRUE on success, FALSE on fail
541
-     */
542
-    public function export_array_to_csv($data = false, $filename = false)
543
-    {
544
-
545
-        // no data file?? get outta here
546
-        if (! $data or ! is_array($data) or empty($data)) {
547
-            return false;
548
-        }
549
-
550
-        // no filename?? get outta here
551
-        if (! $filename) {
552
-            return false;
553
-        }
554
-
555
-
556
-        // somebody told me i might need this ???
557
-        global $wpdb;
558
-        $prefix = $wpdb->prefix;
559
-
560
-
561
-        $fh = $this->begin_sending_csv($filename);
562
-
563
-
564
-        $this->end_sending_csv($fh);
565
-    }
566
-
567
-
568
-    /**
569
-     * @Determine the maximum upload file size based on php.ini settings
570
-     * @access    public
571
-     * @param int $percent_of_max - desired percentage of the max upload_mb
572
-     * @return int KB
573
-     */
574
-    public function get_max_upload_size($percent_of_max = false)
575
-    {
576
-
577
-        $max_upload = (int) (ini_get('upload_max_filesize'));
578
-        $max_post = (int) (ini_get('post_max_size'));
579
-        $memory_limit = (int) (ini_get('memory_limit'));
580
-
581
-        // determine the smallest of the three values from above
582
-        $upload_mb = min($max_upload, $max_post, $memory_limit);
583
-
584
-        // convert MB to KB
585
-        $upload_mb = $upload_mb * 1024;
586
-
587
-        // don't want the full monty? then reduce the max uplaod size
588
-        if ($percent_of_max) {
589
-            // is percent_of_max like this -> 50 or like this -> 0.50 ?
590
-            if ($percent_of_max > 1) {
591
-                // chnages 50 to 0.50
592
-                $percent_of_max = $percent_of_max / 100;
593
-            }
594
-            // make upload_mb a percentage of the max upload_mb
595
-            $upload_mb = $upload_mb * $percent_of_max;
596
-        }
597
-
598
-        return $upload_mb;
599
-    }
600
-
601
-
602
-    /**
603
-     * @Drop   in replacement for PHP's fputcsv function - but this one works!!!
604
-     * @access private
605
-     * @param resource $fh         - file handle - what we are writing to
606
-     * @param array    $row        - individual row of csv data
607
-     * @param string   $delimiter  - csv delimiter
608
-     * @param string   $enclosure  - csv enclosure
609
-     * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
610
-     * @return void
611
-     */
612
-    private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
613
-    {
614
-        // Allow user to filter the csv delimiter and enclosure for other countries csv standards
615
-        $delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
616
-        $enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
617
-
618
-        $delimiter_esc = preg_quote($delimiter, '/');
619
-        $enclosure_esc = preg_quote($enclosure, '/');
620
-
621
-        $output = array();
622
-        foreach ($row as $field_value) {
623
-            if (is_object($field_value) || is_array($field_value)) {
624
-                $field_value = serialize($field_value);
625
-            }
626
-            if ($field_value === null && $mysql_null) {
627
-                $output[] = 'NULL';
628
-                continue;
629
-            }
630
-
631
-            $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
632
-                ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
633
-                : $field_value;
634
-        }
635
-
636
-        fwrite($fh, join($delimiter, $output) . PHP_EOL);
637
-    }
638
-
639
-
640
-    // /**
641
-    //  * @CSV    Import / Export messages
642
-    //  * @access public
643
-    //  * @return void
644
-    //  */
645
-    // public function csv_admin_notices()
646
-    // {
647
-    //
648
-    //     // We play both kinds of music here! Country AND Western! - err... I mean, cycle through both types of notices
649
-    //     foreach (array('updates', 'errors') as $type) {
650
-    //
651
-    //         // if particular notice type is not empty, then "You've got Mail"
652
-    //         if (! empty($this->_notices[ $type ])) {
653
-    //
654
-    //             // is it an update or an error ?
655
-    //             $msg_class = $type == 'updates' ? 'updated' : 'error';
656
-    //             echo '<div id="message" class="' . $msg_class . '">';
657
-    //             // display each notice, however many that may be
658
-    //             foreach ($this->_notices[ $type ] as $message) {
659
-    //                 echo '<p>' . $message . '</p>';
660
-    //             }
661
-    //             // wrap it up
662
-    //             echo '</div>';
663
-    //         }
664
-    //     }
665
-    // }
666
-
667
-    /**
668
-     * Gets the date format to use in teh csv. filterable
669
-     *
670
-     * @param string $current_format
671
-     * @return string
672
-     */
673
-    public function get_date_format_for_csv($current_format = null)
674
-    {
675
-        return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
676
-    }
677
-
678
-    /**
679
-     * Gets the time format we want to use in CSV reports. Filterable
680
-     *
681
-     * @param string $current_format
682
-     * @return string
683
-     */
684
-    public function get_time_format_for_csv($current_format = null)
685
-    {
686
-        return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
687
-    }
19
+	// instance of the EE_CSV object
20
+	private static $_instance = null;
21
+
22
+
23
+	// multidimensional array to store update & error messages
24
+	// var $_notices = array( 'updates' => array(), 'errors' => array() );
25
+
26
+
27
+	private $_primary_keys;
28
+
29
+	/**
30
+	 *
31
+	 * @var EE_Registry
32
+	 */
33
+	private $EE;
34
+	/**
35
+	 * string used for 1st cell in exports, which indicates that the following 2 rows will be metadata keys and values
36
+	 */
37
+	const metadata_header = 'Event Espresso Export Meta Data';
38
+
39
+	/**
40
+	 *        private constructor to prevent direct creation
41
+	 *
42
+	 * @Constructor
43
+	 * @access private
44
+	 * @return void
45
+	 */
46
+	private function __construct()
47
+	{
48
+		global $wpdb;
49
+
50
+		$this->_primary_keys = array(
51
+			$wpdb->prefix . 'esp_answer'                  => array('ANS_ID'),
52
+			$wpdb->prefix . 'esp_attendee'                => array('ATT_ID'),
53
+			$wpdb->prefix . 'esp_datetime'                => array('DTT_ID'),
54
+			$wpdb->prefix . 'esp_event_question_group'    => array('EQG_ID'),
55
+			$wpdb->prefix . 'esp_message_template'        => array('MTP_ID'),
56
+			$wpdb->prefix . 'esp_payment'                 => array('PAY_ID'),
57
+			$wpdb->prefix . 'esp_price'                   => array('PRC_ID'),
58
+			$wpdb->prefix . 'esp_price_type'              => array('PRT_ID'),
59
+			$wpdb->prefix . 'esp_question'                => array('QST_ID'),
60
+			$wpdb->prefix . 'esp_question_group'          => array('QSG_ID'),
61
+			$wpdb->prefix . 'esp_question_group_question' => array('QGQ_ID'),
62
+			$wpdb->prefix . 'esp_question_option'         => array('QSO_ID'),
63
+			$wpdb->prefix . 'esp_registration'            => array('REG_ID'),
64
+			$wpdb->prefix . 'esp_status'                  => array('STS_ID'),
65
+			$wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
66
+			$wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
67
+			$wpdb->prefix . 'events_detail'               => array('id'),
68
+			$wpdb->prefix . 'events_category_detail'      => array('id'),
69
+			$wpdb->prefix . 'events_category_rel'         => array('id'),
70
+			$wpdb->prefix . 'events_venue'                => array('id'),
71
+			$wpdb->prefix . 'events_venue_rel'            => array('emeta_id'),
72
+			$wpdb->prefix . 'events_locale'               => array('id'),
73
+			$wpdb->prefix . 'events_locale_rel'           => array('id'),
74
+			$wpdb->prefix . 'events_personnel'            => array('id'),
75
+			$wpdb->prefix . 'events_personnel_rel'        => array('id'),
76
+		);
77
+	}
78
+
79
+
80
+	/**
81
+	 *        @ singleton method used to instantiate class object
82
+	 *        @ access public
83
+	 *
84
+	 * @return EE_CSV
85
+	 */
86
+	public static function instance()
87
+	{
88
+		// check if class object is instantiated
89
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_CSV)) {
90
+			self::$_instance = new self();
91
+		}
92
+		return self::$_instance;
93
+	}
94
+
95
+	/**
96
+	 * Opens a unicode or utf file (normal file_get_contents has difficulty readin ga unicode file. @see
97
+	 * http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
98
+	 *
99
+	 * @param string $file_path
100
+	 * @return string
101
+	 * @throws EE_Error
102
+	 */
103
+	private function read_unicode_file($file_path)
104
+	{
105
+		$fc = "";
106
+		$fh = fopen($file_path, "rb");
107
+		if (! $fh) {
108
+			throw new EE_Error(sprintf(__("Cannot open file for read: %s<br>\n", 'event_espresso'), $file_path));
109
+		}
110
+		$flen = filesize($file_path);
111
+		$bc = fread($fh, $flen);
112
+		for ($i = 0; $i < $flen; $i++) {
113
+			$c = substr($bc, $i, 1);
114
+			if ((ord($c) != 0) && (ord($c) != 13)) {
115
+				$fc = $fc . $c;
116
+			}
117
+		}
118
+		if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
119
+			$fc = substr($fc, 2);
120
+		}
121
+		return ($fc);
122
+	}
123
+
124
+
125
+	/**
126
+	 * Generic CSV-functionality to turn an entire CSV file into a single array that's
127
+	 * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
128
+	 * representing each row in the CSV file, and the second-level arrays being each column in that row
129
+	 *
130
+	 * @param string $path_to_file
131
+	 * @return array of arrays. Top-level array has rows, second-level array has each item
132
+	 */
133
+	public function import_csv_to_multi_dimensional_array($path_to_file)
134
+	{
135
+		// needed to deal with Mac line endings
136
+		ini_set('auto_detect_line_endings', true);
137
+
138
+		// because fgetcsv does not correctly deal with backslashed quotes such as \"
139
+		// we'll read the file into a string
140
+		$file_contents = $this->read_unicode_file($path_to_file);
141
+		// replace backslashed quotes with CSV enclosures
142
+		$file_contents = str_replace('\\"', '"""', $file_contents);
143
+		// HEY YOU! PUT THAT FILE BACK!!!
144
+		file_put_contents($path_to_file, $file_contents);
145
+
146
+		if (($file_handle = fopen($path_to_file, "r")) !== false) {
147
+			# Set the parent multidimensional array key to 0.
148
+			$nn = 0;
149
+			$csvarray = array();
150
+
151
+			// in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions of fgetcsv choke if passed more than 4 - is that crazy or what?
152
+			if (version_compare(PHP_VERSION, '5.3.0') < 0) {
153
+				//  PHP 5.2- version
154
+				// loop through each row of the file
155
+				while (($data = fgetcsv($file_handle, 0, ',', '"')) !== false) {
156
+					$csvarray[] = $data;
157
+				}
158
+			} else {
159
+				// loop through each row of the file
160
+				while (($data = fgetcsv($file_handle, 0, ',', '"', '\\')) !== false) {
161
+					$csvarray[] = $data;
162
+				}
163
+			}
164
+			# Close the File.
165
+			fclose($file_handle);
166
+			return $csvarray;
167
+		} else {
168
+			EE_Error::add_error(
169
+				sprintf(__("An error occurred - the file: %s could not opened.", "event_espresso"), $path_to_file),
170
+				__FILE__,
171
+				__FUNCTION__,
172
+				__LINE__
173
+			);
174
+			return false;
175
+		}
176
+	}
177
+
178
+
179
+	/**
180
+	 * @Import contents of csv file and store values in an array to be manipulated by other functions
181
+	 * @access public
182
+	 * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
183
+	 *                                      If $model_name is provided, assumes that each row in the CSV represents a
184
+	 *                                      model object for that model If $model_name ISN'T provided, assumes that
185
+	 *                                      before model object data, there is a row where the first entry is simply
186
+	 *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
187
+	 *                                      then maybe a row of headers, and then the model data. Eg.
188
+	 *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
189
+	 *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
190
+	 *                                      Forest
191
+	 * @param string  $model_name           model name if we know what model we're importing
192
+	 * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
193
+	 *                                      data
194
+	 * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
195
+	 *               error message like the following array('Event'=>array( array('EVT_ID'=>1,'EVT_name'=>'bob
196
+	 *               party',...), array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
197
+	 *                                      ...
198
+	 *                                      )
199
+	 *                                      'Venue'=>array(
200
+	 *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
201
+	 *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
202
+	 *                                      ...
203
+	 *                                      )
204
+	 *                                      ...
205
+	 *                                      )
206
+	 */
207
+	public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
208
+	{
209
+		$multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
210
+		if (! $multi_dimensional_array) {
211
+			return false;
212
+		}
213
+		// gotta start somewhere
214
+		$row = 1;
215
+		// array to store csv data in
216
+		$ee_formatted_data = array();
217
+		// array to store headers (column names)
218
+		$headers = array();
219
+		foreach ($multi_dimensional_array as $data) {
220
+			// if first cell is MODEL, then second cell is the MODEL name
221
+			if ($data[0] == 'MODEL') {
222
+				$model_name = $data[1];
223
+				// don't bother looking for model data in this row. The rest of this
224
+				// row should be blank
225
+				// AND pretend this is the first row again
226
+				$row = 1;
227
+				// reset headers
228
+				$headers = array();
229
+				continue;
230
+			}
231
+			if (strpos($data[0], EE_CSV::metadata_header) !== false) {
232
+				$model_name = EE_CSV::metadata_header;
233
+				// store like model data, we just won't try importing it etc.
234
+				$row = 1;
235
+				continue;
236
+			}
237
+
238
+
239
+			// how many columns are there?
240
+			$columns = count($data);
241
+
242
+			$model_entry = array();
243
+			// loop through each column
244
+			for ($i = 0; $i < $columns; $i++) {
245
+				// replace csv_enclosures with backslashed quotes
246
+				$data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
247
+				// do we need to grab the column names?
248
+				if ($row === 1) {
249
+					if ($first_row_is_headers) {
250
+						// store the column names to use for keys
251
+						$column_name = $data[ $i ];
252
+						// check it's not blank... sometimes CSV editign programs adda bunch of empty columns onto the end...
253
+						if (! $column_name) {
254
+							continue;
255
+						}
256
+						$matches = array();
257
+						if ($model_name == EE_CSV::metadata_header) {
258
+							$headers[ $i ] = $column_name;
259
+						} else {
260
+							// now get the db table name from it (the part between square brackets)
261
+							$success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
262
+							if (! $success) {
263
+								EE_Error::add_error(
264
+									sprintf(
265
+										__(
266
+											"The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
267
+											"event_espresso"
268
+										),
269
+										$column_name,
270
+										implode(",", $data)
271
+									),
272
+									__FILE__,
273
+									__FUNCTION__,
274
+									__LINE__
275
+								);
276
+								return false;
277
+							}
278
+							$headers[ $i ] = $matches[2];
279
+						}
280
+					} else {
281
+						// no column names means our final array will just use counters for keys
282
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
283
+						$headers[ $i ] = $i;
284
+					}
285
+					// and we need to store csv data
286
+				} else {
287
+					// this column isn' ta header, store it if there is a header for it
288
+					if (isset($headers[ $i ])) {
289
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
290
+					}
291
+				}
292
+			}
293
+			// save the row's data IF it's a non-header-row
294
+			if (! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
295
+				$ee_formatted_data[ $model_name ][] = $model_entry;
296
+			}
297
+			// advance to next row
298
+			$row++;
299
+		}
300
+
301
+		// delete the uploaded file
302
+		unlink($path_to_file);
303
+		// echo '<pre style="height:auto;border:2px solid lightblue;">' . print_r( $ee_formatted_data, TRUE ) . '</pre><br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>';
304
+		// die();
305
+
306
+		// it's good to give back
307
+		return $ee_formatted_data;
308
+	}
309
+
310
+
311
+	public function save_csv_to_db($csv_data_array, $model_name = false)
312
+	{
313
+		EE_Error::doing_it_wrong(
314
+			'save_csv_to_db',
315
+			__(
316
+				'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
317
+				'event_espresso'
318
+			),
319
+			'4.6.7'
320
+		);
321
+		return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
322
+	}
323
+
324
+	/**
325
+	 * Sends HTTP headers to indicate that the browser should download a file,
326
+	 * and starts writing the file to PHP's output. Returns the file handle so other functions can
327
+	 * also write to it
328
+	 *
329
+	 * @param string $new_filename the name of the file that the user will download
330
+	 * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
331
+	 */
332
+	public function begin_sending_csv($filename)
333
+	{
334
+		// grab file extension
335
+		$ext = substr(strrchr($filename, '.'), 1);
336
+		if ($ext == '.csv' or $ext == '.xls') {
337
+			str_replace($ext, '', $filename);
338
+		}
339
+		$filename .= '.csv';
340
+
341
+		// if somebody's been naughty and already started outputting stuff, trash it
342
+		// and start writing our stuff.
343
+		if (ob_get_length()) {
344
+			@ob_flush();
345
+			@flush();
346
+			@ob_end_flush();
347
+		}
348
+		@ob_start();
349
+		header("Pragma: public");
350
+		header("Expires: 0");
351
+		header("Pragma: no-cache");
352
+		header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
353
+		// header("Content-Type: application/force-download");
354
+		// header("Content-Type: application/octet-stream");
355
+		// header("Content-Type: application/download");
356
+		header('Content-disposition: attachment; filename=' . $filename);
357
+		header("Content-Type: text/csv; charset=utf-8");
358
+		do_action('AHEE__EE_CSV__begin_sending_csv__headers');
359
+		echo apply_filters(
360
+			'FHEE__EE_CSV__begin_sending_csv__start_writing',
361
+			"\xEF\xBB\xBF"
362
+		); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
363
+		$fh = fopen('php://output', 'w');
364
+		return $fh;
365
+	}
366
+
367
+	/**
368
+	 * Writes some meta data to the CSV as a bunch of columns. Initially we're only
369
+	 * mentioning the version and timezone
370
+	 *
371
+	 * @param resource $filehandle
372
+	 */
373
+	public function write_metadata_to_csv($filehandle)
374
+	{
375
+		$data_row = array(EE_CSV::metadata_header);// do NOT translate because this exact string is used when importing
376
+		$this->fputcsv2($filehandle, $data_row);
377
+		$meta_data = array(
378
+			0 => array(
379
+				'version'        => espresso_version(),
380
+				'timezone'       => EEH_DTT_Helper::get_timezone(),
381
+				'time_of_export' => current_time('mysql'),
382
+				'site_url'       => site_url(),
383
+			),
384
+		);
385
+		$this->write_data_array_to_csv($filehandle, $meta_data);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Writes $data to the csv file open in $filehandle. uses the array indices of $data for column headers
391
+	 *
392
+	 * @param array   $data                 2D array, first numerically-indexed, and next-level-down preferably indexed
393
+	 *                                      by string
394
+	 * @param boolean $add_csv_column_names whether or not we should add the keys in the bottom-most array as a row for
395
+	 *                                      headers in the CSV. Eg, if $data looked like
396
+	 *                                      array(0=>array('EVT_ID'=>1,'EVT_name'=>'monkey'...), 1=>array(...),...))
397
+	 *                                      then the first row we'd write to the CSV would be "EVT_ID,EVT_name,..."
398
+	 * @return boolean if we successfully wrote to the CSV or not. If there's no $data, we consider that a success
399
+	 *                 (because we wrote everything there was...nothing)
400
+	 */
401
+	public function write_data_array_to_csv($filehandle, $data)
402
+	{
403
+
404
+
405
+		// determine if $data is actually a 2d array
406
+		if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
407
+			// make sure top level is numerically indexed,
408
+
409
+			if (EEH_Array::is_associative_array($data)) {
410
+				throw new EE_Error(
411
+					sprintf(
412
+						__(
413
+							"top-level array must be numerically indexed. Does these look like numbers to you? %s",
414
+							"event_espresso"
415
+						),
416
+						implode(",", array_keys($data))
417
+					)
418
+				);
419
+			}
420
+			$item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
421
+			// now, is the last item in the top-level array of $data an associative or numeric array?
422
+			if (EEH_Array::is_associative_array($item_in_top_level_array)) {
423
+				// its associative, so we want to output its keys as column headers
424
+				$keys = array_keys($item_in_top_level_array);
425
+				echo $this->fputcsv2($filehandle, $keys);
426
+			}
427
+			// start writing data
428
+			foreach ($data as $data_row) {
429
+				echo $this->fputcsv2($filehandle, $data_row);
430
+			}
431
+			return true;
432
+		} else {
433
+			// no data TO write... so we can assume that's a success
434
+			return true;
435
+		}
436
+		// //if 2nd level is indexed by strings, use those as csv column headers (ie, the first row)
437
+		//
438
+		//
439
+		// $no_table = TRUE;
440
+		//
441
+		// // loop through data and add each row to the file/stream as csv
442
+		// foreach ( $data as $model_name => $model_data ) {
443
+		// // test first row to see if it is data or a model name
444
+		// $model = EE_Registry::instance();->load_model($model_name);
445
+		// //if the model really exists,
446
+		// if ( $model ) {
447
+		//
448
+		// // we have a table name
449
+		// $no_table = FALSE;
450
+		//
451
+		// // put the tablename into an array cuz that's how fputcsv rolls
452
+		// $model_name_row = array( 'MODEL', $model_name );
453
+		//
454
+		// // add table name to csv output
455
+		// echo self::fputcsv2($filehandle, $model_name_row);
456
+		//
457
+		// // now get the rest of the data
458
+		// foreach ( $model_data as $row ) {
459
+		// // output the row
460
+		// echo self::fputcsv2($filehandle, $row);
461
+		// }
462
+		//
463
+		// }
464
+		//
465
+		// if ( $no_table ) {
466
+		// // no table so just put the data
467
+		// echo self::fputcsv2($filehandle, $model_data);
468
+		// }
469
+		//
470
+		// } // END OF foreach ( $data )
471
+	}
472
+
473
+	/**
474
+	 * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
475
+	 * Calls exit to prevent polluting the CSV file with other junk
476
+	 *
477
+	 * @param resource $fh filehandle where we're writing the CSV to
478
+	 */
479
+	public function end_sending_csv($fh)
480
+	{
481
+		fclose($fh);
482
+		exit(0);
483
+	}
484
+
485
+	/**
486
+	 * Given an open file, writes all the model data to it in the format the importer expects.
487
+	 * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($filehandle).
488
+	 *
489
+	 * @param resource $filehandle
490
+	 * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
491
+	 *                                   next layer is numerically indexed to represent each model object (eg, each
492
+	 *                                   individual event), and the last layer has all the attributes o fthat model
493
+	 *                                   object (eg, the event's id, name, etc)
494
+	 * @return boolean success
495
+	 */
496
+	public function write_model_data_to_csv($filehandle, $model_data_array)
497
+	{
498
+		$this->write_metadata_to_csv($filehandle);
499
+		foreach ($model_data_array as $model_name => $model_instance_arrays) {
500
+			// first: output a special row stating the model
501
+			echo $this->fputcsv2($filehandle, array('MODEL', $model_name));
502
+			// if we have items to put in the CSV, do it normally
503
+
504
+			if (! empty($model_instance_arrays)) {
505
+				$this->write_data_array_to_csv($filehandle, $model_instance_arrays);
506
+			} else {
507
+				// echo "no data to write... so just write the headers";
508
+				// so there's actually NO model objects for that model.
509
+				// probably still want to show the columns
510
+				$model = EE_Registry::instance()->load_model($model_name);
511
+				$column_names = array();
512
+				foreach ($model->field_settings() as $field) {
513
+					$column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
514
+				}
515
+				$this->write_data_array_to_csv($filehandle, array($column_names));
516
+			}
517
+		}
518
+	}
519
+
520
+	/**
521
+	 * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
522
+	 * and dies (in order to avoid other plugins from messing up the csv output)
523
+	 *
524
+	 * @param string $filename         the filename you want to give the file
525
+	 * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
526
+	 * @return bool | void writes CSV file to output and dies
527
+	 */
528
+	public function export_multiple_model_data_to_csv($filename, $model_data_array)
529
+	{
530
+		$filehandle = $this->begin_sending_csv($filename);
531
+		$this->write_model_data_to_csv($filehandle, $model_data_array);
532
+		$this->end_sending_csv($filehandle);
533
+	}
534
+
535
+	/**
536
+	 * @Export contents of an array to csv file
537
+	 * @access public
538
+	 * @param array  $data     - the array of data to be converted to csv and exported
539
+	 * @param string $filename - name for newly created csv file
540
+	 * @return TRUE on success, FALSE on fail
541
+	 */
542
+	public function export_array_to_csv($data = false, $filename = false)
543
+	{
544
+
545
+		// no data file?? get outta here
546
+		if (! $data or ! is_array($data) or empty($data)) {
547
+			return false;
548
+		}
549
+
550
+		// no filename?? get outta here
551
+		if (! $filename) {
552
+			return false;
553
+		}
554
+
555
+
556
+		// somebody told me i might need this ???
557
+		global $wpdb;
558
+		$prefix = $wpdb->prefix;
559
+
560
+
561
+		$fh = $this->begin_sending_csv($filename);
562
+
563
+
564
+		$this->end_sending_csv($fh);
565
+	}
566
+
567
+
568
+	/**
569
+	 * @Determine the maximum upload file size based on php.ini settings
570
+	 * @access    public
571
+	 * @param int $percent_of_max - desired percentage of the max upload_mb
572
+	 * @return int KB
573
+	 */
574
+	public function get_max_upload_size($percent_of_max = false)
575
+	{
576
+
577
+		$max_upload = (int) (ini_get('upload_max_filesize'));
578
+		$max_post = (int) (ini_get('post_max_size'));
579
+		$memory_limit = (int) (ini_get('memory_limit'));
580
+
581
+		// determine the smallest of the three values from above
582
+		$upload_mb = min($max_upload, $max_post, $memory_limit);
583
+
584
+		// convert MB to KB
585
+		$upload_mb = $upload_mb * 1024;
586
+
587
+		// don't want the full monty? then reduce the max uplaod size
588
+		if ($percent_of_max) {
589
+			// is percent_of_max like this -> 50 or like this -> 0.50 ?
590
+			if ($percent_of_max > 1) {
591
+				// chnages 50 to 0.50
592
+				$percent_of_max = $percent_of_max / 100;
593
+			}
594
+			// make upload_mb a percentage of the max upload_mb
595
+			$upload_mb = $upload_mb * $percent_of_max;
596
+		}
597
+
598
+		return $upload_mb;
599
+	}
600
+
601
+
602
+	/**
603
+	 * @Drop   in replacement for PHP's fputcsv function - but this one works!!!
604
+	 * @access private
605
+	 * @param resource $fh         - file handle - what we are writing to
606
+	 * @param array    $row        - individual row of csv data
607
+	 * @param string   $delimiter  - csv delimiter
608
+	 * @param string   $enclosure  - csv enclosure
609
+	 * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
610
+	 * @return void
611
+	 */
612
+	private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
613
+	{
614
+		// Allow user to filter the csv delimiter and enclosure for other countries csv standards
615
+		$delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
616
+		$enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
617
+
618
+		$delimiter_esc = preg_quote($delimiter, '/');
619
+		$enclosure_esc = preg_quote($enclosure, '/');
620
+
621
+		$output = array();
622
+		foreach ($row as $field_value) {
623
+			if (is_object($field_value) || is_array($field_value)) {
624
+				$field_value = serialize($field_value);
625
+			}
626
+			if ($field_value === null && $mysql_null) {
627
+				$output[] = 'NULL';
628
+				continue;
629
+			}
630
+
631
+			$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
632
+				($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
633
+				: $field_value;
634
+		}
635
+
636
+		fwrite($fh, join($delimiter, $output) . PHP_EOL);
637
+	}
638
+
639
+
640
+	// /**
641
+	//  * @CSV    Import / Export messages
642
+	//  * @access public
643
+	//  * @return void
644
+	//  */
645
+	// public function csv_admin_notices()
646
+	// {
647
+	//
648
+	//     // We play both kinds of music here! Country AND Western! - err... I mean, cycle through both types of notices
649
+	//     foreach (array('updates', 'errors') as $type) {
650
+	//
651
+	//         // if particular notice type is not empty, then "You've got Mail"
652
+	//         if (! empty($this->_notices[ $type ])) {
653
+	//
654
+	//             // is it an update or an error ?
655
+	//             $msg_class = $type == 'updates' ? 'updated' : 'error';
656
+	//             echo '<div id="message" class="' . $msg_class . '">';
657
+	//             // display each notice, however many that may be
658
+	//             foreach ($this->_notices[ $type ] as $message) {
659
+	//                 echo '<p>' . $message . '</p>';
660
+	//             }
661
+	//             // wrap it up
662
+	//             echo '</div>';
663
+	//         }
664
+	//     }
665
+	// }
666
+
667
+	/**
668
+	 * Gets the date format to use in teh csv. filterable
669
+	 *
670
+	 * @param string $current_format
671
+	 * @return string
672
+	 */
673
+	public function get_date_format_for_csv($current_format = null)
674
+	{
675
+		return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
676
+	}
677
+
678
+	/**
679
+	 * Gets the time format we want to use in CSV reports. Filterable
680
+	 *
681
+	 * @param string $current_format
682
+	 * @return string
683
+	 */
684
+	public function get_time_format_for_csv($current_format = null)
685
+	{
686
+		return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
687
+	}
688 688
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -48,31 +48,31 @@  discard block
 block discarded – undo
48 48
         global $wpdb;
49 49
 
50 50
         $this->_primary_keys = array(
51
-            $wpdb->prefix . 'esp_answer'                  => array('ANS_ID'),
52
-            $wpdb->prefix . 'esp_attendee'                => array('ATT_ID'),
53
-            $wpdb->prefix . 'esp_datetime'                => array('DTT_ID'),
54
-            $wpdb->prefix . 'esp_event_question_group'    => array('EQG_ID'),
55
-            $wpdb->prefix . 'esp_message_template'        => array('MTP_ID'),
56
-            $wpdb->prefix . 'esp_payment'                 => array('PAY_ID'),
57
-            $wpdb->prefix . 'esp_price'                   => array('PRC_ID'),
58
-            $wpdb->prefix . 'esp_price_type'              => array('PRT_ID'),
59
-            $wpdb->prefix . 'esp_question'                => array('QST_ID'),
60
-            $wpdb->prefix . 'esp_question_group'          => array('QSG_ID'),
61
-            $wpdb->prefix . 'esp_question_group_question' => array('QGQ_ID'),
62
-            $wpdb->prefix . 'esp_question_option'         => array('QSO_ID'),
63
-            $wpdb->prefix . 'esp_registration'            => array('REG_ID'),
64
-            $wpdb->prefix . 'esp_status'                  => array('STS_ID'),
65
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
66
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
67
-            $wpdb->prefix . 'events_detail'               => array('id'),
68
-            $wpdb->prefix . 'events_category_detail'      => array('id'),
69
-            $wpdb->prefix . 'events_category_rel'         => array('id'),
70
-            $wpdb->prefix . 'events_venue'                => array('id'),
71
-            $wpdb->prefix . 'events_venue_rel'            => array('emeta_id'),
72
-            $wpdb->prefix . 'events_locale'               => array('id'),
73
-            $wpdb->prefix . 'events_locale_rel'           => array('id'),
74
-            $wpdb->prefix . 'events_personnel'            => array('id'),
75
-            $wpdb->prefix . 'events_personnel_rel'        => array('id'),
51
+            $wpdb->prefix.'esp_answer'                  => array('ANS_ID'),
52
+            $wpdb->prefix.'esp_attendee'                => array('ATT_ID'),
53
+            $wpdb->prefix.'esp_datetime'                => array('DTT_ID'),
54
+            $wpdb->prefix.'esp_event_question_group'    => array('EQG_ID'),
55
+            $wpdb->prefix.'esp_message_template'        => array('MTP_ID'),
56
+            $wpdb->prefix.'esp_payment'                 => array('PAY_ID'),
57
+            $wpdb->prefix.'esp_price'                   => array('PRC_ID'),
58
+            $wpdb->prefix.'esp_price_type'              => array('PRT_ID'),
59
+            $wpdb->prefix.'esp_question'                => array('QST_ID'),
60
+            $wpdb->prefix.'esp_question_group'          => array('QSG_ID'),
61
+            $wpdb->prefix.'esp_question_group_question' => array('QGQ_ID'),
62
+            $wpdb->prefix.'esp_question_option'         => array('QSO_ID'),
63
+            $wpdb->prefix.'esp_registration'            => array('REG_ID'),
64
+            $wpdb->prefix.'esp_status'                  => array('STS_ID'),
65
+            $wpdb->prefix.'esp_transaction'             => array('TXN_ID'),
66
+            $wpdb->prefix.'esp_transaction'             => array('TXN_ID'),
67
+            $wpdb->prefix.'events_detail'               => array('id'),
68
+            $wpdb->prefix.'events_category_detail'      => array('id'),
69
+            $wpdb->prefix.'events_category_rel'         => array('id'),
70
+            $wpdb->prefix.'events_venue'                => array('id'),
71
+            $wpdb->prefix.'events_venue_rel'            => array('emeta_id'),
72
+            $wpdb->prefix.'events_locale'               => array('id'),
73
+            $wpdb->prefix.'events_locale_rel'           => array('id'),
74
+            $wpdb->prefix.'events_personnel'            => array('id'),
75
+            $wpdb->prefix.'events_personnel_rel'        => array('id'),
76 76
         );
77 77
     }
78 78
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
     {
105 105
         $fc = "";
106 106
         $fh = fopen($file_path, "rb");
107
-        if (! $fh) {
107
+        if ( ! $fh) {
108 108
             throw new EE_Error(sprintf(__("Cannot open file for read: %s<br>\n", 'event_espresso'), $file_path));
109 109
         }
110 110
         $flen = filesize($file_path);
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
         for ($i = 0; $i < $flen; $i++) {
113 113
             $c = substr($bc, $i, 1);
114 114
             if ((ord($c) != 0) && (ord($c) != 13)) {
115
-                $fc = $fc . $c;
115
+                $fc = $fc.$c;
116 116
             }
117 117
         }
118 118
         if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
     public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
208 208
     {
209 209
         $multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
210
-        if (! $multi_dimensional_array) {
210
+        if ( ! $multi_dimensional_array) {
211 211
             return false;
212 212
         }
213 213
         // gotta start somewhere
@@ -243,23 +243,23 @@  discard block
 block discarded – undo
243 243
             // loop through each column
244 244
             for ($i = 0; $i < $columns; $i++) {
245 245
                 // replace csv_enclosures with backslashed quotes
246
-                $data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
246
+                $data[$i] = str_replace('"""', '\\"', $data[$i]);
247 247
                 // do we need to grab the column names?
248 248
                 if ($row === 1) {
249 249
                     if ($first_row_is_headers) {
250 250
                         // store the column names to use for keys
251
-                        $column_name = $data[ $i ];
251
+                        $column_name = $data[$i];
252 252
                         // check it's not blank... sometimes CSV editign programs adda bunch of empty columns onto the end...
253
-                        if (! $column_name) {
253
+                        if ( ! $column_name) {
254 254
                             continue;
255 255
                         }
256 256
                         $matches = array();
257 257
                         if ($model_name == EE_CSV::metadata_header) {
258
-                            $headers[ $i ] = $column_name;
258
+                            $headers[$i] = $column_name;
259 259
                         } else {
260 260
                             // now get the db table name from it (the part between square brackets)
261 261
                             $success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
262
-                            if (! $success) {
262
+                            if ( ! $success) {
263 263
                                 EE_Error::add_error(
264 264
                                     sprintf(
265 265
                                         __(
@@ -275,24 +275,24 @@  discard block
 block discarded – undo
275 275
                                 );
276 276
                                 return false;
277 277
                             }
278
-                            $headers[ $i ] = $matches[2];
278
+                            $headers[$i] = $matches[2];
279 279
                         }
280 280
                     } else {
281 281
                         // no column names means our final array will just use counters for keys
282
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
283
-                        $headers[ $i ] = $i;
282
+                        $model_entry[$headers[$i]] = $data[$i];
283
+                        $headers[$i] = $i;
284 284
                     }
285 285
                     // and we need to store csv data
286 286
                 } else {
287 287
                     // this column isn' ta header, store it if there is a header for it
288
-                    if (isset($headers[ $i ])) {
289
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
288
+                    if (isset($headers[$i])) {
289
+                        $model_entry[$headers[$i]] = $data[$i];
290 290
                     }
291 291
                 }
292 292
             }
293 293
             // save the row's data IF it's a non-header-row
294
-            if (! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
295
-                $ee_formatted_data[ $model_name ][] = $model_entry;
294
+            if ( ! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
295
+                $ee_formatted_data[$model_name][] = $model_entry;
296 296
             }
297 297
             // advance to next row
298 298
             $row++;
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
         // header("Content-Type: application/force-download");
354 354
         // header("Content-Type: application/octet-stream");
355 355
         // header("Content-Type: application/download");
356
-        header('Content-disposition: attachment; filename=' . $filename);
356
+        header('Content-disposition: attachment; filename='.$filename);
357 357
         header("Content-Type: text/csv; charset=utf-8");
358 358
         do_action('AHEE__EE_CSV__begin_sending_csv__headers');
359 359
         echo apply_filters(
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
      */
373 373
     public function write_metadata_to_csv($filehandle)
374 374
     {
375
-        $data_row = array(EE_CSV::metadata_header);// do NOT translate because this exact string is used when importing
375
+        $data_row = array(EE_CSV::metadata_header); // do NOT translate because this exact string is used when importing
376 376
         $this->fputcsv2($filehandle, $data_row);
377 377
         $meta_data = array(
378 378
             0 => array(
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
             echo $this->fputcsv2($filehandle, array('MODEL', $model_name));
502 502
             // if we have items to put in the CSV, do it normally
503 503
 
504
-            if (! empty($model_instance_arrays)) {
504
+            if ( ! empty($model_instance_arrays)) {
505 505
                 $this->write_data_array_to_csv($filehandle, $model_instance_arrays);
506 506
             } else {
507 507
                 // echo "no data to write... so just write the headers";
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
                 $model = EE_Registry::instance()->load_model($model_name);
511 511
                 $column_names = array();
512 512
                 foreach ($model->field_settings() as $field) {
513
-                    $column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
513
+                    $column_names[$field->get_nicename()."[".$field->get_name()."]"] = null;
514 514
                 }
515 515
                 $this->write_data_array_to_csv($filehandle, array($column_names));
516 516
             }
@@ -543,12 +543,12 @@  discard block
 block discarded – undo
543 543
     {
544 544
 
545 545
         // no data file?? get outta here
546
-        if (! $data or ! is_array($data) or empty($data)) {
546
+        if ( ! $data or ! is_array($data) or empty($data)) {
547 547
             return false;
548 548
         }
549 549
 
550 550
         // no filename?? get outta here
551
-        if (! $filename) {
551
+        if ( ! $filename) {
552 552
             return false;
553 553
         }
554 554
 
@@ -629,11 +629,11 @@  discard block
 block discarded – undo
629 629
             }
630 630
 
631 631
             $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
632
-                ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
632
+                ($enclosure.str_replace($enclosure, $enclosure.$enclosure, $field_value).$enclosure)
633 633
                 : $field_value;
634 634
         }
635 635
 
636
-        fwrite($fh, join($delimiter, $output) . PHP_EOL);
636
+        fwrite($fh, join($delimiter, $output).PHP_EOL);
637 637
     }
638 638
 
639 639
 
Please login to merge, or discard this patch.