Test Failed
Push — issue/3627 ( fa91e5...bf57b1 )
by Ravinder
10:14
created

Give_Comment::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Class for managing comments
5
 *
6
 * @package     Give
7
 * @subpackage  Classes/Give_Cache
8
 * @copyright   Copyright (c) 2018, WordImpress
9
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
10
 * @since       2.2.0
11
 */
12
class Give_Comment {
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
13
	/**
14
	 * Instance.
15
	 *
16
	 * @since  2.2.0
17
	 * @access private
18
	 * @var
19
	 */
20
	static private $instance;
21
22
	/**
23
	 * Comment Types.
24
	 *
25
	 * @since  2.2.0
26
	 * @access private
27
	 * @var array
28
	 */
29
	private $comment_types;
30
31
	/**
32
	 * Comment Table.
33
	 *
34
	 * @since  2.3.0
35
	 * @access public
36
	 * @var Give_DB_Comments
37
	 */
38
	public $db;
39
40
	/**
41
	 * Comment Meta Table.
42
	 *
43
	 * @since  2.3.0
44
	 * @access public
45
	 * @var Give_DB_Comment_Meta
46
	 */
47
	public $db_meta;
48
49
	/**
50
	 * Singleton pattern.
51
	 *
52
	 * @since  2.2.0
53
	 * @access private
54
	 */
55
	private function __construct() {
56
	}
57
58
59
	/**
60
	 * Get instance.
61
	 *
62
	 * @since  2.2.0
63
	 * @access pu
64
	 * @return Give_Comment
65
	 */
66
	public static function get_instance() {
67
		if ( null === static::$instance ) {
68
			self::$instance = new static();
69
			self::$instance->init();
70
		}
71
72
		return self::$instance;
73
	}
74
75
	/**
76
	 * Initialize
77
	 *
78
	 * @since  2.2.0
79
	 * @access private
80
	 */
81
	private function init() {
82
		$this->db      = new Give_DB_Comments();
83
		$this->db_meta = new Give_DB_Comment_Meta();
84
85
		/**
86
		 * Filter the comment type
87
		 *
88
		 * @since 2.2.0
89
		 */
90
		$this->comment_types = apply_filters(
91
			'give_comment_type',
92
			self::get_comment_types( array( 'payment', 'donor' ) )
93
		);
94
95
		add_action( 'pre_get_comments', array( $this, 'hide_comments' ), 10 );
96
		add_filter( 'comments_clauses', array( $this, 'hide_comments_pre_wp_41' ), 10, 1 );
97
		add_filter( 'comment_feed_where', array( $this, 'hide_comments_from_feeds' ), 10, 1 );
98
		add_filter( 'wp_count_comments', array( $this, 'remove_comments_from_comment_counts' ), 10, 2 );
99
		add_filter( 'get_comment_author', array( $this, '__get_comment_author' ), 10, 3 );
100
	}
101
102
	/**
103
	 * Insert/Update comment
104
	 *
105
	 * @since  2.2.0
106
	 * @access public
107
	 *
108
	 * @param int    $id           Payment|Donor ID.
109
	 * @param string $note         Comment Text
110
	 * @param string $comment_type Value can ve donor|payment
111
	 * @param array  $comment_args Comment arguments
112
	 *
113
	 * @return int|WP_Error
114
	 */
115
	public static function add( $id, $note, $comment_type, $comment_args = array() ) {
116
		if( give_has_upgrade_completed('v230_move_donor_note' ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
117
			give_doing_it_wrong( __FUNCTION__, 'You can use Give()->comment->db or Give()->comment->db_meta to store note/comment data in new table.', '2.3.0' );
118
		}
119
120
		// Bailout
121
		if ( empty( $id ) || empty( $note ) || empty( $comment_type ) ) {
122
			return new WP_Error( 'give_invalid_required_param', __( 'This comment has invalid ID or comment text or comment type', 'give' ) );
123
		}
124
125
		$is_existing_comment = array_key_exists( 'comment_ID', $comment_args ) && ! empty( $comment_args['comment_ID'] );
126
		$action_type         = $is_existing_comment ? 'update' : 'insert';
127
128
		/**
129
		 * Fires before inserting/updating payment|donor comment.
130
		 *
131
		 * @param int    $id   Payment|Donor ID.
132
		 * @param string $note Comment text.
133
		 *
134
		 * @since 1.0
135
		 */
136
		do_action( "give_pre_{$action_type}_{$comment_type}_note", $id, $note );
137
138
		$comment_args = wp_parse_args(
139
			$comment_args,
140
			array(
141
				'comment_post_ID'      => $id,
142
				'comment_content'      => $note,
143
				'user_id'              => is_admin() ? get_current_user_id() : 0,
144
				'comment_date'         => current_time( 'mysql' ),
145
				'comment_date_gmt'     => current_time( 'mysql', 1 ),
146
				'comment_approved'     => 1,
147
				'comment_parent'       => 0,
148
				'comment_author'       => '',
149
				'comment_author_IP'    => '',
150
				'comment_author_url'   => '',
151
				'comment_author_email' => '',
152
				'comment_type'         => "give_{$comment_type}_note",
153
154
			)
155
		);
156
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
157
158
		// Check comment max length.
159
		$error = wp_check_comment_data_max_lengths( $comment_args );
160
		if( is_wp_error( $error ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
161
			return $error;
162
		}
163
164
		// Remove moderation emails when comment posted.
165
		remove_action( 'comment_post', 'wp_new_comment_notify_moderator' );
166
		remove_action( 'comment_post', 'wp_new_comment_notify_postauthor' );
167
168
		// Remove comment flood check.
169
		remove_action( 'check_comment_flood', 'check_comment_flood_db', 10 );
170
171
		$comment_id = $is_existing_comment
172
			? wp_update_comment( $comment_args )
173
			: wp_new_comment( $comment_args, true );
174
175
		// Add moderation emails when comment posted.
176
		add_action( 'comment_post', 'wp_new_comment_notify_moderator' );
177
		add_action( 'comment_post', 'wp_new_comment_notify_postauthor' );
178
179
		// Add comment flood check.
180
		add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 4 );
181
182
		update_comment_meta( $comment_id, "_give_{$comment_type}_id", $id );
183
184
		/**
185
		 * Fires after payment|donor comment inserted/updated.
186
		 *
187
		 * @param int    $comment_id Comment ID.
188
		 * @param int    $id         Payment|Donor ID.
189
		 * @param string $note       Comment text.
190
		 *
191
		 * @since 1.0
192
		 */
193
		do_action( "give_{$action_type}_{$comment_type}_note", $comment_id, $id, $note );
194
195
		return $comment_id;
196
	}
197
198
199
	/**
200
	 * Delete comment
201
	 *
202
	 * @since  2.2.0
203
	 * @access public
204
	 *
205
	 * @param int    $comment_id   The comment ID to delete.
206
	 * @param int    $id           The payment|Donor ID the note is connected to.
207
	 * @param string $comment_type Value can ve donor|payment.
208
	 *
209
	 * @since  1.0
210
	 *
211
	 * @return bool True on success, false otherwise.
212
	 */
213
	public static function delete( $comment_id, $id, $comment_type ) {
214
		if( give_has_upgrade_completed('v230_move_donor_note' ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
215
			give_doing_it_wrong( __FUNCTION__, 'You can use Give()->comment->db or Give()->comment->db_meta to delete note/comment data from new table.', '2.3.0' );
216
		}
217
218
		$ret = false;
219
220
		// Bailout
221
		if ( empty( $id ) || empty( $comment_id ) || empty( $comment_type ) ) {
222
			return $ret;
223
		}
224
225
		/**
226
		 * Fires before deleting donation note.
227
		 *
228
		 * @param int $comment_id Comment ID.
229
		 * @param int $id         Payment|Donor ID.
230
		 *
231
		 * @since 1.0
232
		 */
233
		do_action( "give_pre_delete_{$comment_type}_note", $comment_id, $id );
234
235
		$ret = wp_delete_comment( $comment_id, true );
236
237
		/**
238
		 * Fires after donation note deleted.
239
		 *
240
		 * @param int  $comment_id Note ID.
241
		 * @param int  $id         Payment|Donor ID.
242
		 * @param bool $ret        Flag to check if comment deleted or not.
243
		 *
244
		 * @since 1.0
245
		 */
246
		do_action( "give_post_delete_{$comment_type}_note", $comment_id, $id, $ret );
247
248
		return $ret;
249
	}
250
251
252
	/**
253
	 * Get comments
254
	 *
255
	 * @since  2.2.0
256
	 * @access public
257
	 *
258
	 * @param int    $id
259
	 * @param string $comment_type
260
	 * @param array  $comment_args
261
	 * @param string $search
262
	 *
263
	 * @return array
264
	 */
265
	public static function get( $id, $comment_type, $comment_args = array(), $search = '' ) {
266
		$comments = array();
267
268
		if( give_has_upgrade_completed('v230_move_donor_note' ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
269
			give_doing_it_wrong( __FUNCTION__, 'You can use Give()->comment->db or Give()->comment->db_meta to get note/comment data from new table.', '2.3.0' );
270
		}
271
272
		// Set default meta_query value.
273
		if ( ! isset( $comment_args['meta_query'] ) ) {
274
			$comment_args['meta_query'] = array();
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
275
		}
276
277
		// Bailout
278
		if ( empty( $id ) || empty( $comment_type ) ) {
279
			return $comments;
280
		}
281
282
		remove_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10 );
283
		remove_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10 );
284
285
		switch ( $comment_type ) {
286 View Code Duplication
			case 'payment':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
287
				$comment_args['meta_query'] = ! empty( $comment_args['meta_query'] )
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
288
					? $comment_args['meta_query']
289
					: array(
290
						array(
291
							'key'     => '_give_donor_id',
292
							'compare' => 'NOT EXISTS'
293
						)
294
					);
295
296
				$comments = get_comments( wp_parse_args(
297
					$comment_args,
298
					array(
299
						'post_id' => $id,
300
						'order'   => 'ASC',
301
						'search'  => $search,
302
						'type'    => 'give_payment_note'
303
					)
304
				) );
305
				break;
306
307 View Code Duplication
			case 'donor':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
308
				$comment_args['meta_query'] = ! empty( $comment_args['meta_query'] )
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
309
					? $comment_args['meta_query']
310
					: array(
311
						array(
312
							'key'   => "_give_{$comment_type}_id",
313
							'value' => $id
314
						)
315
					);
316
317
				$comments = get_comments( wp_parse_args(
318
					$comment_args,
319
					array(
320
						'order'  => 'ASC',
321
						'search' => $search,
322
						'type'   => 'give_donor_note'
323
					)
324
				) );
325
				break;
326
		}
327
328
		add_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10, 1 );
329
		add_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10, 1 );
330
331
		return $comments;
332
	}
