Completed
Branch BUG/11214/move-command-handler... (de017e)
by
unknown
04:20 queued 02:32
created
core/EE_Cart.core.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -203,7 +203,7 @@
 block discarded – undo
203 203
      */
204 204
     public function get_tickets()
205 205
     {
206
-        if ($this->_grand_total === null ) {
206
+        if ($this->_grand_total === null) {
207 207
             return array();
208 208
         }
209 209
         return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
Please login to merge, or discard this patch.
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\ResettableInterface;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 do_action('AHEE_log', __FILE__, __FUNCTION__, '');
8 8
 
@@ -23,421 +23,421 @@  discard block
 block discarded – undo
23 23
 class EE_Cart implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * instance of the EE_Cart object
28
-     *
29
-     * @access    private
30
-     * @var EE_Cart $_instance
31
-     */
32
-    private static $_instance;
33
-
34
-    /**
35
-     * instance of the EE_Session object
36
-     *
37
-     * @access    protected
38
-     * @var EE_Session $_session
39
-     */
40
-    protected $_session;
41
-
42
-    /**
43
-     * The total Line item which comprises all the children line-item subtotals,
44
-     * which in turn each have their line items.
45
-     * Typically, the line item structure will look like:
46
-     * grand total
47
-     * -tickets-sub-total
48
-     * --ticket1
49
-     * --ticket2
50
-     * --...
51
-     * -taxes-sub-total
52
-     * --tax1
53
-     * --tax2
54
-     *
55
-     * @var EE_Line_Item
56
-     */
57
-    private $_grand_total;
58
-
59
-
60
-
61
-    /**
62
-     * @singleton method used to instantiate class object
63
-     * @access    public
64
-     * @param EE_Line_Item $grand_total
65
-     * @param EE_Session   $session
66
-     * @return \EE_Cart
67
-     * @throws \EE_Error
68
-     */
69
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
-    {
71
-        if ( ! empty($grand_total)) {
72
-            self::$_instance = new self($grand_total, $session);
73
-        }
74
-        // or maybe retrieve an existing one ?
75
-        if ( ! self::$_instance instanceof EE_Cart) {
76
-            // try getting the cart out of the session
77
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
-            unset($saved_cart);
80
-        }
81
-        // verify that cart is ok and grand total line item exists
82
-        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
-            self::$_instance = new self($grand_total, $session);
84
-        }
85
-        self::$_instance->get_grand_total();
86
-        // once everything is all said and done, save the cart to the EE_Session
87
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
-        return self::$_instance;
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * private constructor to prevent direct creation
95
-     *
96
-     * @Constructor
97
-     * @access private
98
-     * @param EE_Line_Item $grand_total
99
-     * @param EE_Session   $session
100
-     */
101
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
-    {
103
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
-        $this->set_session($session);
105
-        if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
106
-            $this->set_grand_total_line_item($grand_total);
107
-        }
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Resets the cart completely (whereas empty_cart
114
-     *
115
-     * @param EE_Line_Item $grand_total
116
-     * @param EE_Session   $session
117
-     * @return EE_Cart
118
-     * @throws \EE_Error
119
-     */
120
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
-    {
122
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
-        if ($session instanceof EE_Session) {
124
-            $session->reset_cart();
125
-        }
126
-        self::$_instance = null;
127
-        return self::instance($grand_total, $session);
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return \EE_Session
134
-     */
135
-    public function session()
136
-    {
137
-        if ( ! $this->_session instanceof EE_Session) {
138
-            $this->set_session();
139
-        }
140
-        return $this->_session;
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     * @param EE_Session $session
147
-     */
148
-    public function set_session(EE_Session $session = null)
149
-    {
150
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
-     *  know the grand total line item on it
158
-     *
159
-     * @param EE_Line_Item $line_item
160
-     */
161
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
162
-    {
163
-        $this->_grand_total = $line_item;
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * get_cart_from_reg_url_link
170
-     *
171
-     * @access public
172
-     * @param EE_Transaction $transaction
173
-     * @param EE_Session     $session
174
-     * @return \EE_Cart
175
-     * @throws \EE_Error
176
-     */
177
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
-    {
179
-        $grand_total = $transaction->total_line_item();
180
-        $grand_total->get_items();
181
-        $grand_total->tax_descendants();
182
-        return EE_Cart::instance($grand_total, $session);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
-     *
190
-     * @return EE_Line_Item
191
-     * @throws \EE_Error
192
-     */
193
-    private function _create_grand_total()
194
-    {
195
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
196
-        return $this->_grand_total;
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * Gets all the line items of object type Ticket
203
-     *
204
-     * @access public
205
-     * @return \EE_Line_Item[]
206
-     */
207
-    public function get_tickets()
208
-    {
209
-        if ($this->_grand_total === null ) {
210
-            return array();
211
-        }
212
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * returns the total quantity of tickets in the cart
219
-     *
220
-     * @access public
221
-     * @return int
222
-     * @throws \EE_Error
223
-     */
224
-    public function all_ticket_quantity_count()
225
-    {
226
-        $tickets = $this->get_tickets();
227
-        if (empty($tickets)) {
228
-            return 0;
229
-        }
230
-        $count = 0;
231
-        foreach ($tickets as $ticket) {
232
-            $count += $ticket->get('LIN_quantity');
233
-        }
234
-        return $count;
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * Gets all the tax line items
241
-     *
242
-     * @return \EE_Line_Item[]
243
-     * @throws \EE_Error
244
-     */
245
-    public function get_taxes()
246
-    {
247
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * Gets the total line item (which is a parent of all other line items) on this cart
254
-     *
255
-     * @return EE_Line_Item
256
-     * @throws \EE_Error
257
-     */
258
-    public function get_grand_total()
259
-    {
260
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * @process items for adding to cart
267
-     * @access  public
268
-     * @param EE_Ticket $ticket
269
-     * @param int       $qty
270
-     * @return TRUE on success, FALSE on fail
271
-     * @throws \EE_Error
272
-     */
273
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
-    {
275
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
-        return $this->save_cart() ? true : false;
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * get_cart_total_before_tax
283
-     *
284
-     * @access public
285
-     * @return float
286
-     * @throws \EE_Error
287
-     */
288
-    public function get_cart_total_before_tax()
289
-    {
290
-        return $this->get_grand_total()->recalculate_pre_tax_total();
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     * gets the total amount of tax paid for items in this cart
297
-     *
298
-     * @access public
299
-     * @return float
300
-     * @throws \EE_Error
301
-     */
302
-    public function get_applied_taxes()
303
-    {
304
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
-     *
312
-     * @access public
313
-     * @return float
314
-     * @throws \EE_Error
315
-     */
316
-    public function get_cart_grand_total()
317
-    {
318
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
-        return $this->get_grand_total()->total();
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
-     *
327
-     * @access public
328
-     * @return float
329
-     * @throws \EE_Error
330
-     */
331
-    public function recalculate_all_cart_totals()
332
-    {
333
-        $pre_tax_total = $this->get_cart_total_before_tax();
334
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
-        $this->_grand_total->save_this_and_descendants_to_txn();
337
-        return $this->get_grand_total()->total();
338
-    }
339
-
340
-
341
-
342
-    /**
343
-     * deletes an item from the cart
344
-     *
345
-     * @access public
346
-     * @param array|bool|string $line_item_codes
347
-     * @return int on success, FALSE on fail
348
-     * @throws \EE_Error
349
-     */
350
-    public function delete_items($line_item_codes = false)
351
-    {
352
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * @remove ALL items from cart and zero ALL totals
360
-     * @access public
361
-     * @return bool
362
-     * @throws \EE_Error
363
-     */
364
-    public function empty_cart()
365
-    {
366
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
-        $this->_grand_total = $this->_create_grand_total();
368
-        return $this->save_cart(true);
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @remove ALL items from cart and delete total as well
375
-     * @access public
376
-     * @return bool
377
-     * @throws \EE_Error
378
-     */
379
-    public function delete_cart()
380
-    {
381
-        if ($this->_grand_total instanceof EE_Line_Item) {
382
-            $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
383
-            if ($deleted) {
384
-                $deleted += $this->_grand_total->delete();
385
-                $this->_grand_total = null;
386
-                return true;
387
-            }
388
-        }
389
-        return false;
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * @save   cart to session
396
-     * @access public
397
-     * @param bool $apply_taxes
398
-     * @return TRUE on success, FALSE on fail
399
-     * @throws \EE_Error
400
-     */
401
-    public function save_cart($apply_taxes = true)
402
-    {
403
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
404
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
405
-            //make sure we don't cache the transaction because it can get stale
406
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
407
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
408
-            ) {
409
-                $this->_grand_total->clear_cache('Transaction', null, true);
410
-            }
411
-        }
412
-        if ($this->session() instanceof EE_Session) {
413
-            return $this->session()->set_cart($this);
414
-        } else {
415
-            return false;
416
-        }
417
-    }
418
-
419
-
420
-
421
-    public function __wakeup()
422
-    {
423
-        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
424
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
425
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
426
-        }
427
-    }
428
-
429
-
430
-
431
-    /**
432
-     * @return array
433
-     */
434
-    public function __sleep()
435
-    {
436
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
437
-            $this->_grand_total = $this->_grand_total->ID();
438
-        }
439
-        return array('_grand_total');
440
-    }
26
+	/**
27
+	 * instance of the EE_Cart object
28
+	 *
29
+	 * @access    private
30
+	 * @var EE_Cart $_instance
31
+	 */
32
+	private static $_instance;
33
+
34
+	/**
35
+	 * instance of the EE_Session object
36
+	 *
37
+	 * @access    protected
38
+	 * @var EE_Session $_session
39
+	 */
40
+	protected $_session;
41
+
42
+	/**
43
+	 * The total Line item which comprises all the children line-item subtotals,
44
+	 * which in turn each have their line items.
45
+	 * Typically, the line item structure will look like:
46
+	 * grand total
47
+	 * -tickets-sub-total
48
+	 * --ticket1
49
+	 * --ticket2
50
+	 * --...
51
+	 * -taxes-sub-total
52
+	 * --tax1
53
+	 * --tax2
54
+	 *
55
+	 * @var EE_Line_Item
56
+	 */
57
+	private $_grand_total;
58
+
59
+
60
+
61
+	/**
62
+	 * @singleton method used to instantiate class object
63
+	 * @access    public
64
+	 * @param EE_Line_Item $grand_total
65
+	 * @param EE_Session   $session
66
+	 * @return \EE_Cart
67
+	 * @throws \EE_Error
68
+	 */
69
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
+	{
71
+		if ( ! empty($grand_total)) {
72
+			self::$_instance = new self($grand_total, $session);
73
+		}
74
+		// or maybe retrieve an existing one ?
75
+		if ( ! self::$_instance instanceof EE_Cart) {
76
+			// try getting the cart out of the session
77
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
+			unset($saved_cart);
80
+		}
81
+		// verify that cart is ok and grand total line item exists
82
+		if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
+			self::$_instance = new self($grand_total, $session);
84
+		}
85
+		self::$_instance->get_grand_total();
86
+		// once everything is all said and done, save the cart to the EE_Session
87
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
+		return self::$_instance;
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * private constructor to prevent direct creation
95
+	 *
96
+	 * @Constructor
97
+	 * @access private
98
+	 * @param EE_Line_Item $grand_total
99
+	 * @param EE_Session   $session
100
+	 */
101
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
+	{
103
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
+		$this->set_session($session);
105
+		if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
106
+			$this->set_grand_total_line_item($grand_total);
107
+		}
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Resets the cart completely (whereas empty_cart
114
+	 *
115
+	 * @param EE_Line_Item $grand_total
116
+	 * @param EE_Session   $session
117
+	 * @return EE_Cart
118
+	 * @throws \EE_Error
119
+	 */
120
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
+	{
122
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
+		if ($session instanceof EE_Session) {
124
+			$session->reset_cart();
125
+		}
126
+		self::$_instance = null;
127
+		return self::instance($grand_total, $session);
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return \EE_Session
134
+	 */
135
+	public function session()
136
+	{
137
+		if ( ! $this->_session instanceof EE_Session) {
138
+			$this->set_session();
139
+		}
140
+		return $this->_session;
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 * @param EE_Session $session
147
+	 */
148
+	public function set_session(EE_Session $session = null)
149
+	{
150
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
+	 *  know the grand total line item on it
158
+	 *
159
+	 * @param EE_Line_Item $line_item
160
+	 */
161
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
162
+	{
163
+		$this->_grand_total = $line_item;
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * get_cart_from_reg_url_link
170
+	 *
171
+	 * @access public
172
+	 * @param EE_Transaction $transaction
173
+	 * @param EE_Session     $session
174
+	 * @return \EE_Cart
175
+	 * @throws \EE_Error
176
+	 */
177
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
+	{
179
+		$grand_total = $transaction->total_line_item();
180
+		$grand_total->get_items();
181
+		$grand_total->tax_descendants();
182
+		return EE_Cart::instance($grand_total, $session);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
+	 *
190
+	 * @return EE_Line_Item
191
+	 * @throws \EE_Error
192
+	 */
193
+	private function _create_grand_total()
194
+	{
195
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
196
+		return $this->_grand_total;
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * Gets all the line items of object type Ticket
203
+	 *
204
+	 * @access public
205
+	 * @return \EE_Line_Item[]
206
+	 */
207
+	public function get_tickets()
208
+	{
209
+		if ($this->_grand_total === null ) {
210
+			return array();
211
+		}
212
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * returns the total quantity of tickets in the cart
219
+	 *
220
+	 * @access public
221
+	 * @return int
222
+	 * @throws \EE_Error
223
+	 */
224
+	public function all_ticket_quantity_count()
225
+	{
226
+		$tickets = $this->get_tickets();
227
+		if (empty($tickets)) {
228
+			return 0;
229
+		}
230
+		$count = 0;
231
+		foreach ($tickets as $ticket) {
232
+			$count += $ticket->get('LIN_quantity');
233
+		}
234
+		return $count;
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * Gets all the tax line items
241
+	 *
242
+	 * @return \EE_Line_Item[]
243
+	 * @throws \EE_Error
244
+	 */
245
+	public function get_taxes()
246
+	{
247
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * Gets the total line item (which is a parent of all other line items) on this cart
254
+	 *
255
+	 * @return EE_Line_Item
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function get_grand_total()
259
+	{
260
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * @process items for adding to cart
267
+	 * @access  public
268
+	 * @param EE_Ticket $ticket
269
+	 * @param int       $qty
270
+	 * @return TRUE on success, FALSE on fail
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
+	{
275
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
+		return $this->save_cart() ? true : false;
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * get_cart_total_before_tax
283
+	 *
284
+	 * @access public
285
+	 * @return float
286
+	 * @throws \EE_Error
287
+	 */
288
+	public function get_cart_total_before_tax()
289
+	{
290
+		return $this->get_grand_total()->recalculate_pre_tax_total();
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 * gets the total amount of tax paid for items in this cart
297
+	 *
298
+	 * @access public
299
+	 * @return float
300
+	 * @throws \EE_Error
301
+	 */
302
+	public function get_applied_taxes()
303
+	{
304
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
+	 *
312
+	 * @access public
313
+	 * @return float
314
+	 * @throws \EE_Error
315
+	 */
316
+	public function get_cart_grand_total()
317
+	{
318
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
+		return $this->get_grand_total()->total();
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
+	 *
327
+	 * @access public
328
+	 * @return float
329
+	 * @throws \EE_Error
330
+	 */
331
+	public function recalculate_all_cart_totals()
332
+	{
333
+		$pre_tax_total = $this->get_cart_total_before_tax();
334
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
+		$this->_grand_total->save_this_and_descendants_to_txn();
337
+		return $this->get_grand_total()->total();
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * deletes an item from the cart
344
+	 *
345
+	 * @access public
346
+	 * @param array|bool|string $line_item_codes
347
+	 * @return int on success, FALSE on fail
348
+	 * @throws \EE_Error
349
+	 */
350
+	public function delete_items($line_item_codes = false)
351
+	{
352
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * @remove ALL items from cart and zero ALL totals
360
+	 * @access public
361
+	 * @return bool
362
+	 * @throws \EE_Error
363
+	 */
364
+	public function empty_cart()
365
+	{
366
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
+		$this->_grand_total = $this->_create_grand_total();
368
+		return $this->save_cart(true);
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @remove ALL items from cart and delete total as well
375
+	 * @access public
376
+	 * @return bool
377
+	 * @throws \EE_Error
378
+	 */
379
+	public function delete_cart()
380
+	{
381
+		if ($this->_grand_total instanceof EE_Line_Item) {
382
+			$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
383
+			if ($deleted) {
384
+				$deleted += $this->_grand_total->delete();
385
+				$this->_grand_total = null;
386
+				return true;
387
+			}
388
+		}
389
+		return false;
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * @save   cart to session
396
+	 * @access public
397
+	 * @param bool $apply_taxes
398
+	 * @return TRUE on success, FALSE on fail
399
+	 * @throws \EE_Error
400
+	 */
401
+	public function save_cart($apply_taxes = true)
402
+	{
403
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
404
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
405
+			//make sure we don't cache the transaction because it can get stale
406
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
407
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
408
+			) {
409
+				$this->_grand_total->clear_cache('Transaction', null, true);
410
+			}
411
+		}
412
+		if ($this->session() instanceof EE_Session) {
413
+			return $this->session()->set_cart($this);
414
+		} else {
415
+			return false;
416
+		}
417
+	}
418
+
419
+
420
+
421
+	public function __wakeup()
422
+	{
423
+		if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
424
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
425
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
426
+		}
427
+	}
428
+
429
+
430
+
431
+	/**
432
+	 * @return array
433
+	 */
434
+	public function __sleep()
435
+	{
436
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
437
+			$this->_grand_total = $this->_grand_total->ID();
438
+		}
439
+		return array('_grand_total');
440
+	}
441 441
 
442 442
 
443 443
 }
Please login to merge, or discard this patch.
core/db_models/helpers/EE_Table_Base.php 2 patches
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -9,164 +9,164 @@
 block discarded – undo
9 9
 abstract class EE_Table_Base
10 10
 {
11 11
 
12
-    /**
13
-     * This holds the table_name without the table prefix.
14
-     *
15
-     * @var string
16
-     */
17
-    var $_table_name;
18
-
19
-
20
-    /**
21
-     * This holds what is used as the alias for the table in queries.
22
-     *
23
-     * @var string
24
-     */
25
-    var $_table_alias;
26
-
27
-
28
-    /**
29
-     * Table's private key column
30
-     *
31
-     * @var string
32
-     */
33
-    protected $_pk_column;
34
-
35
-
36
-    /**
37
-     * Whether this table is a global table (in multisite) or specific to site.
38
-     *
39
-     * @var bool
40
-     */
41
-    protected $_global;
42
-
43
-
44
-
45
-    /**
46
-     * @global wpdb   $wpdb
47
-     * @param string  $table_name with or without wpdb prefix
48
-     * @param string  $pk_column
49
-     * @param boolean $global     whether the table is "global" as in there is only 1 table on an entire multisite
50
-     *                            install, or whether each site on a multisite install has a copy of this table
51
-     */
52
-    function __construct($table_name, $pk_column, $global = false)
53
-    {
54
-        $this->_global = $global;
55
-        $prefix = $this->get_table_prefix();
56
-        //if they added the prefix, let's remove it because we delay adding the prefix until right when its needed.
57
-        if (strpos($table_name, $prefix) === 0) {
58
-            $table_name = ltrim($table_name, $prefix);
59
-        }
60
-        $this->_table_name = $table_name;
61
-        $this->_pk_column = $pk_column;
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     * This returns the table prefix for the current model state.
68
-     *
69
-     * @global wpdb $wpdb
70
-     * @return string
71
-     */
72
-    public function get_table_prefix()
73
-    {
74
-        global $wpdb;
75
-        if ($this->_global) {
76
-            $prefix = $wpdb->base_prefix;
77
-        } else {
78
-            $prefix = $wpdb->get_blog_prefix(EEM_Base::get_model_query_blog_id());
79
-        }
80
-        return $prefix;
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     * Used to set the table_alias property
87
-     *
88
-     * @param string $table_alias
89
-     */
90
-    function _construct_finalize_with_alias($table_alias)
91
-    {
92
-        $this->_table_alias = $table_alias;
93
-    }
94
-
95
-
96
-
97
-    /**
98
-     * Returns the fully qualified table name for the database (includes the table prefix current for the blog).
99
-     *
100
-     * @return string
101
-     */
102
-    function get_table_name()
103
-    {
104
-        return $this->get_table_prefix() . $this->_table_name;
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * Provides what is currently set as the alias for the table to be used in queries.
111
-     *
112
-     * @return string
113
-     * @throws EE_Error
114
-     */
115
-    function get_table_alias()
116
-    {
117
-        if ( ! $this->_table_alias) {
118
-            throw new EE_Error("You must call _construct_finalize_with_alias before using the EE_Table_Base. Did you forget to call parent::__construct at the end of your EEMerimental_Base child's __construct?");
119
-        }
120
-        return $this->_table_alias;
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * @return string name of column of PK
127
-     */
128
-    function get_pk_column()
129
-    {
130
-        return $this->_pk_column;
131
-    }
132
-
133
-
134
-
135
-    /**
136
-     * returns a string with the table alias, a period, and the private key's column.
137
-     *
138
-     * @return string
139
-     */
140
-    function get_fully_qualified_pk_column()
141
-    {
142
-        $sql = $this->get_table_alias() . "." . $this->get_pk_column();
143
-        return $sql;
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * returns the special sql for a inner select with a limit.
150
-     *
151
-     * @return string    SQL select
152
-     */
153
-    public function get_select_join_limit($limit)
154
-    {
155
-        $limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int)$limit;
156
-        $SQL = SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
157
-        return $SQL;
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * Returns whether or not htis is a global table (ie, on multisite there's
164
-     * only one of these tables, on the main blog)
165
-     *
166
-     * @return boolean
167
-     */
168
-    public function is_global()
169
-    {
170
-        return $this->_global;
171
-    }
12
+	/**
13
+	 * This holds the table_name without the table prefix.
14
+	 *
15
+	 * @var string
16
+	 */
17
+	var $_table_name;
18
+
19
+
20
+	/**
21
+	 * This holds what is used as the alias for the table in queries.
22
+	 *
23
+	 * @var string
24
+	 */
25
+	var $_table_alias;
26
+
27
+
28
+	/**
29
+	 * Table's private key column
30
+	 *
31
+	 * @var string
32
+	 */
33
+	protected $_pk_column;
34
+
35
+
36
+	/**
37
+	 * Whether this table is a global table (in multisite) or specific to site.
38
+	 *
39
+	 * @var bool
40
+	 */
41
+	protected $_global;
42
+
43
+
44
+
45
+	/**
46
+	 * @global wpdb   $wpdb
47
+	 * @param string  $table_name with or without wpdb prefix
48
+	 * @param string  $pk_column
49
+	 * @param boolean $global     whether the table is "global" as in there is only 1 table on an entire multisite
50
+	 *                            install, or whether each site on a multisite install has a copy of this table
51
+	 */
52
+	function __construct($table_name, $pk_column, $global = false)
53
+	{
54
+		$this->_global = $global;
55
+		$prefix = $this->get_table_prefix();
56
+		//if they added the prefix, let's remove it because we delay adding the prefix until right when its needed.
57
+		if (strpos($table_name, $prefix) === 0) {
58
+			$table_name = ltrim($table_name, $prefix);
59
+		}
60
+		$this->_table_name = $table_name;
61
+		$this->_pk_column = $pk_column;
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 * This returns the table prefix for the current model state.
68
+	 *
69
+	 * @global wpdb $wpdb
70
+	 * @return string
71
+	 */
72
+	public function get_table_prefix()
73
+	{
74
+		global $wpdb;
75
+		if ($this->_global) {
76
+			$prefix = $wpdb->base_prefix;
77
+		} else {
78
+			$prefix = $wpdb->get_blog_prefix(EEM_Base::get_model_query_blog_id());
79
+		}
80
+		return $prefix;
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 * Used to set the table_alias property
87
+	 *
88
+	 * @param string $table_alias
89
+	 */
90
+	function _construct_finalize_with_alias($table_alias)
91
+	{
92
+		$this->_table_alias = $table_alias;
93
+	}
94
+
95
+
96
+
97
+	/**
98
+	 * Returns the fully qualified table name for the database (includes the table prefix current for the blog).
99
+	 *
100
+	 * @return string
101
+	 */
102
+	function get_table_name()
103
+	{
104
+		return $this->get_table_prefix() . $this->_table_name;
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * Provides what is currently set as the alias for the table to be used in queries.
111
+	 *
112
+	 * @return string
113
+	 * @throws EE_Error
114
+	 */
115
+	function get_table_alias()
116
+	{
117
+		if ( ! $this->_table_alias) {
118
+			throw new EE_Error("You must call _construct_finalize_with_alias before using the EE_Table_Base. Did you forget to call parent::__construct at the end of your EEMerimental_Base child's __construct?");
119
+		}
120
+		return $this->_table_alias;
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * @return string name of column of PK
127
+	 */
128
+	function get_pk_column()
129
+	{
130
+		return $this->_pk_column;
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * returns a string with the table alias, a period, and the private key's column.
137
+	 *
138
+	 * @return string
139
+	 */
140
+	function get_fully_qualified_pk_column()
141
+	{
142
+		$sql = $this->get_table_alias() . "." . $this->get_pk_column();
143
+		return $sql;
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * returns the special sql for a inner select with a limit.
150
+	 *
151
+	 * @return string    SQL select
152
+	 */
153
+	public function get_select_join_limit($limit)
154
+	{
155
+		$limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int)$limit;
156
+		$SQL = SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
157
+		return $SQL;
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * Returns whether or not htis is a global table (ie, on multisite there's
164
+	 * only one of these tables, on the main blog)
165
+	 *
166
+	 * @return boolean
167
+	 */
168
+	public function is_global()
169
+	{
170
+		return $this->_global;
171
+	}
172 172
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
      */
102 102
     function get_table_name()
103 103
     {
104
-        return $this->get_table_prefix() . $this->_table_name;
104
+        return $this->get_table_prefix().$this->_table_name;
105 105
     }
106 106
 
107 107
 
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
      */
140 140
     function get_fully_qualified_pk_column()
141 141
     {
142
-        $sql = $this->get_table_alias() . "." . $this->get_pk_column();
142
+        $sql = $this->get_table_alias().".".$this->get_pk_column();
143 143
         return $sql;
144 144
     }
145 145
 
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
      */
153 153
     public function get_select_join_limit($limit)
154 154
     {
155
-        $limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int)$limit;
156
-        $SQL = SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
155
+        $limit = is_array($limit) ? 'LIMIT '.implode(',', array_map('intval', $limit)) : 'LIMIT '.(int) $limit;
156
+        $SQL = SP.'(SELECT * FROM '.$this->_table_name.SP.$limit.') AS '.$this->_table_alias;
157 157
         return $SQL;
158 158
     }
159 159
 
Please login to merge, or discard this patch.
core/db_models/EEM_CPT_Base.model.php 2 patches
Indentation   +514 added lines, -514 removed lines patch added patch discarded remove patch
@@ -18,519 +18,519 @@
 block discarded – undo
18 18
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
19 19
 {
20 20
 
21
-    /**
22
-     * @var string post_status_publish - the wp post status for published cpts
23
-     */
24
-    const post_status_publish = 'publish';
25
-
26
-    /**
27
-     * @var string post_status_future - the wp post status for scheduled cpts
28
-     */
29
-    const post_status_future = 'future';
30
-
31
-    /**
32
-     * @var string post_status_draft - the wp post status for draft cpts
33
-     */
34
-    const post_status_draft = 'draft';
35
-
36
-    /**
37
-     * @var string post_status_pending - the wp post status for pending cpts
38
-     */
39
-    const post_status_pending = 'pending';
40
-
41
-    /**
42
-     * @var string post_status_private - the wp post status for private cpts
43
-     */
44
-    const post_status_private = 'private';
45
-
46
-    /**
47
-     * @var string post_status_trashed - the wp post status for trashed cpts
48
-     */
49
-    const post_status_trashed = 'trash';
50
-
51
-    /**
52
-     * This is an array of custom statuses for the given CPT model (modified by children)
53
-     * format:
54
-     * array(
55
-     *        'status_name' => array(
56
-     *            'label' => __('Status Name', 'event_espresso'),
57
-     *            'public' => TRUE //whether a public status or not.
58
-     *        )
59
-     * )
60
-     *
61
-     * @var array
62
-     */
63
-    protected $_custom_stati = array();
64
-
65
-
66
-
67
-    /**
68
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
69
-     *
70
-     * @param string $timezone
71
-     * @throws \EE_Error
72
-     */
73
-    protected function __construct($timezone = null)
74
-    {
75
-        //adds a relationship to Term_Taxonomy for all these models. For this to work
76
-        //Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
77
-        //eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
78
-        //with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
79
-        //must also be new EE_HABTM_Relation('Term_Relationship');
80
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
81
-        $primary_table_name = null;
82
-        //add  the common _status field to all CPT primary tables.
83
-        foreach ($this->_tables as $alias => $table_obj) {
84
-            if ($table_obj instanceof EE_Primary_Table) {
85
-                $primary_table_name = $alias;
86
-            }
87
-        }
88
-        //set default wp post statuses if child has not already set.
89
-        if ( ! isset($this->_fields[$primary_table_name]['status'])) {
90
-            $this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field('post_status',
91
-                __("Event Status", "event_espresso"), false, 'draft');
92
-        }
93
-        if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
94
-            $this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field('to_ping',
95
-                __('To Ping', 'event_espresso'), false, '');
96
-        }
97
-        if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
98
-            $this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field('pinged',
99
-                __('Pinged', 'event_espresso'), false, '');
100
-        }
101
-        if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
102
-            $this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field('comment_status',
103
-                __('Comment Status', 'event_espresso'), false, 'open');
104
-        }
105
-        if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
106
-            $this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field('ping_status',
107
-                __('Ping Status', 'event_espresso'), false, 'open');
108
-        }
109
-        if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
110
-            $this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field('post_content_filtered',
111
-                __('Post Content Filtered', 'event_espresso'), false, '');
112
-        }
113
-        if ( ! isset($this->_model_relations['Post_Meta'])) {
114
-            //don't block deletes though because we want to maintain the current behaviour
115
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
116
-        }
117
-        if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
118
-            //nothing was set during child constructor, so set default
119
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
120
-        }
121
-        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
122
-            //nothing was set during child constructor, so set default
123
-            //it's ok for child classes to specify this, but generally this is more DRY
124
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
125
-        }
126
-        parent::__construct($timezone);
127
-    }
128
-
129
-
130
-
131
-    /**
132
-     * @return array
133
-     */
134
-    public function public_event_stati()
135
-    {
136
-        // @see wp-includes/post.php
137
-        return get_post_stati(array('public' => true));
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
144
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
145
-     *
146
-     * @return string
147
-     * @throws EE_Error
148
-     */
149
-    public function deleted_field_name()
150
-    {
151
-        throw new EE_Error(sprintf(__("EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
152
-            "event_espresso")));
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * Gets the field's name that sets the post status
159
-     *
160
-     * @return string
161
-     * @throws EE_Error
162
-     */
163
-    public function post_status_field_name()
164
-    {
165
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
166
-        if ($field) {
167
-            return $field->get_name();
168
-        } else {
169
-            throw new EE_Error(sprintf(__('We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
170
-                'event_espresso'), get_class($this), get_class($this)));
171
-        }
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     * Alters the query params so that only trashed/soft-deleted items are considered
178
-     *
179
-     * @param array $query_params like EEM_Base::get_all's $query_params
180
-     * @return array like EEM_Base::get_all's $query_params
181
-     */
182
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
183
-    {
184
-        $post_status_field_name = $this->post_status_field_name();
185
-        $query_params[0][$post_status_field_name] = self::post_status_trashed;
186
-        return $query_params;
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * Alters the query params so each item's deleted status is ignored.
193
-     *
194
-     * @param array $query_params
195
-     * @return array
196
-     */
197
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
198
-    {
199
-        $query_params['default_where_conditions'] = 'minimum';
200
-        return $query_params;
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
207
-     *
208
-     * @param boolean $delete       true to indicate deletion, false to indicate restoration
209
-     * @param array   $query_params like EEM_Base::get_all
210
-     * @return boolean success
211
-     */
212
-    function delete_or_restore($delete = true, $query_params = array())
213
-    {
214
-        $post_status_field_name = $this->post_status_field_name();
215
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
216
-        $new_status = $delete ? self::post_status_trashed : 'draft';
217
-        if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
218
-            return true;
219
-        } else {
220
-            return false;
221
-        }
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * meta_table
228
-     * returns first EE_Secondary_Table table name
229
-     *
230
-     * @access public
231
-     * @return string
232
-     */
233
-    public function meta_table()
234
-    {
235
-        $meta_table = $this->_get_other_tables();
236
-        $meta_table = reset($meta_table);
237
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
244
-     *
245
-     * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
246
-     *                   db only fields)
247
-     * @return array
248
-     */
249
-    public function get_meta_table_fields($all = false)
250
-    {
251
-        $all_fields = $fields_to_return = array();
252
-        foreach ($this->_tables as $alias => $table_obj) {
253
-            if ($table_obj instanceof EE_Secondary_Table) {
254
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
255
-            }
256
-        }
257
-        if ( ! $all) {
258
-            foreach ($all_fields as $name => $obj) {
259
-                if ($obj instanceof EE_DB_Only_Field_Base) {
260
-                    continue;
261
-                }
262
-                $fields_to_return[] = $name;
263
-            }
264
-        } else {
265
-            $fields_to_return = array_keys($all_fields);
266
-        }
267
-        return $fields_to_return;
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * Adds an event category with the specified name and description to the specified
274
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
275
-     * and adds an entry in the term_relationship if necessary.
276
-     *
277
-     * @param EE_CPT_Base $cpt_model_object
278
-     * @param string      $category_name (used to derive the term slug too)
279
-     * @param string      $category_description
280
-     * @param int         $parent_term_taxonomy_id
281
-     * @return EE_Term_Taxonomy
282
-     */
283
-    function add_event_category(
284
-        EE_CPT_Base $cpt_model_object,
285
-        $category_name,
286
-        $category_description = '',
287
-        $parent_term_taxonomy_id = null
288
-    ) {
289
-        //create term
290
-        require_once(EE_MODELS . 'EEM_Term.model.php');
291
-        //first, check for a term by the same name or slug
292
-        $category_slug = sanitize_title($category_name);
293
-        $term = EEM_Term::instance()->get_one(array(
294
-            array(
295
-                'OR' => array(
296
-                    'name' => $category_name,
297
-                    'slug' => $category_slug,
298
-                ),
299
-            ),
300
-        ));
301
-        if ( ! $term) {
302
-            $term = EE_Term::new_instance(array(
303
-                'name' => $category_name,
304
-                'slug' => $category_slug,
305
-            ));
306
-            $term->save();
307
-        }
308
-        //make sure there's a term-taxonomy entry too
309
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
310
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311
-            array(
312
-                'term_id'  => $term->ID(),
313
-                'taxonomy' => EE_Event_Category_Taxonomy,
314
-            ),
315
-        ));
316
-        /** @var $term_taxonomy EE_Term_Taxonomy */
317
-        if ( ! $term_taxonomy) {
318
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(array(
319
-                'term_id'     => $term->ID(),
320
-                'taxonomy'    => EE_Event_Category_Taxonomy,
321
-                'description' => $category_description,
322
-                'count'       => 1,
323
-                'parent'      => $parent_term_taxonomy_id,
324
-            ));
325
-            $term_taxonomy->save();
326
-        } else {
327
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
328
-            $term_taxonomy->save();
329
-        }
330
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * Removed the category specified by name as having a relation to this event.
337
-     * Does not remove the term or term_taxonomy.
338
-     *
339
-     * @param EE_CPT_Base $cpt_model_object_event
340
-     * @param string      $category_name name of the event category (term)
341
-     * @return bool
342
-     */
343
-    function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
344
-    {
345
-        //find the term_taxonomy by that name
346
-        $term_taxonomy = $this->get_first_related($cpt_model_object_event, 'Term_Taxonomy',
347
-            array(array('Term.name' => $category_name, 'taxonomy' => EE_Event_Category_Taxonomy)));
348
-        /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if ($term_taxonomy) {
350
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
351
-            $term_taxonomy->save();
352
-        }
353
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
360
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
361
-     *
362
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
363
-     * @access public
364
-     * @param int          $id   the ID for the cpt we want the feature image for
365
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
366
-     *                           representing width and height in pixels (i.e. array(32,32) ).
367
-     * @param string|array $attr Optional. Query string or array of attributes.
368
-     * @return string HTML image element
369
-     */
370
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
371
-    {
372
-        return get_the_post_thumbnail($id, $size, $attr);
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * Just a handy way to get the list of post statuses currently registered with WP.
379
-     *
380
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
381
-     * @return array
382
-     */
383
-    public function get_post_statuses()
384
-    {
385
-        global $wp_post_statuses;
386
-        $statuses = array();
387
-        foreach ($wp_post_statuses as $post_status => $args_object) {
388
-            $statuses[$post_status] = $args_object->label;
389
-        }
390
-        return $statuses;
391
-    }
392
-
393
-
394
-
395
-    /**
396
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
397
-     *
398
-     * @return array array of statuses.
399
-     */
400
-    public function get_status_array()
401
-    {
402
-        $statuses = $this->get_post_statuses();
403
-        //first the global filter
404
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405
-        //now the class specific filter
406
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
407
-        return $statuses;
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * this returns the post statuses that are NOT the default wordpress status
414
-     *
415
-     * @return array
416
-     */
417
-    public function get_custom_post_statuses()
418
-    {
419
-        $new_stati = array();
420
-        foreach ($this->_custom_stati as $status => $props) {
421
-            $new_stati[$status] = $props['label'];
422
-        }
423
-        return $new_stati;
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
430
-     * are a row from the posts table. If we're missing any fields required for the model,
431
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
432
-     * make sure you are attaching all the model's fields onto the post)
433
-     *
434
-     * @param WP_Post|array $post
435
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
436
-     */
437
-    public function instantiate_class_from_post_object_orig($post)
438
-    {
439
-        $post = (array)$post;
440
-        $has_all_necessary_fields_for_table = true;
441
-        //check if the post has fields on the meta table already
442
-        foreach ($this->_get_other_tables() as $table_obj) {
443
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
444
-            foreach ($fields_for_that_table as $field_obj) {
445
-                if ( ! isset($post[$field_obj->get_table_column()])
446
-                     && ! isset($post[$field_obj->get_qualified_column()])
447
-                ) {
448
-                    $has_all_necessary_fields_for_table = false;
449
-                }
450
-            }
451
-        }
452
-        //if we don't have all the fields we need, then just fetch the proper model from the DB
453
-        if ( ! $has_all_necessary_fields_for_table) {
454
-            return $this->get_one_by_ID($post['ID']);
455
-        } else {
456
-            return $this->instantiate_class_from_array_or_object($post);
457
-        }
458
-    }
459
-
460
-
461
-
462
-    /**
463
-     * @param null $post
464
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
465
-     */
466
-    public function instantiate_class_from_post_object($post = null)
467
-    {
468
-        if (empty($post)) {
469
-            global $post;
470
-        }
471
-        $post = (array)$post;
472
-        $tables_needing_to_be_queried = array();
473
-        //check if the post has fields on the meta table already
474
-        foreach ($this->get_tables() as $table_obj) {
475
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
476
-            foreach ($fields_for_that_table as $field_obj) {
477
-                if ( ! isset($post[$field_obj->get_table_column()])
478
-                     && ! isset($post[$field_obj->get_qualified_column()])
479
-                ) {
480
-                    $tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
481
-                }
482
-            }
483
-        }
484
-        //if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if ($tables_needing_to_be_queried) {
486
-            if (count($tables_needing_to_be_queried) == 1
487
-                && reset($tables_needing_to_be_queried)
488
-                   instanceof
489
-                   EE_Secondary_Table
490
-            ) {
491
-                //so we're only missing data from a secondary table. Well that's not too hard to query for
492
-                $table_to_query = reset($tables_needing_to_be_queried);
493
-                $missing_data = $this->_do_wpdb_query('get_row', array(
494
-                    'SELECT * FROM '
495
-                    . $table_to_query->get_table_name()
496
-                    . ' WHERE '
497
-                    . $table_to_query->get_fk_on_table()
498
-                    . ' = '
499
-                    . $post['ID'],
500
-                    ARRAY_A,
501
-                ));
502
-                if ( ! empty($missing_data)) {
503
-                    $post = array_merge($post, $missing_data);
504
-                }
505
-            } else {
506
-                return $this->get_one_by_ID($post['ID']);
507
-            }
508
-        }
509
-        return $this->instantiate_class_from_array_or_object($post);
510
-    }
511
-
512
-
513
-
514
-    /**
515
-     * Gets the post type associated with this
516
-     *
517
-     * @throws EE_Error
518
-     * @return string
519
-     */
520
-    public function post_type()
521
-    {
522
-        $post_type_field = null;
523
-        foreach ($this->field_settings(true) as $field_obj) {
524
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
525
-                $post_type_field = $field_obj;
526
-                break;
527
-            }
528
-        }
529
-        if ($post_type_field == null) {
530
-            throw new EE_Error(sprintf(__("CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
531
-                "event_espresso"), get_class($this)));
532
-        }
533
-        return $post_type_field->get_default_value();
534
-    }
21
+	/**
22
+	 * @var string post_status_publish - the wp post status for published cpts
23
+	 */
24
+	const post_status_publish = 'publish';
25
+
26
+	/**
27
+	 * @var string post_status_future - the wp post status for scheduled cpts
28
+	 */
29
+	const post_status_future = 'future';
30
+
31
+	/**
32
+	 * @var string post_status_draft - the wp post status for draft cpts
33
+	 */
34
+	const post_status_draft = 'draft';
35
+
36
+	/**
37
+	 * @var string post_status_pending - the wp post status for pending cpts
38
+	 */
39
+	const post_status_pending = 'pending';
40
+
41
+	/**
42
+	 * @var string post_status_private - the wp post status for private cpts
43
+	 */
44
+	const post_status_private = 'private';
45
+
46
+	/**
47
+	 * @var string post_status_trashed - the wp post status for trashed cpts
48
+	 */
49
+	const post_status_trashed = 'trash';
50
+
51
+	/**
52
+	 * This is an array of custom statuses for the given CPT model (modified by children)
53
+	 * format:
54
+	 * array(
55
+	 *        'status_name' => array(
56
+	 *            'label' => __('Status Name', 'event_espresso'),
57
+	 *            'public' => TRUE //whether a public status or not.
58
+	 *        )
59
+	 * )
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $_custom_stati = array();
64
+
65
+
66
+
67
+	/**
68
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
69
+	 *
70
+	 * @param string $timezone
71
+	 * @throws \EE_Error
72
+	 */
73
+	protected function __construct($timezone = null)
74
+	{
75
+		//adds a relationship to Term_Taxonomy for all these models. For this to work
76
+		//Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
77
+		//eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
78
+		//with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
79
+		//must also be new EE_HABTM_Relation('Term_Relationship');
80
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
81
+		$primary_table_name = null;
82
+		//add  the common _status field to all CPT primary tables.
83
+		foreach ($this->_tables as $alias => $table_obj) {
84
+			if ($table_obj instanceof EE_Primary_Table) {
85
+				$primary_table_name = $alias;
86
+			}
87
+		}
88
+		//set default wp post statuses if child has not already set.
89
+		if ( ! isset($this->_fields[$primary_table_name]['status'])) {
90
+			$this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field('post_status',
91
+				__("Event Status", "event_espresso"), false, 'draft');
92
+		}
93
+		if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
94
+			$this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field('to_ping',
95
+				__('To Ping', 'event_espresso'), false, '');
96
+		}
97
+		if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
98
+			$this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field('pinged',
99
+				__('Pinged', 'event_espresso'), false, '');
100
+		}
101
+		if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
102
+			$this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field('comment_status',
103
+				__('Comment Status', 'event_espresso'), false, 'open');
104
+		}
105
+		if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
106
+			$this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field('ping_status',
107
+				__('Ping Status', 'event_espresso'), false, 'open');
108
+		}
109
+		if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
110
+			$this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field('post_content_filtered',
111
+				__('Post Content Filtered', 'event_espresso'), false, '');
112
+		}
113
+		if ( ! isset($this->_model_relations['Post_Meta'])) {
114
+			//don't block deletes though because we want to maintain the current behaviour
115
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
116
+		}
117
+		if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
118
+			//nothing was set during child constructor, so set default
119
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
120
+		}
121
+		if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
122
+			//nothing was set during child constructor, so set default
123
+			//it's ok for child classes to specify this, but generally this is more DRY
124
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
125
+		}
126
+		parent::__construct($timezone);
127
+	}
128
+
129
+
130
+
131
+	/**
132
+	 * @return array
133
+	 */
134
+	public function public_event_stati()
135
+	{
136
+		// @see wp-includes/post.php
137
+		return get_post_stati(array('public' => true));
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
144
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
145
+	 *
146
+	 * @return string
147
+	 * @throws EE_Error
148
+	 */
149
+	public function deleted_field_name()
150
+	{
151
+		throw new EE_Error(sprintf(__("EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
152
+			"event_espresso")));
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * Gets the field's name that sets the post status
159
+	 *
160
+	 * @return string
161
+	 * @throws EE_Error
162
+	 */
163
+	public function post_status_field_name()
164
+	{
165
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
166
+		if ($field) {
167
+			return $field->get_name();
168
+		} else {
169
+			throw new EE_Error(sprintf(__('We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
170
+				'event_espresso'), get_class($this), get_class($this)));
171
+		}
172
+	}
173
+
174
+
175
+
176
+	/**
177
+	 * Alters the query params so that only trashed/soft-deleted items are considered
178
+	 *
179
+	 * @param array $query_params like EEM_Base::get_all's $query_params
180
+	 * @return array like EEM_Base::get_all's $query_params
181
+	 */
182
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
183
+	{
184
+		$post_status_field_name = $this->post_status_field_name();
185
+		$query_params[0][$post_status_field_name] = self::post_status_trashed;
186
+		return $query_params;
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * Alters the query params so each item's deleted status is ignored.
193
+	 *
194
+	 * @param array $query_params
195
+	 * @return array
196
+	 */
197
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
198
+	{
199
+		$query_params['default_where_conditions'] = 'minimum';
200
+		return $query_params;
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
207
+	 *
208
+	 * @param boolean $delete       true to indicate deletion, false to indicate restoration
209
+	 * @param array   $query_params like EEM_Base::get_all
210
+	 * @return boolean success
211
+	 */
212
+	function delete_or_restore($delete = true, $query_params = array())
213
+	{
214
+		$post_status_field_name = $this->post_status_field_name();
215
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
216
+		$new_status = $delete ? self::post_status_trashed : 'draft';
217
+		if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
218
+			return true;
219
+		} else {
220
+			return false;
221
+		}
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * meta_table
228
+	 * returns first EE_Secondary_Table table name
229
+	 *
230
+	 * @access public
231
+	 * @return string
232
+	 */
233
+	public function meta_table()
234
+	{
235
+		$meta_table = $this->_get_other_tables();
236
+		$meta_table = reset($meta_table);
237
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
244
+	 *
245
+	 * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
246
+	 *                   db only fields)
247
+	 * @return array
248
+	 */
249
+	public function get_meta_table_fields($all = false)
250
+	{
251
+		$all_fields = $fields_to_return = array();
252
+		foreach ($this->_tables as $alias => $table_obj) {
253
+			if ($table_obj instanceof EE_Secondary_Table) {
254
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
255
+			}
256
+		}
257
+		if ( ! $all) {
258
+			foreach ($all_fields as $name => $obj) {
259
+				if ($obj instanceof EE_DB_Only_Field_Base) {
260
+					continue;
261
+				}
262
+				$fields_to_return[] = $name;
263
+			}
264
+		} else {
265
+			$fields_to_return = array_keys($all_fields);
266
+		}
267
+		return $fields_to_return;
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * Adds an event category with the specified name and description to the specified
274
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
275
+	 * and adds an entry in the term_relationship if necessary.
276
+	 *
277
+	 * @param EE_CPT_Base $cpt_model_object
278
+	 * @param string      $category_name (used to derive the term slug too)
279
+	 * @param string      $category_description
280
+	 * @param int         $parent_term_taxonomy_id
281
+	 * @return EE_Term_Taxonomy
282
+	 */
283
+	function add_event_category(
284
+		EE_CPT_Base $cpt_model_object,
285
+		$category_name,
286
+		$category_description = '',
287
+		$parent_term_taxonomy_id = null
288
+	) {
289
+		//create term
290
+		require_once(EE_MODELS . 'EEM_Term.model.php');
291
+		//first, check for a term by the same name or slug
292
+		$category_slug = sanitize_title($category_name);
293
+		$term = EEM_Term::instance()->get_one(array(
294
+			array(
295
+				'OR' => array(
296
+					'name' => $category_name,
297
+					'slug' => $category_slug,
298
+				),
299
+			),
300
+		));
301
+		if ( ! $term) {
302
+			$term = EE_Term::new_instance(array(
303
+				'name' => $category_name,
304
+				'slug' => $category_slug,
305
+			));
306
+			$term->save();
307
+		}
308
+		//make sure there's a term-taxonomy entry too
309
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
310
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311
+			array(
312
+				'term_id'  => $term->ID(),
313
+				'taxonomy' => EE_Event_Category_Taxonomy,
314
+			),
315
+		));
316
+		/** @var $term_taxonomy EE_Term_Taxonomy */
317
+		if ( ! $term_taxonomy) {
318
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(array(
319
+				'term_id'     => $term->ID(),
320
+				'taxonomy'    => EE_Event_Category_Taxonomy,
321
+				'description' => $category_description,
322
+				'count'       => 1,
323
+				'parent'      => $parent_term_taxonomy_id,
324
+			));
325
+			$term_taxonomy->save();
326
+		} else {
327
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
328
+			$term_taxonomy->save();
329
+		}
330
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * Removed the category specified by name as having a relation to this event.
337
+	 * Does not remove the term or term_taxonomy.
338
+	 *
339
+	 * @param EE_CPT_Base $cpt_model_object_event
340
+	 * @param string      $category_name name of the event category (term)
341
+	 * @return bool
342
+	 */
343
+	function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
344
+	{
345
+		//find the term_taxonomy by that name
346
+		$term_taxonomy = $this->get_first_related($cpt_model_object_event, 'Term_Taxonomy',
347
+			array(array('Term.name' => $category_name, 'taxonomy' => EE_Event_Category_Taxonomy)));
348
+		/** @var $term_taxonomy EE_Term_Taxonomy */
349
+		if ($term_taxonomy) {
350
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
351
+			$term_taxonomy->save();
352
+		}
353
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
360
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
361
+	 *
362
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
363
+	 * @access public
364
+	 * @param int          $id   the ID for the cpt we want the feature image for
365
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
366
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
367
+	 * @param string|array $attr Optional. Query string or array of attributes.
368
+	 * @return string HTML image element
369
+	 */
370
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
371
+	{
372
+		return get_the_post_thumbnail($id, $size, $attr);
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * Just a handy way to get the list of post statuses currently registered with WP.
379
+	 *
380
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
381
+	 * @return array
382
+	 */
383
+	public function get_post_statuses()
384
+	{
385
+		global $wp_post_statuses;
386
+		$statuses = array();
387
+		foreach ($wp_post_statuses as $post_status => $args_object) {
388
+			$statuses[$post_status] = $args_object->label;
389
+		}
390
+		return $statuses;
391
+	}
392
+
393
+
394
+
395
+	/**
396
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
397
+	 *
398
+	 * @return array array of statuses.
399
+	 */
400
+	public function get_status_array()
401
+	{
402
+		$statuses = $this->get_post_statuses();
403
+		//first the global filter
404
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405
+		//now the class specific filter
406
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
407
+		return $statuses;
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * this returns the post statuses that are NOT the default wordpress status
414
+	 *
415
+	 * @return array
416
+	 */
417
+	public function get_custom_post_statuses()
418
+	{
419
+		$new_stati = array();
420
+		foreach ($this->_custom_stati as $status => $props) {
421
+			$new_stati[$status] = $props['label'];
422
+		}
423
+		return $new_stati;
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
430
+	 * are a row from the posts table. If we're missing any fields required for the model,
431
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
432
+	 * make sure you are attaching all the model's fields onto the post)
433
+	 *
434
+	 * @param WP_Post|array $post
435
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
436
+	 */
437
+	public function instantiate_class_from_post_object_orig($post)
438
+	{
439
+		$post = (array)$post;
440
+		$has_all_necessary_fields_for_table = true;
441
+		//check if the post has fields on the meta table already
442
+		foreach ($this->_get_other_tables() as $table_obj) {
443
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
444
+			foreach ($fields_for_that_table as $field_obj) {
445
+				if ( ! isset($post[$field_obj->get_table_column()])
446
+					 && ! isset($post[$field_obj->get_qualified_column()])
447
+				) {
448
+					$has_all_necessary_fields_for_table = false;
449
+				}
450
+			}
451
+		}
452
+		//if we don't have all the fields we need, then just fetch the proper model from the DB
453
+		if ( ! $has_all_necessary_fields_for_table) {
454
+			return $this->get_one_by_ID($post['ID']);
455
+		} else {
456
+			return $this->instantiate_class_from_array_or_object($post);
457
+		}
458
+	}
459
+
460
+
461
+
462
+	/**
463
+	 * @param null $post
464
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
465
+	 */
466
+	public function instantiate_class_from_post_object($post = null)
467
+	{
468
+		if (empty($post)) {
469
+			global $post;
470
+		}
471
+		$post = (array)$post;
472
+		$tables_needing_to_be_queried = array();
473
+		//check if the post has fields on the meta table already
474
+		foreach ($this->get_tables() as $table_obj) {
475
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
476
+			foreach ($fields_for_that_table as $field_obj) {
477
+				if ( ! isset($post[$field_obj->get_table_column()])
478
+					 && ! isset($post[$field_obj->get_qualified_column()])
479
+				) {
480
+					$tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
481
+				}
482
+			}
483
+		}
484
+		//if we don't have all the fields we need, then just fetch the proper model from the DB
485
+		if ($tables_needing_to_be_queried) {
486
+			if (count($tables_needing_to_be_queried) == 1
487
+				&& reset($tables_needing_to_be_queried)
488
+				   instanceof
489
+				   EE_Secondary_Table
490
+			) {
491
+				//so we're only missing data from a secondary table. Well that's not too hard to query for
492
+				$table_to_query = reset($tables_needing_to_be_queried);
493
+				$missing_data = $this->_do_wpdb_query('get_row', array(
494
+					'SELECT * FROM '
495
+					. $table_to_query->get_table_name()
496
+					. ' WHERE '
497
+					. $table_to_query->get_fk_on_table()
498
+					. ' = '
499
+					. $post['ID'],
500
+					ARRAY_A,
501
+				));
502
+				if ( ! empty($missing_data)) {
503
+					$post = array_merge($post, $missing_data);
504
+				}
505
+			} else {
506
+				return $this->get_one_by_ID($post['ID']);
507
+			}
508
+		}
509
+		return $this->instantiate_class_from_array_or_object($post);
510
+	}
511
+
512
+
513
+
514
+	/**
515
+	 * Gets the post type associated with this
516
+	 *
517
+	 * @throws EE_Error
518
+	 * @return string
519
+	 */
520
+	public function post_type()
521
+	{
522
+		$post_type_field = null;
523
+		foreach ($this->field_settings(true) as $field_obj) {
524
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
525
+				$post_type_field = $field_obj;
526
+				break;
527
+			}
528
+		}
529
+		if ($post_type_field == null) {
530
+			throw new EE_Error(sprintf(__("CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
531
+				"event_espresso"), get_class($this)));
532
+		}
533
+		return $post_type_field->get_default_value();
534
+	}
535 535
 
536 536
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
         $parent_term_taxonomy_id = null
288 288
     ) {
289 289
         //create term
290
-        require_once(EE_MODELS . 'EEM_Term.model.php');
290
+        require_once(EE_MODELS.'EEM_Term.model.php');
291 291
         //first, check for a term by the same name or slug
292 292
         $category_slug = sanitize_title($category_name);
293 293
         $term = EEM_Term::instance()->get_one(array(
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
             $term->save();
307 307
         }
308 308
         //make sure there's a term-taxonomy entry too
309
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
309
+        require_once(EE_MODELS.'EEM_Term_Taxonomy.model.php');
310 310
         $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311 311
             array(
312 312
                 'term_id'  => $term->ID(),
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
         //first the global filter
404 404
         $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405 405
         //now the class specific filter
406
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
406
+        $statuses = apply_filters('FHEE_EEM_'.get_class($this).'__get_status_array', $statuses);
407 407
         return $statuses;
408 408
     }
409 409
 
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
      */
437 437
     public function instantiate_class_from_post_object_orig($post)
438 438
     {
439
-        $post = (array)$post;
439
+        $post = (array) $post;
440 440
         $has_all_necessary_fields_for_table = true;
441 441
         //check if the post has fields on the meta table already
442 442
         foreach ($this->_get_other_tables() as $table_obj) {
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
         if (empty($post)) {
469 469
             global $post;
470 470
         }
471
-        $post = (array)$post;
471
+        $post = (array) $post;
472 472
         $tables_needing_to_be_queried = array();
473 473
         //check if the post has fields on the meta table already
474 474
         foreach ($this->get_tables() as $table_obj) {
Please login to merge, or discard this patch.
core/db_models/EEM_Venue.model.php 2 patches
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,87 +25,87 @@  discard block
 block discarded – undo
25 25
 class EEM_Venue extends EEM_CPT_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32 32
 
33
-    protected function __construct($timezone = null)
34
-    {
35
-        $this->singular_item = __('Venue', 'event_espresso');
36
-        $this->plural_item = __('Venues', 'event_espresso');
37
-        $this->_tables = array(
38
-            'Venue_CPT'  => new EE_Primary_Table('posts', 'ID'),
39
-            'Venue_Meta' => new EE_Secondary_Table('esp_venue_meta', 'VNUM_ID', 'VNU_ID'),
40
-        );
41
-        $this->_fields = array(
42
-            'Venue_CPT'  => array(
43
-                'VNU_ID'         => new EE_Primary_Key_Int_Field('ID', __("Venue ID", "event_espresso")),
44
-                'VNU_name'       => new EE_Plain_Text_Field('post_title', __("Venue Name", "event_espresso"), false,
45
-                    ''),
46
-                'VNU_desc'       => new EE_Post_Content_Field('post_content', __("Venue Description", "event_espresso"),
47
-                    false, ''),
48
-                'VNU_identifier' => new EE_Slug_Field('post_name', __("Venue Identifier", "event_espresso"), false, ''),
49
-                'VNU_created'    => new EE_Datetime_Field('post_date', __("Date Venue Created", "event_espresso"),
50
-                    false, EE_Datetime_Field::now),
51
-                'VNU_short_desc' => new EE_Plain_Text_Field('post_excerpt',
52
-                    __("Short Description of Venue", "event_espresso"), true, ''),
53
-                'VNU_modified'   => new EE_Datetime_Field('post_modified', __("Venue Modified Date", "event_espresso"),
54
-                    false, EE_Datetime_Field::now),
55
-                'VNU_wp_user'    => new EE_WP_User_Field('post_author', __("Venue Creator ID", "event_espresso"),
56
-                    false),
57
-                'parent'         => new EE_Integer_Field('post_parent', __("Venue Parent ID", "event_espresso"), false,
58
-                    0),
59
-                'VNU_order'      => new EE_Integer_Field('menu_order', __("Venue order", "event_espresso"), false, 1),
60
-                'post_type'      => new EE_WP_Post_Type_Field('espresso_venues'),
61
-                // EE_Plain_Text_Field('post_type', __("Venue post type", "event_espresso"), false, 'espresso_venues'),
62
-            ),
63
-            'Venue_Meta' => array(
64
-                'VNUM_ID'             => new EE_DB_Only_Int_Field('VNUM_ID',
65
-                    __("ID of Venue Meta Row", "event_espresso"), false),
66
-                'VNU_ID_fk'           => new EE_DB_Only_Int_Field('VNU_ID',
67
-                    __("Foreign Key to Venue Post ", "event_espresso"), false),
68
-                'VNU_address'         => new EE_Plain_Text_Field('VNU_address',
69
-                    __("Venue Address line 1", "event_espresso"), true, ''),
70
-                'VNU_address2'        => new EE_Plain_Text_Field('VNU_address2',
71
-                    __("Venue Address line 2", "event_espresso"), true, ''),
72
-                'VNU_city'            => new EE_Plain_Text_Field('VNU_city', __("Venue City", "event_espresso"), true,
73
-                    ''),
74
-                'STA_ID'              => new EE_Foreign_Key_Int_Field('STA_ID', __("State ID", "event_espresso"), true,
75
-                    null, 'State'),
76
-                'CNT_ISO'             => new EE_Foreign_Key_String_Field('CNT_ISO',
77
-                    __("Country Code", "event_espresso"), true, null, 'Country'),
78
-                'VNU_zip'             => new EE_Plain_Text_Field('VNU_zip',
79
-                    __("Venue Zip/Postal Code", "event_espresso"), true),
80
-                'VNU_phone'           => new EE_Plain_Text_Field('VNU_phone', __("Venue Phone", "event_espresso"),
81
-                    true),
82
-                'VNU_capacity'        => new EE_Infinite_Integer_Field('VNU_capacity',
83
-                    __("Venue Capacity", "event_espresso"), true, EE_INF),
84
-                'VNU_url'             => new EE_Plain_Text_Field('VNU_url', __('Venue Website', 'event_espresso'),
85
-                    true),
86
-                'VNU_virtual_phone'   => new EE_Plain_Text_Field('VNU_virtual_phone',
87
-                    __('Call in Number', 'event_espresso'), true),
88
-                'VNU_virtual_url'     => new EE_Plain_Text_Field('VNU_virtual_url', __('Virtual URL', 'event_espresso'),
89
-                    true),
90
-                'VNU_google_map_link' => new EE_Plain_Text_Field('VNU_google_map_link',
91
-                    __('Google Map Link', 'event_espresso'), true),
92
-                'VNU_enable_for_gmap' => new EE_Boolean_Field('VNU_enable_for_gmap',
93
-                    __('Show Google Map?', 'event_espresso'), false, false),
94
-            ),
95
-        );
96
-        $this->_model_relations = array(
97
-            'Event'             => new EE_HABTM_Relation('Event_Venue'),
98
-            'State'             => new EE_Belongs_To_Relation(),
99
-            'Country'           => new EE_Belongs_To_Relation(),
100
-            'Event_Venue'       => new EE_Has_Many_Relation(),
101
-            'WP_User'           => new EE_Belongs_To_Relation(),
102
-            'Term_Relationship' => new EE_Has_Many_Relation(),
103
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
104
-        );
105
-        //this model is generally available for reading
106
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
107
-        parent::__construct($timezone);
108
-    }
33
+	protected function __construct($timezone = null)
34
+	{
35
+		$this->singular_item = __('Venue', 'event_espresso');
36
+		$this->plural_item = __('Venues', 'event_espresso');
37
+		$this->_tables = array(
38
+			'Venue_CPT'  => new EE_Primary_Table('posts', 'ID'),
39
+			'Venue_Meta' => new EE_Secondary_Table('esp_venue_meta', 'VNUM_ID', 'VNU_ID'),
40
+		);
41
+		$this->_fields = array(
42
+			'Venue_CPT'  => array(
43
+				'VNU_ID'         => new EE_Primary_Key_Int_Field('ID', __("Venue ID", "event_espresso")),
44
+				'VNU_name'       => new EE_Plain_Text_Field('post_title', __("Venue Name", "event_espresso"), false,
45
+					''),
46
+				'VNU_desc'       => new EE_Post_Content_Field('post_content', __("Venue Description", "event_espresso"),
47
+					false, ''),
48
+				'VNU_identifier' => new EE_Slug_Field('post_name', __("Venue Identifier", "event_espresso"), false, ''),
49
+				'VNU_created'    => new EE_Datetime_Field('post_date', __("Date Venue Created", "event_espresso"),
50
+					false, EE_Datetime_Field::now),
51
+				'VNU_short_desc' => new EE_Plain_Text_Field('post_excerpt',
52
+					__("Short Description of Venue", "event_espresso"), true, ''),
53
+				'VNU_modified'   => new EE_Datetime_Field('post_modified', __("Venue Modified Date", "event_espresso"),
54
+					false, EE_Datetime_Field::now),
55
+				'VNU_wp_user'    => new EE_WP_User_Field('post_author', __("Venue Creator ID", "event_espresso"),
56
+					false),
57
+				'parent'         => new EE_Integer_Field('post_parent', __("Venue Parent ID", "event_espresso"), false,
58
+					0),
59
+				'VNU_order'      => new EE_Integer_Field('menu_order', __("Venue order", "event_espresso"), false, 1),
60
+				'post_type'      => new EE_WP_Post_Type_Field('espresso_venues'),
61
+				// EE_Plain_Text_Field('post_type', __("Venue post type", "event_espresso"), false, 'espresso_venues'),
62
+			),
63
+			'Venue_Meta' => array(
64
+				'VNUM_ID'             => new EE_DB_Only_Int_Field('VNUM_ID',
65
+					__("ID of Venue Meta Row", "event_espresso"), false),
66
+				'VNU_ID_fk'           => new EE_DB_Only_Int_Field('VNU_ID',
67
+					__("Foreign Key to Venue Post ", "event_espresso"), false),
68
+				'VNU_address'         => new EE_Plain_Text_Field('VNU_address',
69
+					__("Venue Address line 1", "event_espresso"), true, ''),
70
+				'VNU_address2'        => new EE_Plain_Text_Field('VNU_address2',
71
+					__("Venue Address line 2", "event_espresso"), true, ''),
72
+				'VNU_city'            => new EE_Plain_Text_Field('VNU_city', __("Venue City", "event_espresso"), true,
73
+					''),
74
+				'STA_ID'              => new EE_Foreign_Key_Int_Field('STA_ID', __("State ID", "event_espresso"), true,
75
+					null, 'State'),
76
+				'CNT_ISO'             => new EE_Foreign_Key_String_Field('CNT_ISO',
77
+					__("Country Code", "event_espresso"), true, null, 'Country'),
78
+				'VNU_zip'             => new EE_Plain_Text_Field('VNU_zip',
79
+					__("Venue Zip/Postal Code", "event_espresso"), true),
80
+				'VNU_phone'           => new EE_Plain_Text_Field('VNU_phone', __("Venue Phone", "event_espresso"),
81
+					true),
82
+				'VNU_capacity'        => new EE_Infinite_Integer_Field('VNU_capacity',
83
+					__("Venue Capacity", "event_espresso"), true, EE_INF),
84
+				'VNU_url'             => new EE_Plain_Text_Field('VNU_url', __('Venue Website', 'event_espresso'),
85
+					true),
86
+				'VNU_virtual_phone'   => new EE_Plain_Text_Field('VNU_virtual_phone',
87
+					__('Call in Number', 'event_espresso'), true),
88
+				'VNU_virtual_url'     => new EE_Plain_Text_Field('VNU_virtual_url', __('Virtual URL', 'event_espresso'),
89
+					true),
90
+				'VNU_google_map_link' => new EE_Plain_Text_Field('VNU_google_map_link',
91
+					__('Google Map Link', 'event_espresso'), true),
92
+				'VNU_enable_for_gmap' => new EE_Boolean_Field('VNU_enable_for_gmap',
93
+					__('Show Google Map?', 'event_espresso'), false, false),
94
+			),
95
+		);
96
+		$this->_model_relations = array(
97
+			'Event'             => new EE_HABTM_Relation('Event_Venue'),
98
+			'State'             => new EE_Belongs_To_Relation(),
99
+			'Country'           => new EE_Belongs_To_Relation(),
100
+			'Event_Venue'       => new EE_Has_Many_Relation(),
101
+			'WP_User'           => new EE_Belongs_To_Relation(),
102
+			'Term_Relationship' => new EE_Has_Many_Relation(),
103
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
104
+		);
105
+		//this model is generally available for reading
106
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
107
+		parent::__construct($timezone);
108
+	}
109 109
 
110 110
 }
111 111
 // End of file EEM_Venue.model.php
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@
 block discarded – undo
18 18
  * @author                Michael Nelson
19 19
  *                        ------------------------------------------------------------------------
20 20
  */
21
-require_once(EE_MODELS . 'EEM_Base.model.php');
21
+require_once(EE_MODELS.'EEM_Base.model.php');
22 22
 
23 23
 
24 24
 
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/JobParameters.php 1 patch
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -96,12 +96,12 @@  discard block
 block discarded – undo
96 96
 	 * @param array $request_data
97 97
 	 * @param array $extra_data
98 98
 	 */
99
-	function __construct( $job_id, $classname, $request_data, $extra_data = array() ) {
100
-		$this->set_job_id( $job_id );
101
-		$this->set_classname( $classname );
102
-		$this->set_request_data( $request_data );
103
-		$this->set_extra_data( $extra_data );
104
-		$this->set_status( JobParameters::status_continue );
99
+	function __construct($job_id, $classname, $request_data, $extra_data = array()) {
100
+		$this->set_job_id($job_id);
101
+		$this->set_classname($classname);
102
+		$this->set_request_data($request_data);
103
+		$this->set_extra_data($extra_data);
104
+		$this->set_status(JobParameters::status_continue);
105 105
 	}
106 106
 
107 107
 
@@ -126,12 +126,12 @@  discard block
 block discarded – undo
126 126
 	 * @param boolean $first
127 127
 	 * @return boolean success
128 128
 	 */
129
-	function save( $first = false ) {
130
-		$object_vars = get_object_vars( $this );
131
-		if( $first ) {
132
-			return add_option( $this->option_name(), $object_vars, null, 'no' );
133
-		} else{
134
-			return update_option( $this->option_name(), $object_vars );
129
+	function save($first = false) {
130
+		$object_vars = get_object_vars($this);
131
+		if ($first) {
132
+			return add_option($this->option_name(), $object_vars, null, 'no');
133
+		} else {
134
+			return update_option($this->option_name(), $object_vars);
135 135
 		}
136 136
 	}
137 137
 
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 * @return boolean
144 144
 	 */
145 145
 	function delete() {
146
-		return delete_option( $this->option_name() );
146
+		return delete_option($this->option_name());
147 147
 	}
148 148
 
149 149
 
@@ -154,26 +154,26 @@  discard block
 block discarded – undo
154 154
 	 * @return JobParameters
155 155
 	 * @throws BatchRequestException
156 156
 	 */
157
-	static function load( $job_id ) {
158
-		$job_parameter_vars = get_option( JobParameters::wp_option_prefix . $job_id );
159
-		if(
160
-			! is_array( $job_parameter_vars ) ||
161
-			! isset( $job_parameter_vars[ '_classname' ] ) ||
162
-			! isset( $job_parameter_vars[ '_request_data' ] )
157
+	static function load($job_id) {
158
+		$job_parameter_vars = get_option(JobParameters::wp_option_prefix.$job_id);
159
+		if (
160
+			! is_array($job_parameter_vars) ||
161
+			! isset($job_parameter_vars['_classname']) ||
162
+			! isset($job_parameter_vars['_request_data'])
163 163
 		) {
164 164
 			throw new BatchRequestException(
165 165
 				sprintf(
166 166
 					__('Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s', 'event_espresso'),
167 167
 					$job_id,
168
-					get_option( JobParameters::wp_option_prefix . $job_id )
168
+					get_option(JobParameters::wp_option_prefix.$job_id)
169 169
 				)
170 170
 			);
171 171
 		}
172 172
 		$job_parameters = new JobParameters(
173 173
 				$job_id,
174
-				$job_parameter_vars[ '_classname' ],
175
-				$job_parameter_vars[ '_request_data'] );
176
-		foreach( $job_parameter_vars as $key => $value ) {
174
+				$job_parameter_vars['_classname'],
175
+				$job_parameter_vars['_request_data'] );
176
+		foreach ($job_parameter_vars as $key => $value) {
177 177
 			$job_parameters->{$key} = $value;
178 178
 		}
179 179
 		return $job_parameters;
@@ -217,9 +217,9 @@  discard block
 block discarded – undo
217 217
 	 * @param string|array $default
218 218
 	 * @return string|array
219 219
 	 */
220
-	function request_datum( $key, $default = '' ) {
221
-		if( isset( $this->_request_data[ $key ] ) ) {
222
-			return $this->_request_data[ $key ];
220
+	function request_datum($key, $default = '') {
221
+		if (isset($this->_request_data[$key])) {
222
+			return $this->_request_data[$key];
223 223
 		} else {
224 224
 			return $default;
225 225
 		}
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 	 * @param string|array $default
234 234
 	 * @return string|array
235 235
 	 */
236
-	function extra_datum( $key, $default = '' ) {
237
-		if( isset( $this->_extra_data[ $key ] ) ) {
238
-			return $this->_extra_data[ $key ];
236
+	function extra_datum($key, $default = '') {
237
+		if (isset($this->_extra_data[$key])) {
238
+			return $this->_extra_data[$key];
239 239
 		} else {
240 240
 			return $default;
241 241
 		}
@@ -248,8 +248,8 @@  discard block
 block discarded – undo
248 248
 	 * @param string $key
249 249
 	 * @param string|int|array|null $value almost any extra data you want to store
250 250
 	 */
251
-	function add_extra_data( $key, $value ) {
252
-		$this->_extra_data[ $key ] = $value;
251
+	function add_extra_data($key, $value) {
252
+		$this->_extra_data[$key] = $value;
253 253
 	}
254 254
 
255 255
 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 	 * Sets the job size. You decide what units to use
279 279
 	 * @param int $size
280 280
 	 */
281
-	function set_job_size( $size ) {
281
+	function set_job_size($size) {
282 282
 		$this->_job_size = $size;
283 283
 	}
284 284
 
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 	 * @param int $newly_processed
300 300
 	 * @return int updated units processed
301 301
 	 */
302
-	function mark_processed( $newly_processed ) {
302
+	function mark_processed($newly_processed) {
303 303
 		$this->_units_processed += $newly_processed;
304 304
 		return $this->_units_processed;
305 305
 	}
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	 * Sets the total count of units processed. You might prefer to use mark_processed
311 311
 	 * @param int $total_units_processed
312 312
 	 */
313
-	function set_units_processed( $total_units_processed ) {
313
+	function set_units_processed($total_units_processed) {
314 314
 		$this->_units_processed = $total_units_processed;
315 315
 	}
316 316
 
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	 * Sets the job's ID
321 321
 	 * @param string $job_id
322 322
 	 */
323
-	function set_job_id( $job_id ) {
323
+	function set_job_id($job_id) {
324 324
 		$this->_job_id = $job_id;
325 325
 	}
326 326
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	 * sets the classname
331 331
 	 * @param string $classname
332 332
 	 */
333
-	function set_classname( $classname ) {
333
+	function set_classname($classname) {
334 334
 		$this->_classname = $classname;
335 335
 	}
336 336
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 	 * Sets the request data
341 341
 	 * @param array $request_data
342 342
 	 */
343
-	function set_request_data( $request_data ) {
343
+	function set_request_data($request_data) {
344 344
 		$this->_request_data = $request_data;
345 345
 	}
346 346
 
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 	 * Sets the array of extra data we want to store on this request
351 351
 	 * @param array $extra_data
352 352
 	 */
353
-	function set_extra_data( $extra_data ) {
353
+	function set_extra_data($extra_data) {
354 354
 		$this->_extra_data = $extra_data;
355 355
 	}
356 356
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 * @return string
362 362
 	 */
363 363
 	function option_name() {
364
-		return JobParameters::wp_option_prefix . $this->job_id();
364
+		return JobParameters::wp_option_prefix.$this->job_id();
365 365
 	}
366 366
 
367 367
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 *
381 381
 	 * @param string $status on eof JobParameters::valid_stati()
382 382
 	 */
383
-	public function set_status( $status ) {
383
+	public function set_status($status) {
384 384
 		$this->_status = $status;
385 385
 	}
386 386
 
Please login to merge, or discard this patch.
core/domain/entities/DbSafeDateTime.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -1,8 +1,8 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 namespace EventEspresso\core\domain\entities;
3 3
 
4
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
5
-	exit( 'No direct script access allowed' );
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -47,20 +47,20 @@  discard block
 block discarded – undo
47 47
     {
48 48
         // if the folder path is writable, then except the path + filename, else keep empty
49 49
         $this->_error_log_dir = is_writable(str_replace(basename($error_log_dir), '', $error_log_dir))
50
-            ?  $error_log_dir
50
+            ? $error_log_dir
51 51
             : '';
52 52
     }
53 53
 
54 54
 
55 55
 
56 56
 	public function __toString() {
57
-		return $this->format( DbSafeDateTime::db_safe_timestamp_format );
57
+		return $this->format(DbSafeDateTime::db_safe_timestamp_format);
58 58
 	}
59 59
 
60 60
 
61 61
 
62 62
 	public function __sleep() {
63
-		$this->_datetime_string = $this->format( DbSafeDateTime::db_safe_timestamp_format );
63
+		$this->_datetime_string = $this->format(DbSafeDateTime::db_safe_timestamp_format);
64 64
         $date = \DateTime::createFromFormat(DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string);
65 65
         if ( ! $date instanceof \DateTime) {
66 66
             try {
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
                 )
84 84
             );
85 85
         }
86
-        return array( '_datetime_string' );
86
+        return array('_datetime_string');
87 87
 	}
88 88
 
89 89
 
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
         // but still result in the internal date for that object being set to "-0001-11-30 10:00:00.000000".
97 97
         // so we're no better off, but at least things won't go fatal on us.
98 98
         $this->_datetime_string = str_replace('-0001-11-30', '0000-00-00', $this->_datetime_string);
99
-		$date = \DateTime::createFromFormat( DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string );
99
+		$date = \DateTime::createFromFormat(DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string);
100 100
 		if ( ! $date instanceof \DateTime) {
101 101
             $this->writeToErrorLog(
102 102
                 sprintf(
Please login to merge, or discard this patch.
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -32,24 +32,24 @@  discard block
 block discarded – undo
32 32
 	protected $_datetime_string = '';
33 33
 
34 34
 	/**
35
-     * where to write the error log to
36
-     *
37
-     * @type string $_error_log_dir
35
+	 * where to write the error log to
36
+	 *
37
+	 * @type string $_error_log_dir
38 38
 	 */
39 39
 	protected $_error_log_dir = '';
40 40
 
41 41
 
42 42
 
43
-    /**
44
-     * @param string $error_log_dir
45
-     */
46
-    public function setErrorLogDir($error_log_dir)
47
-    {
48
-        // if the folder path is writable, then except the path + filename, else keep empty
49
-        $this->_error_log_dir = is_writable(str_replace(basename($error_log_dir), '', $error_log_dir))
50
-            ?  $error_log_dir
51
-            : '';
52
-    }
43
+	/**
44
+	 * @param string $error_log_dir
45
+	 */
46
+	public function setErrorLogDir($error_log_dir)
47
+	{
48
+		// if the folder path is writable, then except the path + filename, else keep empty
49
+		$this->_error_log_dir = is_writable(str_replace(basename($error_log_dir), '', $error_log_dir))
50
+			?  $error_log_dir
51
+			: '';
52
+	}
53 53
 
54 54
 
55 55
 
@@ -61,84 +61,84 @@  discard block
 block discarded – undo
61 61
 
62 62
 	public function __sleep() {
63 63
 		$this->_datetime_string = $this->format( DbSafeDateTime::db_safe_timestamp_format );
64
-        $date = \DateTime::createFromFormat(DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string);
65
-        if ( ! $date instanceof \DateTime) {
66
-            try {
67
-                // we want a stack trace to determine where the malformed date came from, so...
68
-                throw new \DomainException();
69
-            } catch (\DomainException $e) {
70
-                $stack_trace = $e->getTraceAsString();
71
-            }
72
-            $this->writeToErrorLog(
73
-                sprintf(
74
-                    __(
75
-                        'A valid DateTime could not be generated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s %2$s Stack Trace: %5$s',
76
-                        'event_espresso'
77
-                    ),
78
-                    $this->_datetime_string,
79
-                    '<br />',
80
-                    print_r(\DateTime::getLastErrors(), true),
81
-                    PHP_VERSION,
82
-                    $stack_trace
83
-                )
84
-            );
85
-        }
86
-        return array( '_datetime_string' );
64
+		$date = \DateTime::createFromFormat(DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string);
65
+		if ( ! $date instanceof \DateTime) {
66
+			try {
67
+				// we want a stack trace to determine where the malformed date came from, so...
68
+				throw new \DomainException();
69
+			} catch (\DomainException $e) {
70
+				$stack_trace = $e->getTraceAsString();
71
+			}
72
+			$this->writeToErrorLog(
73
+				sprintf(
74
+					__(
75
+						'A valid DateTime could not be generated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s %2$s Stack Trace: %5$s',
76
+						'event_espresso'
77
+					),
78
+					$this->_datetime_string,
79
+					'<br />',
80
+					print_r(\DateTime::getLastErrors(), true),
81
+					PHP_VERSION,
82
+					$stack_trace
83
+				)
84
+			);
85
+		}
86
+		return array( '_datetime_string' );
87 87
 	}
88 88
 
89 89
 
90 90
 
91 91
 	public function __wakeup() {
92
-	    // if an empty or null value got saved to the db for a datetime,
93
-        // then some servers and/or PHP itself will incorrectly convert that date string
94
-        // resulting in "-0001-11-30" for the year-month-day.
95
-        // We'll replace those with "0000-00-00" which will allow a valid DateTime object to be created,
96
-        // but still result in the internal date for that object being set to "-0001-11-30 10:00:00.000000".
97
-        // so we're no better off, but at least things won't go fatal on us.
98
-        $this->_datetime_string = str_replace('-0001-11-30', '0000-00-00', $this->_datetime_string);
92
+		// if an empty or null value got saved to the db for a datetime,
93
+		// then some servers and/or PHP itself will incorrectly convert that date string
94
+		// resulting in "-0001-11-30" for the year-month-day.
95
+		// We'll replace those with "0000-00-00" which will allow a valid DateTime object to be created,
96
+		// but still result in the internal date for that object being set to "-0001-11-30 10:00:00.000000".
97
+		// so we're no better off, but at least things won't go fatal on us.
98
+		$this->_datetime_string = str_replace('-0001-11-30', '0000-00-00', $this->_datetime_string);
99 99
 		$date = \DateTime::createFromFormat( DbSafeDateTime::db_safe_timestamp_format, $this->_datetime_string );
100 100
 		if ( ! $date instanceof \DateTime) {
101
-            $this->writeToErrorLog(
102
-                sprintf(
103
-                    __(
104
-                        'A valid DateTime could not be recreated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s',
105
-                        'event_espresso'
106
-                    ),
107
-                    $this->_datetime_string,
108
-                    '<br />',
109
-                    print_r(\DateTime::getLastErrors(), true),
110
-                    PHP_VERSION
111
-                )
112
-            );
113
-        } else {
114
-            $this->__construct(
115
-                $date->format(\EE_Datetime_Field::mysql_timestamp_format),
116
-                new \DateTimeZone($date->format('e'))
117
-            );
118
-        }
101
+			$this->writeToErrorLog(
102
+				sprintf(
103
+					__(
104
+						'A valid DateTime could not be recreated from "%1$s" because the following errors occurred: %2$s %3$s %2$s PHP version: %4$s',
105
+						'event_espresso'
106
+					),
107
+					$this->_datetime_string,
108
+					'<br />',
109
+					print_r(\DateTime::getLastErrors(), true),
110
+					PHP_VERSION
111
+				)
112
+			);
113
+		} else {
114
+			$this->__construct(
115
+				$date->format(\EE_Datetime_Field::mysql_timestamp_format),
116
+				new \DateTimeZone($date->format('e'))
117
+			);
118
+		}
119 119
 	}
120 120
 
121
-    /**
122
-     * Creates a DbSafeDateTime from ye old DateTime
123
-     * @param \DateTime $datetime
124
-     * @return \EventEspresso\core\domain\entities\DbSafeDateTime
125
-     */
126
-    public static function createFromDateTime(\DateTime $datetime)
127
-    {
128
-        return new DbSafeDateTime(
129
-            $datetime->format(\EE_Datetime_Field::mysql_timestamp_format),
130
-            new \DateTimeZone($datetime->format('e'))
131
-        );
132
-    }
133
-
134
-    private function writeToErrorLog($message)
135
-    {
136
-        if ( ! empty($this->_error_log_dir)) {
137
-            error_log($message, 3, $this->_error_log_dir);
138
-        } else {
139
-            error_log($message);
140
-        }
141
-    }
121
+	/**
122
+	 * Creates a DbSafeDateTime from ye old DateTime
123
+	 * @param \DateTime $datetime
124
+	 * @return \EventEspresso\core\domain\entities\DbSafeDateTime
125
+	 */
126
+	public static function createFromDateTime(\DateTime $datetime)
127
+	{
128
+		return new DbSafeDateTime(
129
+			$datetime->format(\EE_Datetime_Field::mysql_timestamp_format),
130
+			new \DateTimeZone($datetime->format('e'))
131
+		);
132
+	}
133
+
134
+	private function writeToErrorLog($message)
135
+	{
136
+		if ( ! empty($this->_error_log_dir)) {
137
+			error_log($message, 3, $this->_error_log_dir);
138
+		} else {
139
+			error_log($message);
140
+		}
141
+	}
142 142
 
143 143
 
144 144
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 /**
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
  * @ version            4.0
13 13
  * ------------------------------------------------------------------------
14 14
  */
15
-require_once(EE_MODELS . 'EEM_Base.model.php');
15
+require_once(EE_MODELS.'EEM_Base.model.php');
16 16
 
17 17
 /**
18 18
  * Class EEM_Status
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
                     false,
50 50
                     'event',
51 51
                     array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
52
+                        'event'        => __("Event", "event_espresso"), //deprecated
53 53
                         'registration' => __("Registration", "event_espresso"),
54 54
                         'transaction'  => __("Transaction", "event_espresso"),
55 55
                         'payment'      => __("Payment", "event_espresso"),
Please login to merge, or discard this patch.
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,291 +25,291 @@  discard block
 block discarded – undo
25 25
 class EEM_Status extends EEM_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32
-    /**
33
-     * @return EEM_Status
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        $this->singular_item    = __('Status', 'event_espresso');
38
-        $this->plural_item      = __('Stati', 'event_espresso');
39
-        $this->_tables          = array(
40
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
-        );
42
-        $this->_fields          = array(
43
-            'StatusTable' => array(
44
-                'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
-                'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
-                'STS_type'     => new EE_Enum_Text_Field(
47
-                    'STS_type',
48
-                    __("Type", "event_espresso"),
49
-                    false,
50
-                    'event',
51
-                    array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
53
-                        'registration' => __("Registration", "event_espresso"),
54
-                        'transaction'  => __("Transaction", "event_espresso"),
55
-                        'payment'      => __("Payment", "event_espresso"),
56
-                        'email'        => __("Email", "event_espresso"),
57
-                        'message'      => __("Message", "event_espresso"),
58
-                    )),
59
-                'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
-                'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
-                'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Registration' => new EE_Has_Many_Relation(),
66
-            'Transaction'  => new EE_Has_Many_Relation(),
67
-            'Payment'      => new EE_Has_Many_Relation(),
68
-        );
69
-        //this model is generally available for reading
70
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
32
+	/**
33
+	 * @return EEM_Status
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		$this->singular_item    = __('Status', 'event_espresso');
38
+		$this->plural_item      = __('Stati', 'event_espresso');
39
+		$this->_tables          = array(
40
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
+		);
42
+		$this->_fields          = array(
43
+			'StatusTable' => array(
44
+				'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
+				'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
+				'STS_type'     => new EE_Enum_Text_Field(
47
+					'STS_type',
48
+					__("Type", "event_espresso"),
49
+					false,
50
+					'event',
51
+					array(
52
+						'event'        => __("Event", "event_espresso"),//deprecated
53
+						'registration' => __("Registration", "event_espresso"),
54
+						'transaction'  => __("Transaction", "event_espresso"),
55
+						'payment'      => __("Payment", "event_espresso"),
56
+						'email'        => __("Email", "event_espresso"),
57
+						'message'      => __("Message", "event_espresso"),
58
+					)),
59
+				'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
+				'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
+				'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Registration' => new EE_Has_Many_Relation(),
66
+			'Transaction'  => new EE_Has_Many_Relation(),
67
+			'Payment'      => new EE_Has_Many_Relation(),
68
+		);
69
+		//this model is generally available for reading
70
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
 
72
-        parent::__construct($timezone);
73
-    }
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * This method provides the localized singular or plural string for a given status id
78
-     *
79
-     * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
-     *                           That way if there isn't a translation in the index we'll return the default code.
81
-     * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
-     *                           same as the singular (in English), however, this may NOT be the case with other
83
-     *                           languages
84
-     * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
-     *                           the status string returned ( UPPER, lower, Sentence)
86
-     * @throws EE_Error
87
-     * @return array             an array of translated strings for the incoming status id.
88
-     */
89
-    public function localized_status($statuses, $plural = false, $schema = 'upper')
90
-    {
91
-        //note these are all in lower case because ucwords() on upper case will NOT convert.
92
-        $translation_array = array(
93
-            EEM_Registration::status_id_pending_payment => array(
94
-                __('pending payment', 'event_espresso'), //singular
95
-                __('pending payments', 'event_espresso') //plural
96
-            ),
97
-            EEM_Registration::status_id_approved        => array(
98
-                __('approved', 'event_espresso'), //singular
99
-                __('approved', 'event_espresso') //plural
100
-            ),
101
-            EEM_Registration::status_id_not_approved    => array(
102
-                __('not approved', 'event_espresso'),
103
-                __('not approved', 'event_espresso'),
104
-            ),
105
-            EEM_Registration::status_id_cancelled       => array(
106
-                __('cancelled', 'event_espresso'),
107
-                __('cancelled', 'event_espresso'),
108
-            ),
109
-            EEM_Registration::status_id_incomplete      => array(
110
-                __('incomplete', 'event_espresso'),
111
-                __('incomplete', 'event_espresso'),
112
-            ),
113
-            EEM_Registration::status_id_declined        => array(
114
-                __('declined', 'event_espresso'),
115
-                __('declined', 'event_espresso'),
116
-            ),
117
-            EEM_Registration::status_id_wait_list       => array(
118
-                __('wait list', 'event_espresso'),
119
-                __('wait list', 'event_espresso'),
120
-            ),
121
-            EEM_Transaction::overpaid_status_code       => array(
122
-                __('overpaid', 'event_espresso'),
123
-                __('overpaid', 'event_espresso'),
124
-            ),
125
-            EEM_Transaction::complete_status_code       => array(
126
-                __('complete', 'event_espresso'),
127
-                __('complete', 'event_espresso'),
128
-            ),
129
-            EEM_Transaction::incomplete_status_code     => array(
130
-                __('incomplete', 'event_espresso'),
131
-                __('incomplete', 'event_espresso'),
132
-            ),
133
-            EEM_Transaction::failed_status_code         => array(
134
-                __('failed', 'event_espresso'),
135
-                __('failed', 'event_espresso'),
136
-            ),
137
-            EEM_Transaction::abandoned_status_code      => array(
138
-                __('abandoned', 'event_espresso'),
139
-                __('abandoned', 'event_espresso'),
140
-            ),
141
-            EEM_Payment::status_id_approved             => array(
142
-                __('accepted', 'event_espresso'),
143
-                __('accepted', 'event_espresso'),
144
-            ),
145
-            EEM_Payment::status_id_pending              => array(
146
-                __('pending', 'event_espresso'),
147
-                __('pending', 'event_espresso'),
148
-            ),
149
-            EEM_Payment::status_id_cancelled            => array(
150
-                __('cancelled', 'event_espresso'),
151
-                __('cancelled', 'event_espresso'),
152
-            ),
153
-            EEM_Payment::status_id_declined             => array(
154
-                __('declined', 'event_espresso'),
155
-                __('declined', 'event_espresso'),
156
-            ),
157
-            EEM_Payment::status_id_failed               => array(
158
-                __('failed', 'event_espresso'),
159
-                __('failed', 'event_espresso'),
160
-            ),
161
-            //following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
-            EEM_Event::sold_out                         => array(
163
-                __('sold out', 'event_espresso'),
164
-                __('sold out', 'event_espresso'),
165
-            ),
166
-            EEM_Event::postponed                        => array(
167
-                __('postponed', 'event_espresso'),
168
-                __('Postponed', 'event_espresso'),
169
-            ),
170
-            EEM_Event::cancelled                        => array(
171
-                __('cancelled', 'event_espresso'),
172
-                __('cancelled', 'event_espresso'),
173
-            ),
174
-            EE_Ticket::archived                         => array(
175
-                __('archived', 'event_espresso'),
176
-                __('archived', 'event_espresso'),
177
-            ),
178
-            EE_Ticket::expired                          => array(
179
-                __('expired', 'event_espresso'),
180
-                __('expired', 'event_espresso'),
181
-            ),
182
-            EE_Ticket::sold_out                         => array(
183
-                __('sold out', 'event_espresso'),
184
-                __('sold out', 'event_espresso'),
185
-            ),
186
-            EE_Ticket::pending                          => array(
187
-                __('upcoming', 'event_espresso'),
188
-                __('upcoming', 'event_espresso'),
189
-            ),
190
-            EE_Ticket::onsale                           => array(
191
-                __('on sale', 'event_espresso'),
192
-                __('on sale', 'event_espresso'),
193
-            ),
194
-            EE_Datetime::cancelled                      => array(
195
-                __('cancelled', 'event_espresso'),
196
-                __('cancelled', 'event_espresso'),
197
-            ),
198
-            EE_Datetime::sold_out                       => array(
199
-                __('sold out', 'event_espresso'),
200
-                __('sold out', 'event_espresso'),
201
-            ),
202
-            EE_Datetime::expired                        => array(
203
-                __('expired', 'event_espresso'),
204
-                __('expired', 'event_espresso'),
205
-            ),
206
-            EE_Datetime::inactive                       => array(
207
-                __('inactive', 'event_espresso'),
208
-                __('inactive', 'event_espresso'),
209
-            ),
210
-            EE_Datetime::upcoming                       => array(
211
-                __('upcoming', 'event_espresso'),
212
-                __('upcoming', 'event_espresso'),
213
-            ),
214
-            EE_Datetime::active                         => array(
215
-                __('active', 'event_espresso'),
216
-                __('active', 'event_espresso'),
217
-            ),
218
-            EE_Datetime::postponed                      => array(
219
-                __('postponed', 'event_espresso'),
220
-                __('postponed', 'event_espresso'),
221
-            ),
222
-            //messages related
223
-            EEM_Message::status_sent                    => array(
224
-                __('sent', 'event_espresso'),
225
-                __('sent', 'event_espresso'),
226
-            ),
227
-            EEM_Message::status_idle                    => array(
228
-                __('queued for sending', 'event_espresso'),
229
-                __('queued for sending', 'event_espresso'),
230
-            ),
231
-            EEM_Message::status_failed                  => array(
232
-                __('failed', 'event_espresso'),
233
-                __('failed', 'event_espresso'),
234
-            ),
235
-            EEM_Message::status_debug_only              => array(
236
-                __('debug only', 'event_espresso'),
237
-                __('debug only', 'event_espresso'),
238
-            ),
239
-            EEM_Message::status_messenger_executing     => array(
240
-                __('messenger is executing', 'event_espresso'),
241
-                __('messenger is executing', 'event_espresso'),
242
-            ),
243
-            EEM_Message::status_resend                  => array(
244
-                __('queued for resending', 'event_espresso'),
245
-                __('queued for resending', 'event_espresso'),
246
-            ),
247
-            EEM_Message::status_incomplete              => array(
248
-                __('queued for generating', 'event_espresso'),
249
-                __('queued for generating', 'event_espresso'),
250
-            ),
251
-            EEM_Message::status_retry                   => array(
252
-                __('failed sending, can be retried', 'event_espresso'),
253
-                __('failed sending, can be retried', 'event_espresso'),
254
-            ),
255
-            EEM_CPT_Base::post_status_publish           => array(
256
-                __('published', 'event_espresso'),
257
-                __('published', 'event_espresso'),
258
-            ),
259
-            EEM_CPT_Base::post_status_future            => array(
260
-                __('scheduled', 'event_espresso'),
261
-                __('scheduled', 'event_espresso'),
262
-            ),
263
-            EEM_CPT_Base::post_status_draft             => array(
264
-                __('draft', 'event_espresso'),
265
-                __('draft', 'event_espresso'),
266
-            ),
267
-            EEM_CPT_Base::post_status_pending           => array(
268
-                __('pending', 'event_espresso'),
269
-                __('pending', 'event_espresso'),
270
-            ),
271
-            EEM_CPT_Base::post_status_private           => array(
272
-                __('private', 'event_espresso'),
273
-                __('private', 'event_espresso'),
274
-            ),
275
-            EEM_CPT_Base::post_status_trashed           => array(
276
-                __('trashed', 'event_espresso'),
277
-                __('trashed', 'event_espresso'),
278
-            ),
279
-        );
76
+	/**
77
+	 * This method provides the localized singular or plural string for a given status id
78
+	 *
79
+	 * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
+	 *                           That way if there isn't a translation in the index we'll return the default code.
81
+	 * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
+	 *                           same as the singular (in English), however, this may NOT be the case with other
83
+	 *                           languages
84
+	 * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
+	 *                           the status string returned ( UPPER, lower, Sentence)
86
+	 * @throws EE_Error
87
+	 * @return array             an array of translated strings for the incoming status id.
88
+	 */
89
+	public function localized_status($statuses, $plural = false, $schema = 'upper')
90
+	{
91
+		//note these are all in lower case because ucwords() on upper case will NOT convert.
92
+		$translation_array = array(
93
+			EEM_Registration::status_id_pending_payment => array(
94
+				__('pending payment', 'event_espresso'), //singular
95
+				__('pending payments', 'event_espresso') //plural
96
+			),
97
+			EEM_Registration::status_id_approved        => array(
98
+				__('approved', 'event_espresso'), //singular
99
+				__('approved', 'event_espresso') //plural
100
+			),
101
+			EEM_Registration::status_id_not_approved    => array(
102
+				__('not approved', 'event_espresso'),
103
+				__('not approved', 'event_espresso'),
104
+			),
105
+			EEM_Registration::status_id_cancelled       => array(
106
+				__('cancelled', 'event_espresso'),
107
+				__('cancelled', 'event_espresso'),
108
+			),
109
+			EEM_Registration::status_id_incomplete      => array(
110
+				__('incomplete', 'event_espresso'),
111
+				__('incomplete', 'event_espresso'),
112
+			),
113
+			EEM_Registration::status_id_declined        => array(
114
+				__('declined', 'event_espresso'),
115
+				__('declined', 'event_espresso'),
116
+			),
117
+			EEM_Registration::status_id_wait_list       => array(
118
+				__('wait list', 'event_espresso'),
119
+				__('wait list', 'event_espresso'),
120
+			),
121
+			EEM_Transaction::overpaid_status_code       => array(
122
+				__('overpaid', 'event_espresso'),
123
+				__('overpaid', 'event_espresso'),
124
+			),
125
+			EEM_Transaction::complete_status_code       => array(
126
+				__('complete', 'event_espresso'),
127
+				__('complete', 'event_espresso'),
128
+			),
129
+			EEM_Transaction::incomplete_status_code     => array(
130
+				__('incomplete', 'event_espresso'),
131
+				__('incomplete', 'event_espresso'),
132
+			),
133
+			EEM_Transaction::failed_status_code         => array(
134
+				__('failed', 'event_espresso'),
135
+				__('failed', 'event_espresso'),
136
+			),
137
+			EEM_Transaction::abandoned_status_code      => array(
138
+				__('abandoned', 'event_espresso'),
139
+				__('abandoned', 'event_espresso'),
140
+			),
141
+			EEM_Payment::status_id_approved             => array(
142
+				__('accepted', 'event_espresso'),
143
+				__('accepted', 'event_espresso'),
144
+			),
145
+			EEM_Payment::status_id_pending              => array(
146
+				__('pending', 'event_espresso'),
147
+				__('pending', 'event_espresso'),
148
+			),
149
+			EEM_Payment::status_id_cancelled            => array(
150
+				__('cancelled', 'event_espresso'),
151
+				__('cancelled', 'event_espresso'),
152
+			),
153
+			EEM_Payment::status_id_declined             => array(
154
+				__('declined', 'event_espresso'),
155
+				__('declined', 'event_espresso'),
156
+			),
157
+			EEM_Payment::status_id_failed               => array(
158
+				__('failed', 'event_espresso'),
159
+				__('failed', 'event_espresso'),
160
+			),
161
+			//following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
+			EEM_Event::sold_out                         => array(
163
+				__('sold out', 'event_espresso'),
164
+				__('sold out', 'event_espresso'),
165
+			),
166
+			EEM_Event::postponed                        => array(
167
+				__('postponed', 'event_espresso'),
168
+				__('Postponed', 'event_espresso'),
169
+			),
170
+			EEM_Event::cancelled                        => array(
171
+				__('cancelled', 'event_espresso'),
172
+				__('cancelled', 'event_espresso'),
173
+			),
174
+			EE_Ticket::archived                         => array(
175
+				__('archived', 'event_espresso'),
176
+				__('archived', 'event_espresso'),
177
+			),
178
+			EE_Ticket::expired                          => array(
179
+				__('expired', 'event_espresso'),
180
+				__('expired', 'event_espresso'),
181
+			),
182
+			EE_Ticket::sold_out                         => array(
183
+				__('sold out', 'event_espresso'),
184
+				__('sold out', 'event_espresso'),
185
+			),
186
+			EE_Ticket::pending                          => array(
187
+				__('upcoming', 'event_espresso'),
188
+				__('upcoming', 'event_espresso'),
189
+			),
190
+			EE_Ticket::onsale                           => array(
191
+				__('on sale', 'event_espresso'),
192
+				__('on sale', 'event_espresso'),
193
+			),
194
+			EE_Datetime::cancelled                      => array(
195
+				__('cancelled', 'event_espresso'),
196
+				__('cancelled', 'event_espresso'),
197
+			),
198
+			EE_Datetime::sold_out                       => array(
199
+				__('sold out', 'event_espresso'),
200
+				__('sold out', 'event_espresso'),
201
+			),
202
+			EE_Datetime::expired                        => array(
203
+				__('expired', 'event_espresso'),
204
+				__('expired', 'event_espresso'),
205
+			),
206
+			EE_Datetime::inactive                       => array(
207
+				__('inactive', 'event_espresso'),
208
+				__('inactive', 'event_espresso'),
209
+			),
210
+			EE_Datetime::upcoming                       => array(
211
+				__('upcoming', 'event_espresso'),
212
+				__('upcoming', 'event_espresso'),
213
+			),
214
+			EE_Datetime::active                         => array(
215
+				__('active', 'event_espresso'),
216
+				__('active', 'event_espresso'),
217
+			),
218
+			EE_Datetime::postponed                      => array(
219
+				__('postponed', 'event_espresso'),
220
+				__('postponed', 'event_espresso'),
221
+			),
222
+			//messages related
223
+			EEM_Message::status_sent                    => array(
224
+				__('sent', 'event_espresso'),
225
+				__('sent', 'event_espresso'),
226
+			),
227
+			EEM_Message::status_idle                    => array(
228
+				__('queued for sending', 'event_espresso'),
229
+				__('queued for sending', 'event_espresso'),
230
+			),
231
+			EEM_Message::status_failed                  => array(
232
+				__('failed', 'event_espresso'),
233
+				__('failed', 'event_espresso'),
234
+			),
235
+			EEM_Message::status_debug_only              => array(
236
+				__('debug only', 'event_espresso'),
237
+				__('debug only', 'event_espresso'),
238
+			),
239
+			EEM_Message::status_messenger_executing     => array(
240
+				__('messenger is executing', 'event_espresso'),
241
+				__('messenger is executing', 'event_espresso'),
242
+			),
243
+			EEM_Message::status_resend                  => array(
244
+				__('queued for resending', 'event_espresso'),
245
+				__('queued for resending', 'event_espresso'),
246
+			),
247
+			EEM_Message::status_incomplete              => array(
248
+				__('queued for generating', 'event_espresso'),
249
+				__('queued for generating', 'event_espresso'),
250
+			),
251
+			EEM_Message::status_retry                   => array(
252
+				__('failed sending, can be retried', 'event_espresso'),
253
+				__('failed sending, can be retried', 'event_espresso'),
254
+			),
255
+			EEM_CPT_Base::post_status_publish           => array(
256
+				__('published', 'event_espresso'),
257
+				__('published', 'event_espresso'),
258
+			),
259
+			EEM_CPT_Base::post_status_future            => array(
260
+				__('scheduled', 'event_espresso'),
261
+				__('scheduled', 'event_espresso'),
262
+			),
263
+			EEM_CPT_Base::post_status_draft             => array(
264
+				__('draft', 'event_espresso'),
265
+				__('draft', 'event_espresso'),
266
+			),
267
+			EEM_CPT_Base::post_status_pending           => array(
268
+				__('pending', 'event_espresso'),
269
+				__('pending', 'event_espresso'),
270
+			),
271
+			EEM_CPT_Base::post_status_private           => array(
272
+				__('private', 'event_espresso'),
273
+				__('private', 'event_espresso'),
274
+			),
275
+			EEM_CPT_Base::post_status_trashed           => array(
276
+				__('trashed', 'event_espresso'),
277
+				__('trashed', 'event_espresso'),
278
+			),
279
+		);
280 280
 
281
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
281
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
282 282
 
283
-        if ( ! is_array($statuses)) {
284
-            throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
-                'event_espresso'));
286
-        }
283
+		if ( ! is_array($statuses)) {
284
+			throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
+				'event_espresso'));
286
+		}
287 287
 
288
-        $translation = array();
288
+		$translation = array();
289 289
 
290
-        foreach ($statuses as $id => $code) {
291
-            if (isset($translation_array[$id])) {
292
-                $translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
-            } else {
294
-                $translation[$id] = $code;
295
-            }
290
+		foreach ($statuses as $id => $code) {
291
+			if (isset($translation_array[$id])) {
292
+				$translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
+			} else {
294
+				$translation[$id] = $code;
295
+			}
296 296
 
297
-            //schema
298
-            switch ($schema) {
299
-                case 'lower' :
300
-                    $translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
-                    break;
302
-                case 'sentence' :
303
-                    $translation[$id] = ucwords($translation[$id]);
304
-                    break;
305
-                case 'upper' :
306
-                    $translation[$id] = strtoupper($translation[$id]);
307
-                    break;
308
-            }
309
-        }
297
+			//schema
298
+			switch ($schema) {
299
+				case 'lower' :
300
+					$translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
+					break;
302
+				case 'sentence' :
303
+					$translation[$id] = ucwords($translation[$id]);
304
+					break;
305
+				case 'upper' :
306
+					$translation[$id] = strtoupper($translation[$id]);
307
+					break;
308
+			}
309
+		}
310 310
 
311
-        return $translation;
312
-    }
311
+		return $translation;
312
+	}
313 313
 
314 314
 
315 315
 }
Please login to merge, or discard this patch.
admin_pages/messages/EE_Message_List_Table.class.php 2 patches
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -15,430 +15,430 @@  discard block
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * @return Messages_Admin_Page
20
-     */
21
-    public function get_admin_page()
22
-    {
23
-        return $this->_admin_page;
24
-    }
25
-
26
-
27
-    protected function _setup_data()
28
-    {
29
-        $this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
-        $this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
-    }
32
-
33
-
34
-    protected function _set_properties()
35
-    {
36
-        $this->_wp_list_args = array(
37
-            'singular' => __('Message', 'event_espresso'),
38
-            'plural'   => __('Messages', 'event_espresso'),
39
-            'ajax'     => true,
40
-            'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
-        );
42
-
43
-        $this->_columns = array(
44
-            'cb'           => '<input type="checkbox" />',
45
-            'to'           => __('To', 'event_espresso'),
46
-            'from'         => __('From', 'event_espresso'),
47
-            'messenger'    => __('Messenger', 'event_espresso'),
48
-            'message_type' => __('Message Type', 'event_espresso'),
49
-            'context'      => __('Context', 'event_espresso'),
50
-            'modified'     => __('Modified', 'event_espresso'),
51
-            'action'       => __('Actions', 'event_espresso'),
52
-            'msg_id'       => __('ID', 'event_espresso'),
53
-        );
54
-
55
-        $this->_sortable_columns = array(
56
-            'modified'     => array('MSG_modified' => true),
57
-            'message_type' => array('MSG_message_type' => false),
58
-            'messenger'    => array('MSG_messenger' => false),
59
-            'to'           => array('MSG_to' => false),
60
-            'from'         => array('MSG_from' => false),
61
-            'context'      => array('MSG_context' => false),
62
-            'msg_id'       => array('MSG_ID', false),
63
-        );
64
-
65
-        $this->_primary_column = 'to';
66
-
67
-        $this->_hidden_columns = array(
68
-            'msg_id',
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     * This simply sets up the row class for the table rows.
75
-     * Allows for easier overriding of child methods for setting up sorting.
76
-     *
77
-     * @param  object $item the current item
78
-     * @return string
79
-     */
80
-    protected function _get_row_class($item)
81
-    {
82
-        $class = parent::_get_row_class($item);
83
-        //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
-        if ($this->_has_checkbox_column) {
86
-            $class .= ' has-checkbox-column';
87
-        }
88
-        return $class;
89
-    }
90
-
91
-
92
-    /**
93
-     * _get_table_filters
94
-     * We use this to assemble and return any filters that are associated with this table that help further refine what
95
-     * get's shown in the table.
96
-     *
97
-     * @abstract
98
-     * @access protected
99
-     * @return string
100
-     * @throws \EE_Error
101
-     */
102
-    protected function _get_table_filters()
103
-    {
104
-        $filters = array();
105
-
106
-        //get select_inputs
107
-        $select_inputs = array(
108
-            $this->_get_messengers_dropdown_filter(),
109
-            $this->_get_message_types_dropdown_filter(),
110
-            $this->_get_contexts_for_message_types_dropdown_filter(),
111
-        );
112
-
113
-        //set filters to select inputs if they aren't empty
114
-        foreach ($select_inputs as $select_input) {
115
-            if ($select_input) {
116
-                $filters[] = $select_input;
117
-            }
118
-        }
119
-        return $filters;
120
-    }
121
-
122
-
123
-    protected function _add_view_counts()
124
-    {
125
-        foreach ($this->_views as $view => $args) {
126
-            $this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
-        }
128
-    }
129
-
130
-
131
-    /**
132
-     * @param EE_Message $message
133
-     * @return string   checkbox
134
-     * @throws \EE_Error
135
-     */
136
-    public function column_cb($message)
137
-    {
138
-        return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
-    }
140
-
141
-
142
-    /**
143
-     * @param EE_Message $message
144
-     * @return string
145
-     * @throws \EE_Error
146
-     */
147
-    public function column_msg_id(EE_Message $message)
148
-    {
149
-        return $message->ID();
150
-    }
151
-
152
-
153
-    /**
154
-     * @param EE_Message $message
155
-     * @return string    The recipient of the message
156
-     * @throws \EE_Error
157
-     */
158
-    public function column_to(EE_Message $message)
159
-    {
160
-        EE_Registry::instance()->load_helper('URL');
161
-        $actions           = array();
162
-        $actions['delete'] = '<a href="'
163
-                             . EEH_URL::add_query_args_and_nonce(
164
-                array(
165
-                    'page'   => 'espresso_messages',
166
-                    'action' => 'delete_ee_message',
167
-                    'MSG_ID' => $message->ID(),
168
-                ),
169
-                admin_url('admin.php')
170
-            )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
173
-    }
174
-
175
-
176
-    /**
177
-     * @param EE_Message $message
178
-     * @return string   The sender of the message
179
-     */
180
-    public function column_from(EE_Message $message)
181
-    {
182
-        return esc_html($message->from());
183
-    }
184
-
185
-
186
-    /**
187
-     * @param EE_Message $message
188
-     * @return string  The messenger used to send the message.
189
-     */
190
-    public function column_messenger(EE_Message $message)
191
-    {
192
-        return ucwords($message->messenger_label());
193
-    }
194
-
195
-
196
-    /**
197
-     * @param EE_Message $message
198
-     * @return string  The message type used to generate the message.
199
-     */
200
-    public function column_message_type(EE_Message $message)
201
-    {
202
-        return ucwords($message->message_type_label());
203
-    }
204
-
205
-
206
-    /**
207
-     * @param EE_Message $message
208
-     * @return string  The context the message was generated for.
209
-     */
210
-    public function column_context(EE_Message $message)
211
-    {
212
-        return $message->context_label();
213
-    }
214
-
215
-
216
-    /**
217
-     * @param EE_Message $message
218
-     * @return string    The timestamp when this message was last modified.
219
-     */
220
-    public function column_modified(EE_Message $message)
221
-    {
222
-        return $message->modified();
223
-    }
224
-
225
-
226
-    /**
227
-     * @param EE_Message $message
228
-     * @return string   Actions that can be done on the current message.
229
-     */
230
-    public function column_action(EE_Message $message)
231
-    {
232
-        EE_Registry::instance()->load_helper('MSG_Template');
233
-        $action_links = array(
234
-            'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
-            'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
-            'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
-            'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
-            'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
-            'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
-        );
241
-        $content      = '';
242
-        switch ($message->STS_ID()) {
243
-            case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
-                break;
246
-            case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
-                break;
249
-            case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
-                break;
252
-            case EEM_Message::status_failed :
253
-            case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
255
-                break;
256
-            case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
-                break;
259
-            case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
261
-                break;
262
-        }
263
-        return $content;
264
-    }
265
-
266
-
267
-    /**
268
-     * Retrieve the EE_Message objects for the list table.
269
-     *
270
-     * @param int    $perpage The number of items per page
271
-     * @param string $view    The view items are being retrieved for
272
-     * @param bool   $count   Whether to just return a count or not.
273
-     * @param bool   $all     Disregard any paging info (no limit on data returned).
274
-     * @return int|EE_Message[]
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
-    {
279
-
280
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
-            ? $this->_req_data['paged']
282
-            : 1;
283
-
284
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
-            ? $this->_req_data['perpage']
286
-            : $perpage;
287
-
288
-        $offset       = ($current_page - 1) * $per_page;
289
-        $limit        = $all || $count ? null : array($offset, $per_page);
290
-        $query_params = array(
291
-            'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
-            'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
-            'limit'    => $limit,
294
-        );
295
-
296
-        /**
297
-         * Any filters coming in from other routes?
298
-         */
299
-        if (isset($this->_req_data['filterby'])) {
300
-            $query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
-            if ( ! $count) {
302
-                $query_params['group_by'] = 'MSG_ID';
303
-            }
304
-        }
305
-
306
-        //view conditionals
307
-        if ($view !== 'all' && $count && $all) {
308
-            $query_params[0]['AND*view_conditional'] = array(
309
-                'STS_ID' => strtoupper($view),
310
-            );
311
-        }
312
-
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
-            $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
-                ? array(
316
-                    'STS_ID' => array(
317
-                        'IN',
318
-                        array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
-                    )
320
-                )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
-        }
323
-
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
326
-            $query_params[0]['OR'] = array(
327
-                'MSG_to'      => array('LIKE', $search_string),
328
-                'MSG_from'    => array('LIKE', $search_string),
329
-                'MSG_subject' => array('LIKE', $search_string),
330
-                'MSG_content' => array('LIKE', $search_string),
331
-            );
332
-        }
333
-
334
-        //account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
-        //the messages system is in debug mode.
336
-        //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
-        //messages in the database.
338
-        if (! EEM_Message::debug()) {
339
-            $query_params[0]['AND*debug_only_conditional'] = array(
340
-                'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
-            );
342
-        }
343
-
344
-        //account for filters
345
-        if (! $all
346
-            && isset($this->_req_data['ee_messenger_filter_by'])
347
-            && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
-        ) {
349
-            $query_params[0]['AND*messenger_filter'] = array(
350
-                'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
-            );
352
-        }
353
-        if (! $all
354
-            && ! empty($this->_req_data['ee_message_type_filter_by'])
355
-            && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
-        ) {
357
-            $query_params[0]['AND*message_type_filter'] = array(
358
-                'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
-            );
360
-        }
361
-
362
-        if (! $all
363
-            && ! empty($this->_req_data['ee_context_filter_by'])
364
-            && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
-        ) {
366
-            $query_params[0]['AND*context_filter'] = array(
367
-                'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
-            );
369
-        }
370
-
371
-        return $count
372
-            /** @type int */
373
-            ? EEM_Message::instance()->count($query_params, null, true)
374
-            /** @type EE_Message[] */
375
-            : EEM_Message::instance()->get_all($query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Generate dropdown filter select input for messengers.
381
-     *
382
-     * @return string
383
-     */
384
-    protected function _get_messengers_dropdown_filter()
385
-    {
386
-        $messenger_options                    = array();
387
-        $active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
-
389
-        //setup array of messenger options
390
-        foreach ($active_messages_grouped_by_messenger as $active_message) {
391
-            if ($active_message instanceof EE_Message) {
392
-                $messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
-            }
394
-        }
395
-        return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
-    }
397
-
398
-
399
-    /**
400
-     * Generate dropdown filter select input for message types
401
-     *
402
-     * @return string
403
-     */
404
-    protected function _get_message_types_dropdown_filter()
405
-    {
406
-        $message_type_options                    = array();
407
-        $active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
-
409
-        //setup array of message type options
410
-        foreach ($active_messages_grouped_by_message_type as $active_message) {
411
-            if ($active_message instanceof EE_Message) {
412
-                $message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
-            }
414
-        }
415
-        return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
-    }
417
-
418
-
419
-    /**
420
-     * Generate dropdown filter select input for message type contexts
421
-     *
422
-     * @return string
423
-     */
424
-    protected function _get_contexts_for_message_types_dropdown_filter()
425
-    {
426
-        $context_options                    = array();
427
-        $active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
-
429
-        //setup array of context options
430
-        foreach ($active_messages_grouped_by_context as $active_message) {
431
-            if ($active_message instanceof EE_Message) {
432
-                $message_type = $active_message->message_type_object();
433
-                if ($message_type instanceof EE_message_type) {
434
-                    foreach ($message_type->get_contexts() as $context => $context_details) {
435
-                        if (isset($context_details['label'])) {
436
-                            $context_options[$context] = $context_details['label'];
437
-                        }
438
-                    }
439
-                }
440
-            }
441
-        }
442
-        return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
-    }
18
+	/**
19
+	 * @return Messages_Admin_Page
20
+	 */
21
+	public function get_admin_page()
22
+	{
23
+		return $this->_admin_page;
24
+	}
25
+
26
+
27
+	protected function _setup_data()
28
+	{
29
+		$this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
+		$this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
+	}
32
+
33
+
34
+	protected function _set_properties()
35
+	{
36
+		$this->_wp_list_args = array(
37
+			'singular' => __('Message', 'event_espresso'),
38
+			'plural'   => __('Messages', 'event_espresso'),
39
+			'ajax'     => true,
40
+			'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
+		);
42
+
43
+		$this->_columns = array(
44
+			'cb'           => '<input type="checkbox" />',
45
+			'to'           => __('To', 'event_espresso'),
46
+			'from'         => __('From', 'event_espresso'),
47
+			'messenger'    => __('Messenger', 'event_espresso'),
48
+			'message_type' => __('Message Type', 'event_espresso'),
49
+			'context'      => __('Context', 'event_espresso'),
50
+			'modified'     => __('Modified', 'event_espresso'),
51
+			'action'       => __('Actions', 'event_espresso'),
52
+			'msg_id'       => __('ID', 'event_espresso'),
53
+		);
54
+
55
+		$this->_sortable_columns = array(
56
+			'modified'     => array('MSG_modified' => true),
57
+			'message_type' => array('MSG_message_type' => false),
58
+			'messenger'    => array('MSG_messenger' => false),
59
+			'to'           => array('MSG_to' => false),
60
+			'from'         => array('MSG_from' => false),
61
+			'context'      => array('MSG_context' => false),
62
+			'msg_id'       => array('MSG_ID', false),
63
+		);
64
+
65
+		$this->_primary_column = 'to';
66
+
67
+		$this->_hidden_columns = array(
68
+			'msg_id',
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 * This simply sets up the row class for the table rows.
75
+	 * Allows for easier overriding of child methods for setting up sorting.
76
+	 *
77
+	 * @param  object $item the current item
78
+	 * @return string
79
+	 */
80
+	protected function _get_row_class($item)
81
+	{
82
+		$class = parent::_get_row_class($item);
83
+		//add status class
84
+		$class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
+		if ($this->_has_checkbox_column) {
86
+			$class .= ' has-checkbox-column';
87
+		}
88
+		return $class;
89
+	}
90
+
91
+
92
+	/**
93
+	 * _get_table_filters
94
+	 * We use this to assemble and return any filters that are associated with this table that help further refine what
95
+	 * get's shown in the table.
96
+	 *
97
+	 * @abstract
98
+	 * @access protected
99
+	 * @return string
100
+	 * @throws \EE_Error
101
+	 */
102
+	protected function _get_table_filters()
103
+	{
104
+		$filters = array();
105
+
106
+		//get select_inputs
107
+		$select_inputs = array(
108
+			$this->_get_messengers_dropdown_filter(),
109
+			$this->_get_message_types_dropdown_filter(),
110
+			$this->_get_contexts_for_message_types_dropdown_filter(),
111
+		);
112
+
113
+		//set filters to select inputs if they aren't empty
114
+		foreach ($select_inputs as $select_input) {
115
+			if ($select_input) {
116
+				$filters[] = $select_input;
117
+			}
118
+		}
119
+		return $filters;
120
+	}
121
+
122
+
123
+	protected function _add_view_counts()
124
+	{
125
+		foreach ($this->_views as $view => $args) {
126
+			$this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
+		}
128
+	}
129
+
130
+
131
+	/**
132
+	 * @param EE_Message $message
133
+	 * @return string   checkbox
134
+	 * @throws \EE_Error
135
+	 */
136
+	public function column_cb($message)
137
+	{
138
+		return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param EE_Message $message
144
+	 * @return string
145
+	 * @throws \EE_Error
146
+	 */
147
+	public function column_msg_id(EE_Message $message)
148
+	{
149
+		return $message->ID();
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param EE_Message $message
155
+	 * @return string    The recipient of the message
156
+	 * @throws \EE_Error
157
+	 */
158
+	public function column_to(EE_Message $message)
159
+	{
160
+		EE_Registry::instance()->load_helper('URL');
161
+		$actions           = array();
162
+		$actions['delete'] = '<a href="'
163
+							 . EEH_URL::add_query_args_and_nonce(
164
+				array(
165
+					'page'   => 'espresso_messages',
166
+					'action' => 'delete_ee_message',
167
+					'MSG_ID' => $message->ID(),
168
+				),
169
+				admin_url('admin.php')
170
+			)
171
+							 . '">' . __('Delete', 'event_espresso') . '</a>';
172
+		return esc_html($message->to()) . $this->row_actions($actions);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param EE_Message $message
178
+	 * @return string   The sender of the message
179
+	 */
180
+	public function column_from(EE_Message $message)
181
+	{
182
+		return esc_html($message->from());
183
+	}
184
+
185
+
186
+	/**
187
+	 * @param EE_Message $message
188
+	 * @return string  The messenger used to send the message.
189
+	 */
190
+	public function column_messenger(EE_Message $message)
191
+	{
192
+		return ucwords($message->messenger_label());
193
+	}
194
+
195
+
196
+	/**
197
+	 * @param EE_Message $message
198
+	 * @return string  The message type used to generate the message.
199
+	 */
200
+	public function column_message_type(EE_Message $message)
201
+	{
202
+		return ucwords($message->message_type_label());
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param EE_Message $message
208
+	 * @return string  The context the message was generated for.
209
+	 */
210
+	public function column_context(EE_Message $message)
211
+	{
212
+		return $message->context_label();
213
+	}
214
+
215
+
216
+	/**
217
+	 * @param EE_Message $message
218
+	 * @return string    The timestamp when this message was last modified.
219
+	 */
220
+	public function column_modified(EE_Message $message)
221
+	{
222
+		return $message->modified();
223
+	}
224
+
225
+
226
+	/**
227
+	 * @param EE_Message $message
228
+	 * @return string   Actions that can be done on the current message.
229
+	 */
230
+	public function column_action(EE_Message $message)
231
+	{
232
+		EE_Registry::instance()->load_helper('MSG_Template');
233
+		$action_links = array(
234
+			'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
+			'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
+			'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
+			'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
+			'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
+			'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
+		);
241
+		$content      = '';
242
+		switch ($message->STS_ID()) {
243
+			case EEM_Message::status_sent :
244
+				$content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
+				break;
246
+			case EEM_Message::status_resend :
247
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
+				break;
249
+			case EEM_Message::status_retry :
250
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
+				break;
252
+			case EEM_Message::status_failed :
253
+			case EEM_Message::status_debug_only :
254
+				$content = $action_links['error'] . $action_links['view_transaction'];
255
+				break;
256
+			case EEM_Message::status_idle :
257
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
+				break;
259
+			case EEM_Message::status_incomplete;
260
+				$content = $action_links['generate_now'] . $action_links['view_transaction'];
261
+				break;
262
+		}
263
+		return $content;
264
+	}
265
+
266
+
267
+	/**
268
+	 * Retrieve the EE_Message objects for the list table.
269
+	 *
270
+	 * @param int    $perpage The number of items per page
271
+	 * @param string $view    The view items are being retrieved for
272
+	 * @param bool   $count   Whether to just return a count or not.
273
+	 * @param bool   $all     Disregard any paging info (no limit on data returned).
274
+	 * @return int|EE_Message[]
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
+	{
279
+
280
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
+			? $this->_req_data['paged']
282
+			: 1;
283
+
284
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
+			? $this->_req_data['perpage']
286
+			: $perpage;
287
+
288
+		$offset       = ($current_page - 1) * $per_page;
289
+		$limit        = $all || $count ? null : array($offset, $per_page);
290
+		$query_params = array(
291
+			'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
+			'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
+			'limit'    => $limit,
294
+		);
295
+
296
+		/**
297
+		 * Any filters coming in from other routes?
298
+		 */
299
+		if (isset($this->_req_data['filterby'])) {
300
+			$query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
+			if ( ! $count) {
302
+				$query_params['group_by'] = 'MSG_ID';
303
+			}
304
+		}
305
+
306
+		//view conditionals
307
+		if ($view !== 'all' && $count && $all) {
308
+			$query_params[0]['AND*view_conditional'] = array(
309
+				'STS_ID' => strtoupper($view),
310
+			);
311
+		}
312
+
313
+		if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
+			$query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
+				? array(
316
+					'STS_ID' => array(
317
+						'IN',
318
+						array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
+					)
320
+				)
321
+				: array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
+		}
323
+
324
+		if (! $all && ! empty($this->_req_data['s'])) {
325
+			$search_string         = '%' . $this->_req_data['s'] . '%';
326
+			$query_params[0]['OR'] = array(
327
+				'MSG_to'      => array('LIKE', $search_string),
328
+				'MSG_from'    => array('LIKE', $search_string),
329
+				'MSG_subject' => array('LIKE', $search_string),
330
+				'MSG_content' => array('LIKE', $search_string),
331
+			);
332
+		}
333
+
334
+		//account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
+		//the messages system is in debug mode.
336
+		//Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
+		//messages in the database.
338
+		if (! EEM_Message::debug()) {
339
+			$query_params[0]['AND*debug_only_conditional'] = array(
340
+				'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
+			);
342
+		}
343
+
344
+		//account for filters
345
+		if (! $all
346
+			&& isset($this->_req_data['ee_messenger_filter_by'])
347
+			&& $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
+		) {
349
+			$query_params[0]['AND*messenger_filter'] = array(
350
+				'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
+			);
352
+		}
353
+		if (! $all
354
+			&& ! empty($this->_req_data['ee_message_type_filter_by'])
355
+			&& $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
+		) {
357
+			$query_params[0]['AND*message_type_filter'] = array(
358
+				'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
+			);
360
+		}
361
+
362
+		if (! $all
363
+			&& ! empty($this->_req_data['ee_context_filter_by'])
364
+			&& $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
+		) {
366
+			$query_params[0]['AND*context_filter'] = array(
367
+				'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
+			);
369
+		}
370
+
371
+		return $count
372
+			/** @type int */
373
+			? EEM_Message::instance()->count($query_params, null, true)
374
+			/** @type EE_Message[] */
375
+			: EEM_Message::instance()->get_all($query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Generate dropdown filter select input for messengers.
381
+	 *
382
+	 * @return string
383
+	 */
384
+	protected function _get_messengers_dropdown_filter()
385
+	{
386
+		$messenger_options                    = array();
387
+		$active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
+
389
+		//setup array of messenger options
390
+		foreach ($active_messages_grouped_by_messenger as $active_message) {
391
+			if ($active_message instanceof EE_Message) {
392
+				$messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
+			}
394
+		}
395
+		return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Generate dropdown filter select input for message types
401
+	 *
402
+	 * @return string
403
+	 */
404
+	protected function _get_message_types_dropdown_filter()
405
+	{
406
+		$message_type_options                    = array();
407
+		$active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
+
409
+		//setup array of message type options
410
+		foreach ($active_messages_grouped_by_message_type as $active_message) {
411
+			if ($active_message instanceof EE_Message) {
412
+				$message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
+			}
414
+		}
415
+		return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
+	}
417
+
418
+
419
+	/**
420
+	 * Generate dropdown filter select input for message type contexts
421
+	 *
422
+	 * @return string
423
+	 */
424
+	protected function _get_contexts_for_message_types_dropdown_filter()
425
+	{
426
+		$context_options                    = array();
427
+		$active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
+
429
+		//setup array of context options
430
+		foreach ($active_messages_grouped_by_context as $active_message) {
431
+			if ($active_message instanceof EE_Message) {
432
+				$message_type = $active_message->message_type_object();
433
+				if ($message_type instanceof EE_message_type) {
434
+					foreach ($message_type->get_contexts() as $context => $context_details) {
435
+						if (isset($context_details['label'])) {
436
+							$context_options[$context] = $context_details['label'];
437
+						}
438
+					}
439
+				}
440
+			}
441
+		}
442
+		return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
+	}
444 444
 } //end EE_Message_List_Table class
445 445
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     {
82 82
         $class = parent::_get_row_class($item);
83 83
         //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
84
+        $class .= ' ee-status-strip msg-status-'.$item->STS_ID();
85 85
         if ($this->_has_checkbox_column) {
86 86
             $class .= ' has-checkbox-column';
87 87
         }
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
                 ),
169 169
                 admin_url('admin.php')
170 170
             )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
171
+                             . '">'.__('Delete', 'event_espresso').'</a>';
172
+        return esc_html($message->to()).$this->row_actions($actions);
173 173
     }
174 174
 
175 175
 
@@ -238,26 +238,26 @@  discard block
 block discarded – undo
238 238
             'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239 239
             'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240 240
         );
241
-        $content      = '';
241
+        $content = '';
242 242
         switch ($message->STS_ID()) {
243 243
             case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
244
+                $content = $action_links['view'].$action_links['queue_for_resending'].$action_links['view_transaction'];
245 245
                 break;
246 246
             case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
247
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
248 248
                 break;
249 249
             case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
250
+                $content = $action_links['view'].$action_links['send_now'].$action_links['error'].$action_links['view_transaction'];
251 251
                 break;
252 252
             case EEM_Message::status_failed :
253 253
             case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
254
+                $content = $action_links['error'].$action_links['view_transaction'];
255 255
                 break;
256 256
             case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
257
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
258 258
                 break;
259 259
             case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
260
+                $content = $action_links['generate_now'].$action_links['view_transaction'];
261 261
                 break;
262 262
         }
263 263
         return $content;
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
             );
311 311
         }
312 312
 
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
313
+        if ( ! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314 314
             $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315 315
                 ? array(
316 316
                     'STS_ID' => array(
@@ -318,11 +318,11 @@  discard block
 block discarded – undo
318 318
                         array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319 319
                     )
320 320
                 )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
321
+                : array('STS_ID' => strtoupper($this->_req_data['status']));
322 322
         }
323 323
 
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
324
+        if ( ! $all && ! empty($this->_req_data['s'])) {
325
+            $search_string         = '%'.$this->_req_data['s'].'%';
326 326
             $query_params[0]['OR'] = array(
327 327
                 'MSG_to'      => array('LIKE', $search_string),
328 328
                 'MSG_from'    => array('LIKE', $search_string),
@@ -335,14 +335,14 @@  discard block
 block discarded – undo
335 335
         //the messages system is in debug mode.
336 336
         //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337 337
         //messages in the database.
338
-        if (! EEM_Message::debug()) {
338
+        if ( ! EEM_Message::debug()) {
339 339
             $query_params[0]['AND*debug_only_conditional'] = array(
340 340
                 'STS_ID' => array('!=', EEM_Message::status_debug_only),
341 341
             );
342 342
         }
343 343
 
344 344
         //account for filters
345
-        if (! $all
345
+        if ( ! $all
346 346
             && isset($this->_req_data['ee_messenger_filter_by'])
347 347
             && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348 348
         ) {
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351 351
             );
352 352
         }
353
-        if (! $all
353
+        if ( ! $all
354 354
             && ! empty($this->_req_data['ee_message_type_filter_by'])
355 355
             && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356 356
         ) {
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
             );
360 360
         }
361 361
 
362
-        if (! $all
362
+        if ( ! $all
363 363
             && ! empty($this->_req_data['ee_context_filter_by'])
364 364
             && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365 365
         ) {
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Queue.lib.php 2 patches
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4
-if (! defined('EVENT_ESPRESSO_VERSION')) {
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5 5
     exit('No direct script access allowed');
6 6
 }
7 7
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
             'order_by' => $this->_get_priority_orderby(),
183 183
             'limit'    => $this->_batch_count,
184 184
         );
185
-        $messages   = EEM_Message::instance()->get_all($query_args);
185
+        $messages = EEM_Message::instance()->get_all($query_args);
186 186
 
187 187
         if ( ! $messages) {
188 188
             return false; //nothing to generate
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
      */
288 288
     protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289 289
     {
290
-        return '_ee_lock_' . $type;
290
+        return '_ee_lock_'.$type;
291 291
     }
292 292
 
293 293
 
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
      */
300 300
     protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301 301
     {
302
-        return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
302
+        return (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303 303
     }
304 304
 
305 305
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      */
322 322
     protected function _get_rate_limit_expiry()
323 323
     {
324
-        return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
324
+        return (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325 325
     }
326 326
 
327 327
 
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
      */
333 333
     protected function _default_rate_limit()
334 334
     {
335
-        return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
335
+        return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336 336
     }
337 337
 
338 338
 
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
         $rate_limit = $this->get_rate_limit();
414 414
         $new_limit  = $rate_limit - $batch_completed;
415 415
         //updating the transient option directly to avoid resetting the expiry.
416
-        update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
416
+        update_option('_transient_'.$this->_get_rate_limit_key(), $new_limit);
417 417
     }
418 418
 
419 419
 
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
             /** @type EE_Message $message */
495 495
             $message = $this->_message_repository->current();
496 496
             //only process things that are queued for sending
497
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
497
+            if ( ! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498 498
                 $this->_message_repository->next();
499 499
                 continue;
500 500
             }
@@ -504,13 +504,13 @@  discard block
 block discarded – undo
504 504
                 continue;
505 505
             }
506 506
             //error checking
507
-            if (! $message->valid_messenger()) {
507
+            if ( ! $message->valid_messenger()) {
508 508
                 $error_messages[] = sprintf(
509 509
                     __('The %s messenger is not active at time of sending.', 'event_espresso'),
510 510
                     $message->messenger()
511 511
                 );
512 512
             }
513
-            if (! $message->valid_message_type()) {
513
+            if ( ! $message->valid_message_type()) {
514 514
                 $error_messages[] = sprintf(
515 515
                     __('The %s message type is not active at the time of sending.', 'event_espresso'),
516 516
                     $message->message_type()
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
      */
676 676
     protected function _set_error_message(EE_Message $message, $error_messages)
677 677
     {
678
-        $error_messages = (array)$error_messages;
678
+        $error_messages = (array) $error_messages;
679 679
         if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680 680
             $notices          = EE_Error::has_notices();
681 681
             $error_messages[] = __(
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
         }
691 691
         if (count($error_messages) > 0) {
692 692
             $msg = __('Message was not executed successfully.', 'event_espresso');
693
-            $msg = $msg . "\n" . implode("\n", $error_messages);
693
+            $msg = $msg."\n".implode("\n", $error_messages);
694 694
             $message->set_error_message($msg);
695 695
         }
696 696
     }
Please login to merge, or discard this patch.
Indentation   +677 added lines, -677 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4 4
 if (! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 /**
@@ -18,681 +18,681 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @type    string  reference for sending action
23
-     */
24
-    const action_sending = 'sending';
25
-
26
-    /**
27
-     * @type    string  reference for generation action
28
-     */
29
-    const action_generating = 'generation';
30
-
31
-
32
-    /**
33
-     * @type EE_Message_Repository $_message_repository
34
-     */
35
-    protected $_message_repository;
36
-
37
-    /**
38
-     * Sets the limit of how many messages are generated per process.
39
-     *
40
-     * @type int
41
-     */
42
-    protected $_batch_count;
43
-
44
-    /**
45
-     * Sets the limit of how many messages can be sent per hour.
46
-     *
47
-     * @type int
48
-     */
49
-    protected $_rate_limit;
50
-
51
-    /**
52
-     * This is an array of cached queue items being stored in this object.
53
-     * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
54
-     * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
55
-     *
56
-     * @type EE_Message[]
57
-     */
58
-    protected $_cached_queue_items;
59
-
60
-    /**
61
-     * Tracks the number of unsaved queue items.
62
-     *
63
-     * @type int
64
-     */
65
-    protected $_unsaved_count = 0;
66
-
67
-    /**
68
-     * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
69
-     * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
70
-     *
71
-     * @type array
72
-     */
73
-    protected $_did_hook = array();
74
-
75
-
76
-    /**
77
-     * Constructor.
78
-     * Setup all the initial properties and load a EE_Message_Repository.
79
-     *
80
-     * @param \EE_Message_Repository $message_repository
81
-     */
82
-    public function __construct(EE_Message_Repository $message_repository)
83
-    {
84
-        $this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
85
-        $this->_rate_limit         = $this->get_rate_limit();
86
-        $this->_message_repository = $message_repository;
87
-    }
88
-
89
-
90
-    /**
91
-     * Add a EE_Message object to the queue
92
-     *
93
-     * @param EE_Message $message
94
-     * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
95
-     *                                 object is persisted, this data will be saved on an extra_meta object related to
96
-     *                                 EE_Message.
97
-     * @param  bool      $preview      Whether this EE_Message represents a preview or not.
98
-     * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
99
-     *                                 use the messenger send method but typically is based on preview data.
100
-     * @return bool          Whether the message was successfully added to the repository or not.
101
-     */
102
-    public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
103
-    {
104
-        $data['preview']   = $preview;
105
-        $data['test_send'] = $test_send;
106
-        return $this->_message_repository->add($message, $data);
107
-    }
108
-
109
-
110
-    /**
111
-     * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
112
-     *
113
-     * @param EE_Message $message The message to detach from the queue
114
-     * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
115
-     * @return bool
116
-     */
117
-    public function remove(EE_Message $message, $persist = false)
118
-    {
119
-        if ($persist && $this->_message_repository->current() !== $message) {
120
-            //get pointer on right message
121
-            if ($this->_message_repository->has($message)) {
122
-                $this->_message_repository->rewind();
123
-                while ($this->_message_repository->valid()) {
124
-                    if ($this->_message_repository->current() === $message) {
125
-                        break;
126
-                    }
127
-                    $this->_message_repository->next();
128
-                }
129
-            } else {
130
-                return false;
131
-            }
132
-        }
133
-        return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
134
-    }
135
-
136
-
137
-    /**
138
-     * Persists all queued EE_Message objects to the db.
139
-     *
140
-     * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
141
-     * @return array @see EE_Messages_Repository::saveAll() for return values.
142
-     */
143
-    public function save($do_hooks_only = false)
144
-    {
145
-        return $this->_message_repository->saveAll($do_hooks_only);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return EE_Message_Repository
151
-     */
152
-    public function get_message_repository()
153
-    {
154
-        return $this->_message_repository;
155
-    }
156
-
157
-
158
-    /**
159
-     * This does the following things:
160
-     * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
161
-     * false).
162
-     * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
163
-     * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
164
-     * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
165
-     * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
166
-     * removed.
167
-     *
168
-     * @return bool  true if successfully retrieved batch, false no batch ready.
169
-     */
170
-    public function get_batch_to_generate()
171
-    {
172
-        if ($this->is_locked(EE_Messages_Queue::action_generating)) {
173
-            return false;
174
-        }
175
-
176
-        //lock batch generation to prevent race conditions.
177
-        $this->lock_queue(EE_Messages_Queue::action_generating);
178
-
179
-        $query_args = array(
180
-            // key 0 = where conditions
181
-            0          => array('STS_ID' => EEM_Message::status_incomplete),
182
-            'order_by' => $this->_get_priority_orderby(),
183
-            'limit'    => $this->_batch_count,
184
-        );
185
-        $messages   = EEM_Message::instance()->get_all($query_args);
186
-
187
-        if ( ! $messages) {
188
-            return false; //nothing to generate
189
-        }
190
-
191
-        foreach ($messages as $message) {
192
-            if ($message instanceof EE_Message) {
193
-                $data = $message->all_extra_meta_array();
194
-                $this->add($message, $data);
195
-            }
196
-        }
197
-        return true;
198
-    }
199
-
200
-
201
-    /**
202
-     * This does the following things:
203
-     * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
204
-     * false).
205
-     * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
206
-     * return false.
207
-     * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
208
-     * 3. On success or unsuccessful send, sets status appropriately.
209
-     * 4. Saves messages via the queue
210
-     * 5. Releases lock.
211
-     *
212
-     * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
213
-     *               necessarily mean that all messages were successfully sent.  It just means that this method
214
-     *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
215
-     *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
216
-     *               will also have a saved error message on it to assist with notifying user.
217
-     */
218
-    public function get_to_send_batch_and_send()
219
-    {
220
-        if ($this->is_locked(EE_Messages_Queue::action_sending) || $this->_rate_limit < 1) {
221
-            return false;
222
-        }
223
-
224
-        $this->lock_queue(EE_Messages_Queue::action_sending);
225
-
226
-        $batch = $this->_batch_count < $this->_rate_limit ? $this->_batch_count : $this->_rate_limit;
227
-
228
-        $query_args = array(
229
-            // key 0 = where conditions
230
-            0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
231
-            'order_by' => $this->_get_priority_orderby(),
232
-            'limit'    => $batch,
233
-        );
234
-
235
-        $messages_to_send = EEM_Message::instance()->get_all($query_args);
236
-
237
-
238
-        //any to send?
239
-        if ( ! $messages_to_send) {
240
-            $this->unlock_queue(EE_Messages_Queue::action_sending);
241
-            return false;
242
-        }
243
-
244
-        //add to queue.
245
-        foreach ($messages_to_send as $message) {
246
-            if ($message instanceof EE_Message) {
247
-                $this->add($message);
248
-            }
249
-        }
250
-
251
-        //send messages  (this also updates the rate limit)
252
-        $this->execute();
253
-
254
-        //release lock
255
-        $this->unlock_queue(EE_Messages_Queue::action_sending);
256
-        return true;
257
-    }
258
-
259
-
260
-    /**
261
-     * Locks the queue so that no other queues can call the "batch" methods.
262
-     *
263
-     * @param   string $type The type of queue being locked.
264
-     */
265
-    public function lock_queue($type = EE_Messages_Queue::action_generating)
266
-    {
267
-        set_transient($this->_get_lock_key($type), 1, $this->_get_lock_expiry($type));
268
-    }
269
-
270
-
271
-    /**
272
-     * Unlocks the queue so that batch methods can be used.
273
-     *
274
-     * @param   string $type The type of queue being unlocked.
275
-     */
276
-    public function unlock_queue($type = EE_Messages_Queue::action_generating)
277
-    {
278
-        delete_transient($this->_get_lock_key($type));
279
-    }
280
-
281
-
282
-    /**
283
-     * Retrieve the key used for the lock transient.
284
-     *
285
-     * @param string $type The type of lock.
286
-     * @return string
287
-     */
288
-    protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289
-    {
290
-        return '_ee_lock_' . $type;
291
-    }
292
-
293
-
294
-    /**
295
-     * Retrieve the expiry time for the lock transient.
296
-     *
297
-     * @param string $type The type of lock
298
-     * @return int   time to expiry in seconds.
299
-     */
300
-    protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301
-    {
302
-        return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303
-    }
304
-
305
-
306
-    /**
307
-     * Returns the key used for rate limit transient.
308
-     *
309
-     * @return string
310
-     */
311
-    protected function _get_rate_limit_key()
312
-    {
313
-        return '_ee_rate_limit';
314
-    }
315
-
316
-
317
-    /**
318
-     * Returns the rate limit expiry time.
319
-     *
320
-     * @return int
321
-     */
322
-    protected function _get_rate_limit_expiry()
323
-    {
324
-        return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325
-    }
326
-
327
-
328
-    /**
329
-     * Returns the default rate limit for sending messages.
330
-     *
331
-     * @return int
332
-     */
333
-    protected function _default_rate_limit()
334
-    {
335
-        return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336
-    }
337
-
338
-
339
-    /**
340
-     * Return the orderby array for priority.
341
-     *
342
-     * @return array
343
-     */
344
-    protected function _get_priority_orderby()
345
-    {
346
-        return array(
347
-            'MSG_priority' => 'ASC',
348
-            'MSG_modified' => 'DESC',
349
-        );
350
-    }
351
-
352
-
353
-    /**
354
-     * Returns whether batch methods are "locked" or not.
355
-     *
356
-     * @param  string $type The type of lock being checked for.
357
-     * @return bool
358
-     */
359
-    public function is_locked($type = EE_Messages_Queue::action_generating)
360
-    {
361
-        /**
362
-         * This filters the default is_locked behaviour.
363
-         */
364
-        $is_locked = filter_var(
365
-            apply_filters(
366
-                'FHEE__EE_Messages_Queue__is_locked',
367
-                get_transient($this->_get_lock_key($type)),
368
-                $this
369
-            ),
370
-            FILTER_VALIDATE_BOOLEAN
371
-        );
372
-
373
-        /**
374
-         * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
-         *            Also implemented here because messages processed on the same request should not have any locks applied.
376
-         */
377
-        if (
378
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
-        ) {
381
-            $is_locked = false;
382
-        }
383
-
384
-
385
-        return $is_locked;
386
-    }
387
-
388
-
389
-    /**
390
-     * Retrieves the rate limit that may be cached as a transient.
391
-     * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
-     *
393
-     * @return int
394
-     */
395
-    public function get_rate_limit()
396
-    {
397
-        if ( ! $rate_limit = get_transient($this->_get_rate_limit_key())) {
398
-            $rate_limit = $this->_default_rate_limit();
399
-            set_transient($this->_get_rate_limit_key(), $rate_limit, $this->_get_rate_limit_key());
400
-        }
401
-        return $rate_limit;
402
-    }
403
-
404
-
405
-    /**
406
-     * This updates existing rate limit with the new limit which is the old minus the batch.
407
-     *
408
-     * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
409
-     */
410
-    public function set_rate_limit($batch_completed)
411
-    {
412
-        //first get the most up to date rate limit (in case its expired and reset)
413
-        $rate_limit = $this->get_rate_limit();
414
-        $new_limit  = $rate_limit - $batch_completed;
415
-        //updating the transient option directly to avoid resetting the expiry.
416
-        update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
417
-    }
418
-
419
-
420
-    /**
421
-     * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
422
-     * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
423
-     * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
424
-     * request running on a queue for the given task.
425
-     *
426
-     * @param string $task     This indicates what type of request is going to be initiated.
427
-     * @param int    $priority This indicates the priority that triggers initiating the request.
428
-     */
429
-    public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
430
-    {
431
-        //determine what status is matched with the priority as part of the trigger conditions.
432
-        $status = $task == 'generate'
433
-            ? EEM_Message::status_incomplete
434
-            : EEM_Message::instance()->stati_indicating_to_send();
435
-        // always make sure we save because either this will get executed immediately on a separate request
436
-        // or remains in the queue for the regularly scheduled queue batch.
437
-        $this->save();
438
-        /**
439
-         * This filter/option allows users to override processing of messages on separate requests and instead have everything
440
-         * happen on the same request.  If this is utilized remember:
441
-         * - message priorities don't matter
442
-         * - existing unprocessed messages in the queue will not get processed unless manually triggered.
443
-         * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
444
-         *   processing happening on the same request.
445
-         * - any race condition protection (locks) are removed because they don't apply when things are processed on
446
-         *   the same request.
447
-         */
448
-        if (
449
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
450
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
451
-        ) {
452
-            $messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
453
-            if ($messages_processor instanceof EE_Messages_Processor) {
454
-                return $messages_processor->process_immediately_from_queue($this);
455
-            }
456
-            //if we get here then that means the messages processor couldn't be loaded so messages will just remain
457
-            //queued for manual triggering by end user.
458
-        }
459
-
460
-        if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
461
-            EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
462
-        }
463
-    }
464
-
465
-
466
-    /**
467
-     *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
468
-     *
469
-     * @param   bool     $save                    Used to indicate whether to save the message queue after sending
470
-     *                                            (default will save).
471
-     * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
472
-     *                                            what is on the EE_Message object in the queue.
473
-     *                                            For instance, showing the browser view of an email message,
474
-     *                                            or giving a pdf generated view of an html document.
475
-     *                                            This should be an instance of EE_messenger but if you call this
476
-     *                                            method
477
-     *                                            intending it to be a sending messenger but a valid one could not be
478
-     *                                            retrieved then send in an instance of EE_Error that contains the
479
-     *                                            related error message.
480
-     * @param   bool|int $by_priority             When set, this indicates that only messages
481
-     *                                            matching the given priority should be executed.
482
-     * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
483
-     *                                            Also, if the messenger is an request type messenger (or a preview),
484
-     *                                            its entirely possible that the messenger will exit before
485
-     */
486
-    public function execute($save = true, $sending_messenger = null, $by_priority = false)
487
-    {
488
-        $messages_sent   = 0;
489
-        $this->_did_hook = array();
490
-        $this->_message_repository->rewind();
491
-
492
-        while ($this->_message_repository->valid()) {
493
-            $error_messages = array();
494
-            /** @type EE_Message $message */
495
-            $message = $this->_message_repository->current();
496
-            //only process things that are queued for sending
497
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498
-                $this->_message_repository->next();
499
-                continue;
500
-            }
501
-            //if $by_priority is set and does not match then continue;
502
-            if ($by_priority && $by_priority != $message->priority()) {
503
-                $this->_message_repository->next();
504
-                continue;
505
-            }
506
-            //error checking
507
-            if (! $message->valid_messenger()) {
508
-                $error_messages[] = sprintf(
509
-                    __('The %s messenger is not active at time of sending.', 'event_espresso'),
510
-                    $message->messenger()
511
-                );
512
-            }
513
-            if (! $message->valid_message_type()) {
514
-                $error_messages[] = sprintf(
515
-                    __('The %s message type is not active at the time of sending.', 'event_espresso'),
516
-                    $message->message_type()
517
-                );
518
-            }
519
-            // if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
520
-            // then it will instead be an EE_Error object, so let's check for that
521
-            if ($sending_messenger instanceof EE_Error) {
522
-                $error_messages[] = $sending_messenger->getMessage();
523
-            }
524
-            // if there are no errors, then let's process the message
525
-            if (empty($error_messages)) {
526
-                if ($save) {
527
-                    $message->set_messenger_is_executing();
528
-                }
529
-                if ($this->_process_message($message, $sending_messenger)) {
530
-                    $messages_sent++;
531
-                }
532
-            }
533
-            $this->_set_error_message($message, $error_messages);
534
-            //add modified time
535
-            $message->set_modified(time());
536
-            //we save each message after its processed to make sure its status persists in case PHP times-out or runs
537
-            //out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
538
-            if ($save) {
539
-                $message->save();
540
-            }
541
-
542
-            $this->_message_repository->next();
543
-        }
544
-        if ($save) {
545
-            $this->save(true);
546
-        }
547
-        return $messages_sent;
548
-    }
549
-
550
-
551
-    /**
552
-     * _process_message
553
-     *
554
-     * @param EE_Message $message
555
-     * @param mixed      $sending_messenger (optional)
556
-     * @return bool
557
-     */
558
-    protected function _process_message(EE_Message $message, $sending_messenger = null)
559
-    {
560
-        // these *should* have been validated in the execute() method above
561
-        $messenger    = $message->messenger_object();
562
-        $message_type = $message->message_type_object();
563
-        //do actions for sending messenger if it differs from generating messenger and swap values.
564
-        if (
565
-            $sending_messenger instanceof EE_messenger
566
-            && $messenger instanceof EE_messenger
567
-            && $sending_messenger->name != $messenger->name
568
-        ) {
569
-            $messenger->do_secondary_messenger_hooks($sending_messenger->name);
570
-            $messenger = $sending_messenger;
571
-        }
572
-        // send using messenger, but double check objects
573
-        if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
574
-            //set hook for message type (but only if not using another messenger to send).
575
-            if ( ! isset($this->_did_hook[$message_type->name])) {
576
-                $message_type->do_messenger_hooks($messenger);
577
-                $this->_did_hook[$message_type->name] = 1;
578
-            }
579
-            //if preview then use preview method
580
-            return $this->_message_repository->is_preview()
581
-                ? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
582
-                : $this->_do_send($message, $messenger, $message_type);
583
-        }
584
-        return false;
585
-    }
586
-
587
-
588
-    /**
589
-     * The intention of this method is to count how many EE_Message objects
590
-     * are in the queue with a given status.
591
-     * Example usage:
592
-     * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
593
-     * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
594
-     *
595
-     * @param array|string $status Stati to check for in queue
596
-     * @return int  Count of EE_Message's matching the given status.
597
-     */
598
-    public function count_STS_in_queue($status)
599
-    {
600
-        $count  = 0;
601
-        $status = is_array($status) ? $status : array($status);
602
-        $this->_message_repository->rewind();
603
-        foreach ($this->_message_repository as $message) {
604
-            if (in_array($message->STS_ID(), $status)) {
605
-                $count++;
606
-            }
607
-        }
608
-        return $count;
609
-    }
610
-
611
-
612
-    /**
613
-     * Executes the get_preview method on the provided messenger.
614
-     *
615
-     * @param EE_Message      $message
616
-     * @param EE_messenger    $messenger
617
-     * @param EE_message_type $message_type
618
-     * @param                 $test_send
619
-     * @return bool   true means all went well, false means, not so much.
620
-     */
621
-    protected function _do_preview(
622
-        EE_Message $message,
623
-        EE_messenger $messenger,
624
-        EE_message_type $message_type,
625
-        $test_send
626
-    ) {
627
-        if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
628
-            if ( ! $test_send) {
629
-                $message->set_content($preview);
630
-            }
631
-            $message->set_STS_ID(EEM_Message::status_sent);
632
-            return true;
633
-        } else {
634
-            $message->set_STS_ID(EEM_Message::status_failed);
635
-            return false;
636
-        }
637
-    }
638
-
639
-
640
-    /**
641
-     * Executes the send method on the provided messenger
642
-     * EE_Messengers are expected to:
643
-     * - return true if the send was successful.
644
-     * - return false if the send was unsuccessful but can be tried again.
645
-     * - throw an Exception if the send was unsuccessful and cannot be tried again.
646
-     *
647
-     * @param EE_Message      $message
648
-     * @param EE_messenger    $messenger
649
-     * @param EE_message_type $message_type
650
-     * @return bool true means all went well, false means, not so much.
651
-     */
652
-    protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
653
-    {
654
-        try {
655
-            if ($messenger->send_message($message, $message_type)) {
656
-                $message->set_STS_ID(EEM_Message::status_sent);
657
-                return true;
658
-            } else {
659
-                $message->set_STS_ID(EEM_Message::status_retry);
660
-                return false;
661
-            }
662
-        } catch (SendMessageException $e) {
663
-            $message->set_STS_ID(EEM_Message::status_failed);
664
-            $message->set_error_message($e->getMessage());
665
-            return false;
666
-        }
667
-    }
668
-
669
-
670
-    /**
671
-     * This sets any necessary error messages on the message object and its status to failed.
672
-     *
673
-     * @param EE_Message $message
674
-     * @param array      $error_messages the response from the messenger.
675
-     */
676
-    protected function _set_error_message(EE_Message $message, $error_messages)
677
-    {
678
-        $error_messages = (array)$error_messages;
679
-        if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680
-            $notices          = EE_Error::has_notices();
681
-            $error_messages[] = __(
682
-                'Messenger and Message Type were valid and active, but the messenger send method failed.',
683
-                'event_espresso'
684
-            );
685
-            if ($notices === 1) {
686
-                $notices           = EE_Error::get_vanilla_notices();
687
-                $notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
688
-                $error_messages[]  = implode("\n", $notices['errors']);
689
-            }
690
-        }
691
-        if (count($error_messages) > 0) {
692
-            $msg = __('Message was not executed successfully.', 'event_espresso');
693
-            $msg = $msg . "\n" . implode("\n", $error_messages);
694
-            $message->set_error_message($msg);
695
-        }
696
-    }
21
+	/**
22
+	 * @type    string  reference for sending action
23
+	 */
24
+	const action_sending = 'sending';
25
+
26
+	/**
27
+	 * @type    string  reference for generation action
28
+	 */
29
+	const action_generating = 'generation';
30
+
31
+
32
+	/**
33
+	 * @type EE_Message_Repository $_message_repository
34
+	 */
35
+	protected $_message_repository;
36
+
37
+	/**
38
+	 * Sets the limit of how many messages are generated per process.
39
+	 *
40
+	 * @type int
41
+	 */
42
+	protected $_batch_count;
43
+
44
+	/**
45
+	 * Sets the limit of how many messages can be sent per hour.
46
+	 *
47
+	 * @type int
48
+	 */
49
+	protected $_rate_limit;
50
+
51
+	/**
52
+	 * This is an array of cached queue items being stored in this object.
53
+	 * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
54
+	 * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
55
+	 *
56
+	 * @type EE_Message[]
57
+	 */
58
+	protected $_cached_queue_items;
59
+
60
+	/**
61
+	 * Tracks the number of unsaved queue items.
62
+	 *
63
+	 * @type int
64
+	 */
65
+	protected $_unsaved_count = 0;
66
+
67
+	/**
68
+	 * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
69
+	 * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
70
+	 *
71
+	 * @type array
72
+	 */
73
+	protected $_did_hook = array();
74
+
75
+
76
+	/**
77
+	 * Constructor.
78
+	 * Setup all the initial properties and load a EE_Message_Repository.
79
+	 *
80
+	 * @param \EE_Message_Repository $message_repository
81
+	 */
82
+	public function __construct(EE_Message_Repository $message_repository)
83
+	{
84
+		$this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
85
+		$this->_rate_limit         = $this->get_rate_limit();
86
+		$this->_message_repository = $message_repository;
87
+	}
88
+
89
+
90
+	/**
91
+	 * Add a EE_Message object to the queue
92
+	 *
93
+	 * @param EE_Message $message
94
+	 * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
95
+	 *                                 object is persisted, this data will be saved on an extra_meta object related to
96
+	 *                                 EE_Message.
97
+	 * @param  bool      $preview      Whether this EE_Message represents a preview or not.
98
+	 * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
99
+	 *                                 use the messenger send method but typically is based on preview data.
100
+	 * @return bool          Whether the message was successfully added to the repository or not.
101
+	 */
102
+	public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
103
+	{
104
+		$data['preview']   = $preview;
105
+		$data['test_send'] = $test_send;
106
+		return $this->_message_repository->add($message, $data);
107
+	}
108
+
109
+
110
+	/**
111
+	 * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
112
+	 *
113
+	 * @param EE_Message $message The message to detach from the queue
114
+	 * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
115
+	 * @return bool
116
+	 */
117
+	public function remove(EE_Message $message, $persist = false)
118
+	{
119
+		if ($persist && $this->_message_repository->current() !== $message) {
120
+			//get pointer on right message
121
+			if ($this->_message_repository->has($message)) {
122
+				$this->_message_repository->rewind();
123
+				while ($this->_message_repository->valid()) {
124
+					if ($this->_message_repository->current() === $message) {
125
+						break;
126
+					}
127
+					$this->_message_repository->next();
128
+				}
129
+			} else {
130
+				return false;
131
+			}
132
+		}
133
+		return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
134
+	}
135
+
136
+
137
+	/**
138
+	 * Persists all queued EE_Message objects to the db.
139
+	 *
140
+	 * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
141
+	 * @return array @see EE_Messages_Repository::saveAll() for return values.
142
+	 */
143
+	public function save($do_hooks_only = false)
144
+	{
145
+		return $this->_message_repository->saveAll($do_hooks_only);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return EE_Message_Repository
151
+	 */
152
+	public function get_message_repository()
153
+	{
154
+		return $this->_message_repository;
155
+	}
156
+
157
+
158
+	/**
159
+	 * This does the following things:
160
+	 * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
161
+	 * false).
162
+	 * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
163
+	 * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
164
+	 * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
165
+	 * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
166
+	 * removed.
167
+	 *
168
+	 * @return bool  true if successfully retrieved batch, false no batch ready.
169
+	 */
170
+	public function get_batch_to_generate()
171
+	{
172
+		if ($this->is_locked(EE_Messages_Queue::action_generating)) {
173
+			return false;
174
+		}
175
+
176
+		//lock batch generation to prevent race conditions.
177
+		$this->lock_queue(EE_Messages_Queue::action_generating);
178
+
179
+		$query_args = array(
180
+			// key 0 = where conditions
181
+			0          => array('STS_ID' => EEM_Message::status_incomplete),
182
+			'order_by' => $this->_get_priority_orderby(),
183
+			'limit'    => $this->_batch_count,
184
+		);
185
+		$messages   = EEM_Message::instance()->get_all($query_args);
186
+
187
+		if ( ! $messages) {
188
+			return false; //nothing to generate
189
+		}
190
+
191
+		foreach ($messages as $message) {
192
+			if ($message instanceof EE_Message) {
193
+				$data = $message->all_extra_meta_array();
194
+				$this->add($message, $data);
195
+			}
196
+		}
197
+		return true;
198
+	}
199
+
200
+
201
+	/**
202
+	 * This does the following things:
203
+	 * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
204
+	 * false).
205
+	 * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
206
+	 * return false.
207
+	 * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
208
+	 * 3. On success or unsuccessful send, sets status appropriately.
209
+	 * 4. Saves messages via the queue
210
+	 * 5. Releases lock.
211
+	 *
212
+	 * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
213
+	 *               necessarily mean that all messages were successfully sent.  It just means that this method
214
+	 *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
215
+	 *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
216
+	 *               will also have a saved error message on it to assist with notifying user.
217
+	 */
218
+	public function get_to_send_batch_and_send()
219
+	{
220
+		if ($this->is_locked(EE_Messages_Queue::action_sending) || $this->_rate_limit < 1) {
221
+			return false;
222
+		}
223
+
224
+		$this->lock_queue(EE_Messages_Queue::action_sending);
225
+
226
+		$batch = $this->_batch_count < $this->_rate_limit ? $this->_batch_count : $this->_rate_limit;
227
+
228
+		$query_args = array(
229
+			// key 0 = where conditions
230
+			0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
231
+			'order_by' => $this->_get_priority_orderby(),
232
+			'limit'    => $batch,
233
+		);
234
+
235
+		$messages_to_send = EEM_Message::instance()->get_all($query_args);
236
+
237
+
238
+		//any to send?
239
+		if ( ! $messages_to_send) {
240
+			$this->unlock_queue(EE_Messages_Queue::action_sending);
241
+			return false;
242
+		}
243
+
244
+		//add to queue.
245
+		foreach ($messages_to_send as $message) {
246
+			if ($message instanceof EE_Message) {
247
+				$this->add($message);
248
+			}
249
+		}
250
+
251
+		//send messages  (this also updates the rate limit)
252
+		$this->execute();
253
+
254
+		//release lock
255
+		$this->unlock_queue(EE_Messages_Queue::action_sending);
256
+		return true;
257
+	}
258
+
259
+
260
+	/**
261
+	 * Locks the queue so that no other queues can call the "batch" methods.
262
+	 *
263
+	 * @param   string $type The type of queue being locked.
264
+	 */
265
+	public function lock_queue($type = EE_Messages_Queue::action_generating)
266
+	{
267
+		set_transient($this->_get_lock_key($type), 1, $this->_get_lock_expiry($type));
268
+	}
269
+
270
+
271
+	/**
272
+	 * Unlocks the queue so that batch methods can be used.
273
+	 *
274
+	 * @param   string $type The type of queue being unlocked.
275
+	 */
276
+	public function unlock_queue($type = EE_Messages_Queue::action_generating)
277
+	{
278
+		delete_transient($this->_get_lock_key($type));
279
+	}
280
+
281
+
282
+	/**
283
+	 * Retrieve the key used for the lock transient.
284
+	 *
285
+	 * @param string $type The type of lock.
286
+	 * @return string
287
+	 */
288
+	protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289
+	{
290
+		return '_ee_lock_' . $type;
291
+	}
292
+
293
+
294
+	/**
295
+	 * Retrieve the expiry time for the lock transient.
296
+	 *
297
+	 * @param string $type The type of lock
298
+	 * @return int   time to expiry in seconds.
299
+	 */
300
+	protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301
+	{
302
+		return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303
+	}
304
+
305
+
306
+	/**
307
+	 * Returns the key used for rate limit transient.
308
+	 *
309
+	 * @return string
310
+	 */
311
+	protected function _get_rate_limit_key()
312
+	{
313
+		return '_ee_rate_limit';
314
+	}
315
+
316
+
317
+	/**
318
+	 * Returns the rate limit expiry time.
319
+	 *
320
+	 * @return int
321
+	 */
322
+	protected function _get_rate_limit_expiry()
323
+	{
324
+		return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325
+	}
326
+
327
+
328
+	/**
329
+	 * Returns the default rate limit for sending messages.
330
+	 *
331
+	 * @return int
332
+	 */
333
+	protected function _default_rate_limit()
334
+	{
335
+		return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336
+	}
337
+
338
+
339
+	/**
340
+	 * Return the orderby array for priority.
341
+	 *
342
+	 * @return array
343
+	 */
344
+	protected function _get_priority_orderby()
345
+	{
346
+		return array(
347
+			'MSG_priority' => 'ASC',
348
+			'MSG_modified' => 'DESC',
349
+		);
350
+	}
351
+
352
+
353
+	/**
354
+	 * Returns whether batch methods are "locked" or not.
355
+	 *
356
+	 * @param  string $type The type of lock being checked for.
357
+	 * @return bool
358
+	 */
359
+	public function is_locked($type = EE_Messages_Queue::action_generating)
360
+	{
361
+		/**
362
+		 * This filters the default is_locked behaviour.
363
+		 */
364
+		$is_locked = filter_var(
365
+			apply_filters(
366
+				'FHEE__EE_Messages_Queue__is_locked',
367
+				get_transient($this->_get_lock_key($type)),
368
+				$this
369
+			),
370
+			FILTER_VALIDATE_BOOLEAN
371
+		);
372
+
373
+		/**
374
+		 * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
+		 *            Also implemented here because messages processed on the same request should not have any locks applied.
376
+		 */
377
+		if (
378
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
+		) {
381
+			$is_locked = false;
382
+		}
383
+
384
+
385
+		return $is_locked;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Retrieves the rate limit that may be cached as a transient.
391
+	 * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
+	 *
393
+	 * @return int
394
+	 */
395
+	public function get_rate_limit()
396
+	{
397
+		if ( ! $rate_limit = get_transient($this->_get_rate_limit_key())) {
398
+			$rate_limit = $this->_default_rate_limit();
399
+			set_transient($this->_get_rate_limit_key(), $rate_limit, $this->_get_rate_limit_key());
400
+		}
401
+		return $rate_limit;
402
+	}
403
+
404
+
405
+	/**
406
+	 * This updates existing rate limit with the new limit which is the old minus the batch.
407
+	 *
408
+	 * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
409
+	 */
410
+	public function set_rate_limit($batch_completed)
411
+	{
412
+		//first get the most up to date rate limit (in case its expired and reset)
413
+		$rate_limit = $this->get_rate_limit();
414
+		$new_limit  = $rate_limit - $batch_completed;
415
+		//updating the transient option directly to avoid resetting the expiry.
416
+		update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
417
+	}
418
+
419
+
420
+	/**
421
+	 * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
422
+	 * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
423
+	 * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
424
+	 * request running on a queue for the given task.
425
+	 *
426
+	 * @param string $task     This indicates what type of request is going to be initiated.
427
+	 * @param int    $priority This indicates the priority that triggers initiating the request.
428
+	 */
429
+	public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
430
+	{
431
+		//determine what status is matched with the priority as part of the trigger conditions.
432
+		$status = $task == 'generate'
433
+			? EEM_Message::status_incomplete
434
+			: EEM_Message::instance()->stati_indicating_to_send();
435
+		// always make sure we save because either this will get executed immediately on a separate request
436
+		// or remains in the queue for the regularly scheduled queue batch.
437
+		$this->save();
438
+		/**
439
+		 * This filter/option allows users to override processing of messages on separate requests and instead have everything
440
+		 * happen on the same request.  If this is utilized remember:
441
+		 * - message priorities don't matter
442
+		 * - existing unprocessed messages in the queue will not get processed unless manually triggered.
443
+		 * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
444
+		 *   processing happening on the same request.
445
+		 * - any race condition protection (locks) are removed because they don't apply when things are processed on
446
+		 *   the same request.
447
+		 */
448
+		if (
449
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
450
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
451
+		) {
452
+			$messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
453
+			if ($messages_processor instanceof EE_Messages_Processor) {
454
+				return $messages_processor->process_immediately_from_queue($this);
455
+			}
456
+			//if we get here then that means the messages processor couldn't be loaded so messages will just remain
457
+			//queued for manual triggering by end user.
458
+		}
459
+
460
+		if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
461
+			EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
462
+		}
463
+	}
464
+
465
+
466
+	/**
467
+	 *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
468
+	 *
469
+	 * @param   bool     $save                    Used to indicate whether to save the message queue after sending
470
+	 *                                            (default will save).
471
+	 * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
472
+	 *                                            what is on the EE_Message object in the queue.
473
+	 *                                            For instance, showing the browser view of an email message,
474
+	 *                                            or giving a pdf generated view of an html document.
475
+	 *                                            This should be an instance of EE_messenger but if you call this
476
+	 *                                            method
477
+	 *                                            intending it to be a sending messenger but a valid one could not be
478
+	 *                                            retrieved then send in an instance of EE_Error that contains the
479
+	 *                                            related error message.
480
+	 * @param   bool|int $by_priority             When set, this indicates that only messages
481
+	 *                                            matching the given priority should be executed.
482
+	 * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
483
+	 *                                            Also, if the messenger is an request type messenger (or a preview),
484
+	 *                                            its entirely possible that the messenger will exit before
485
+	 */
486
+	public function execute($save = true, $sending_messenger = null, $by_priority = false)
487
+	{
488
+		$messages_sent   = 0;
489
+		$this->_did_hook = array();
490
+		$this->_message_repository->rewind();
491
+
492
+		while ($this->_message_repository->valid()) {
493
+			$error_messages = array();
494
+			/** @type EE_Message $message */
495
+			$message = $this->_message_repository->current();
496
+			//only process things that are queued for sending
497
+			if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498
+				$this->_message_repository->next();
499
+				continue;
500
+			}
501
+			//if $by_priority is set and does not match then continue;
502
+			if ($by_priority && $by_priority != $message->priority()) {
503
+				$this->_message_repository->next();
504
+				continue;
505
+			}
506
+			//error checking
507
+			if (! $message->valid_messenger()) {
508
+				$error_messages[] = sprintf(
509
+					__('The %s messenger is not active at time of sending.', 'event_espresso'),
510
+					$message->messenger()
511
+				);
512
+			}
513
+			if (! $message->valid_message_type()) {
514
+				$error_messages[] = sprintf(
515
+					__('The %s message type is not active at the time of sending.', 'event_espresso'),
516
+					$message->message_type()
517
+				);
518
+			}
519
+			// if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
520
+			// then it will instead be an EE_Error object, so let's check for that
521
+			if ($sending_messenger instanceof EE_Error) {
522
+				$error_messages[] = $sending_messenger->getMessage();
523
+			}
524
+			// if there are no errors, then let's process the message
525
+			if (empty($error_messages)) {
526
+				if ($save) {
527
+					$message->set_messenger_is_executing();
528
+				}
529
+				if ($this->_process_message($message, $sending_messenger)) {
530
+					$messages_sent++;
531
+				}
532
+			}
533
+			$this->_set_error_message($message, $error_messages);
534
+			//add modified time
535
+			$message->set_modified(time());
536
+			//we save each message after its processed to make sure its status persists in case PHP times-out or runs
537
+			//out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
538
+			if ($save) {
539
+				$message->save();
540
+			}
541
+
542
+			$this->_message_repository->next();
543
+		}
544
+		if ($save) {
545
+			$this->save(true);
546
+		}
547
+		return $messages_sent;
548
+	}
549
+
550
+
551
+	/**
552
+	 * _process_message
553
+	 *
554
+	 * @param EE_Message $message
555
+	 * @param mixed      $sending_messenger (optional)
556
+	 * @return bool
557
+	 */
558
+	protected function _process_message(EE_Message $message, $sending_messenger = null)
559
+	{
560
+		// these *should* have been validated in the execute() method above
561
+		$messenger    = $message->messenger_object();
562
+		$message_type = $message->message_type_object();
563
+		//do actions for sending messenger if it differs from generating messenger and swap values.
564
+		if (
565
+			$sending_messenger instanceof EE_messenger
566
+			&& $messenger instanceof EE_messenger
567
+			&& $sending_messenger->name != $messenger->name
568
+		) {
569
+			$messenger->do_secondary_messenger_hooks($sending_messenger->name);
570
+			$messenger = $sending_messenger;
571
+		}
572
+		// send using messenger, but double check objects
573
+		if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
574
+			//set hook for message type (but only if not using another messenger to send).
575
+			if ( ! isset($this->_did_hook[$message_type->name])) {
576
+				$message_type->do_messenger_hooks($messenger);
577
+				$this->_did_hook[$message_type->name] = 1;
578
+			}
579
+			//if preview then use preview method
580
+			return $this->_message_repository->is_preview()
581
+				? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
582
+				: $this->_do_send($message, $messenger, $message_type);
583
+		}
584
+		return false;
585
+	}
586
+
587
+
588
+	/**
589
+	 * The intention of this method is to count how many EE_Message objects
590
+	 * are in the queue with a given status.
591
+	 * Example usage:
592
+	 * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
593
+	 * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
594
+	 *
595
+	 * @param array|string $status Stati to check for in queue
596
+	 * @return int  Count of EE_Message's matching the given status.
597
+	 */
598
+	public function count_STS_in_queue($status)
599
+	{
600
+		$count  = 0;
601
+		$status = is_array($status) ? $status : array($status);
602
+		$this->_message_repository->rewind();
603
+		foreach ($this->_message_repository as $message) {
604
+			if (in_array($message->STS_ID(), $status)) {
605
+				$count++;
606
+			}
607
+		}
608
+		return $count;
609
+	}
610
+
611
+
612
+	/**
613
+	 * Executes the get_preview method on the provided messenger.
614
+	 *
615
+	 * @param EE_Message      $message
616
+	 * @param EE_messenger    $messenger
617
+	 * @param EE_message_type $message_type
618
+	 * @param                 $test_send
619
+	 * @return bool   true means all went well, false means, not so much.
620
+	 */
621
+	protected function _do_preview(
622
+		EE_Message $message,
623
+		EE_messenger $messenger,
624
+		EE_message_type $message_type,
625
+		$test_send
626
+	) {
627
+		if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
628
+			if ( ! $test_send) {
629
+				$message->set_content($preview);
630
+			}
631
+			$message->set_STS_ID(EEM_Message::status_sent);
632
+			return true;
633
+		} else {
634
+			$message->set_STS_ID(EEM_Message::status_failed);
635
+			return false;
636
+		}
637
+	}
638
+
639
+
640
+	/**
641
+	 * Executes the send method on the provided messenger
642
+	 * EE_Messengers are expected to:
643
+	 * - return true if the send was successful.
644
+	 * - return false if the send was unsuccessful but can be tried again.
645
+	 * - throw an Exception if the send was unsuccessful and cannot be tried again.
646
+	 *
647
+	 * @param EE_Message      $message
648
+	 * @param EE_messenger    $messenger
649
+	 * @param EE_message_type $message_type
650
+	 * @return bool true means all went well, false means, not so much.
651
+	 */
652
+	protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
653
+	{
654
+		try {
655
+			if ($messenger->send_message($message, $message_type)) {
656
+				$message->set_STS_ID(EEM_Message::status_sent);
657
+				return true;
658
+			} else {
659
+				$message->set_STS_ID(EEM_Message::status_retry);
660
+				return false;
661
+			}
662
+		} catch (SendMessageException $e) {
663
+			$message->set_STS_ID(EEM_Message::status_failed);
664
+			$message->set_error_message($e->getMessage());
665
+			return false;
666
+		}
667
+	}
668
+
669
+
670
+	/**
671
+	 * This sets any necessary error messages on the message object and its status to failed.
672
+	 *
673
+	 * @param EE_Message $message
674
+	 * @param array      $error_messages the response from the messenger.
675
+	 */
676
+	protected function _set_error_message(EE_Message $message, $error_messages)
677
+	{
678
+		$error_messages = (array)$error_messages;
679
+		if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680
+			$notices          = EE_Error::has_notices();
681
+			$error_messages[] = __(
682
+				'Messenger and Message Type were valid and active, but the messenger send method failed.',
683
+				'event_espresso'
684
+			);
685
+			if ($notices === 1) {
686
+				$notices           = EE_Error::get_vanilla_notices();
687
+				$notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
688
+				$error_messages[]  = implode("\n", $notices['errors']);
689
+			}
690
+		}
691
+		if (count($error_messages) > 0) {
692
+			$msg = __('Message was not executed successfully.', 'event_espresso');
693
+			$msg = $msg . "\n" . implode("\n", $error_messages);
694
+			$message->set_error_message($msg);
695
+		}
696
+	}
697 697
 
698 698
 } //end EE_Messages_Queue class
Please login to merge, or discard this patch.