333
334
	/**
335
	 * Exclude comments from showing in Recent
336
	 * Comments widgets
337
	 *
338
	 * @since  2.2.0
339
	 * @access public
340
	 *
341
	 * @param object $query WordPress Comment Query Object.
342
	 *
343
	 * @return void
344
	 */
345
	public function hide_comments( $query ) {
346
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
347
			$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
348
			if ( ! is_array( $types ) ) {
349
				$types = array( $types );
350
			}
351
352
			$types = array_filter( array_merge( $types, $this->comment_types ) );
353
354
			$query->query_vars['type__not_in'] = $types;
355
		}
356
	}
357
358
	/**
359
	 * Exclude notes (comments) from showing in Recent Comments widgets
360
	 *
361
	 * @since  2.2.0
362
	 * @access public
363
	 *
364
	 * @param array $clauses Comment clauses for comment query.
365
	 *
366
	 * @return array $clauses Updated comment clauses.
367
	 */
368
	public function hide_comments_pre_wp_41( $clauses ) {
369
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
370
			foreach ( $this->comment_types as $comment_type ) {
371
				$clauses['where'] .= " AND comment_type != \"{$comment_type}\"";
372
			}
373
		}
374
375
		return $clauses;
376
	}
377
378
	/**
379
	 * Exclude notes (comments) from showing in comment feeds
380
	 *
381
	 * @since  2.2.0
382
	 * @access public
383
	 *
384
	 * @param string $where
385
	 *
386
	 * @return string $where
387
	 */
388
	public function hide_comments_from_feeds( $where ) {
389
		global $wpdb;
390
391
		foreach ( $this->comment_types as $comment_type ) {
392
			$where .= $wpdb->prepare( ' AND comment_type!=%s', $comment_type );
393
		}
394
395
		return $where;
396
	}
397
398
	/**
399
	 * Remove Give Comments from the wp_count_comments function
400
	 *
401
	 * @since  2.2.0
402
	 * @access public
403
	 *
404
	 * @param array $stats   (empty from core filter).
405
	 * @param int   $post_id Post ID.
406
	 *
407
	 * @return array|object Array of comment counts.
408
	 */
409
	public function remove_comments_from_comment_counts( $stats, $post_id ) {
410
		global $wpdb;
411
412
		$post_id = (int) $post_id;
413
414
		if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
415
			return $stats;
416
		}
417
418
		$stats = Give_Cache::get_group( "comments-{$post_id}", 'counts' );
419
420
		// Return result from cache.
421
		if ( ! is_null( $stats ) ) {
422
			return $stats;
423
		}
424
425
		$where = 'WHERE';
426
427
		foreach ( $this->comment_types as $index => $comment_type ) {
428
			$where .= ( $index ? ' AND ' : ' ' ) . "comment_type != \"{$comment_type}\"";
429
		}
430
431
		if ( $post_id > 0 ) {
432
			$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
433
		}
434
435
		$count = $wpdb->get_results(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
436
			"
437
				  SELECT comment_approved, COUNT( * ) AS num_comments
438
				  FROM {$wpdb->comments} {$where}
439
				  GROUP BY comment_approved
440
				  ",
441
			ARRAY_A
442
		);
443
444
		$total    = 0;
445
		$approved = array(
446
			'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
447
			'1'            => 'approved',
448
			'spam'         => 'spam',
449
			'trash'        => 'trash',
450
			'post-trashed' => 'post-trashed',
451
		);
452
453
		foreach ( (array) $count as $row ) {
454
			// Don't count post-trashed toward totals.
455
			if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
456
				$total += $row['num_comments'];
457
			}
458
			if ( isset( $approved[ $row['comment_approved'] ] ) ) {
459
				$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
460
			}
461
		}
462
463
		$stats['total_comments'] = $stats['all'] = $total;
464
		foreach ( $approved as $key ) {
465
			if ( empty( $stats[ $key ] ) ) {
466
				$stats[ $key ] = 0;
467
			}
468
		}
469
470
		$stats = (object) $stats;
471
472
		Give_Cache::set_group( "comments-{$post_id}", $stats, 'counts' );
473
474
		return $stats;
475
	}
476
477
	/**
478
	 * Get donor name
479
	 *
480
	 * @since  2.2.0
481
	 * @access public
482
	 *
483
	 * @param string     $author
484
	 * @param int        $comment_id
485
	 * @param WP_Comment $comment
486
	 *
487
	 * @return mixed
488
	 */
489
	public function __get_comment_author( $author, $comment_id, $comment ) {
0 ignored issues
show
Coding Style introduced by
Method name "Give_Comment::__get_comment_author" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
490
		if ( in_array( $comment->comment_type, $this->comment_types ) ) {
491
			switch ( $comment->comment_type ) {
492
				case 'give_payment_note':
493
					if ( get_comment_meta( $comment_id, '_give_donor_id', true ) ) {
494
						$author = give_get_donor_name_by( $comment->comment_post_ID );
495
					}
496
			}
497
		}
498
499
		return $author;
500
	}
501
502
503
	/**
504
	 * Get comment types
505
	 *
506
	 * @since  2.2.0
507
	 * @access public
508
	 *
509
	 * @param array @comment_types
510
	 *
511
	 * @return array
512
	 */
513
	public static function get_comment_types( $comment_types ) {
514
		$_comment_types = array();
515
		foreach ( $comment_types as $comment_type ) {
516
			$_comment_types[] = "give_{$comment_type}_note";
517
		}
518
519
		return $_comment_types;
520
	}
521
}
522