Completed
Pull Request — master (#986)
by Rami
20:36
created

Give_Donors_Gravatars::validate_gravatar()   C

Complexity

Conditions 12
Paths 43

Size

Total Lines 49
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 34
nc 43
nop 1
dl 0
loc 49
rs 5.1474
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 24 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Donors Gravatars
4
 *
5
 * @package     Give
6
 * @subpackage  Classes/Give_Donors_Gravatars
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Give_Donors_Gravatars Class
19
 *
20
 * This class handles donors gravatars.
21
 *
22
 * @since 1.0
23
 */
24
class Give_Donors_Gravatars {
25
26
	/**
27
	 * Class Constructor
28
	 *
29
	 * Set up the Give Donors Gravatars Class.
30
	 *
31
	 * @since  1.0
32
	 * @access public
33
	 *
34
	 * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
35
	 */
36
	public function __construct() {
37
		$this->setup_actions();
0 ignored issues
show
Unused Code introduced by
The call to the method Give_Donors_Gravatars::setup_actions() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
38
	}
39
40
	/**
41
	 * Setup the default hooks and actions
42
	 *
43
	 * @since  1.0
44
	 * @access private
45
	 *
46
	 * @return void
47
	 */
48
	private function setup_actions() {
49
		//		add_action( 'widgets_init', array( $this, 'register_widget' ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
50
		//		add_shortcode( 'give_donors_gravatars', array( $this, 'shortcode' ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
51
		//		add_filter( 'give_settings_display', array( $this, 'settings' ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
52
		//		do_action( 'give_donors_gravatars_setup_actions' );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
53
	}
54
55
	/**
56
	 * Utility function to check if a gravatar exists for a given email or id
57
	 *
58
	 * @see: https://gist.github.com/justinph/5197810
59
	 *
60
	 * @since  1.0
61
	 * @access public
62
	 *
63
	 * @param  int|string|object $id_or_email A user ID, email address, or comment object
64
	 *
65
	 * @return bool If the gravatar exists or not
66
	 */
67
	public function validate_gravatar( $id_or_email ) {
68
		//id or email code borrowed from wp-includes/pluggable.php
69
		$email = '';
70
		if ( is_numeric( $id_or_email ) ) {
71
			$id   = (int) $id_or_email;
72
			$user = get_userdata( $id );
73
			if ( $user ) {
74
				$email = $user->user_email;
75
			}
76
		} elseif ( is_object( $id_or_email ) ) {
77
			// No avatar for pingbacks or trackbacks
78
			$allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
79
			if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) {
80
				return false;
81
			}
82
83
			if ( ! empty( $id_or_email->user_id ) ) {
84
				$id   = (int) $id_or_email->user_id;
85
				$user = get_userdata( $id );
86
				if ( $user ) {
87
					$email = $user->user_email;
88
				}
89
			} elseif ( ! empty( $id_or_email->comment_author_email ) ) {
90
				$email = $id_or_email->comment_author_email;
91
			}
92
		} else {
93
			$email = $id_or_email;
94
		}
95
96
		$hashkey = md5( strtolower( trim( $email ) ) );
97
		$uri     = 'http://www.gravatar.com/avatar/' . $hashkey . '?d=404';
98
99
		$data = wp_cache_get( $hashkey );
100
		if ( false === $data ) {
101
			$response = wp_remote_head( $uri );
102
			if ( is_wp_error( $response ) ) {
103
				$data = 'not200';
104
			} else {
105
				$data = $response['response']['code'];
106
			}
107
			wp_cache_set( $hashkey, $data, $group = '', $expire = 60 * 5 );
108
109
		}
110
		if ( $data == '200' ) {
111
			return true;
112
		} else {
113
			return false;
114
		}
115
	}
116
117
	/**
118
	 * Get an array of all the log IDs using the Give Logging Class
119
	 *
120
	 * @since  1.0
121
	 * @access public
122
	 *
123
	 * @param  int $form_id Donation form id
124
	 *
125
	 * @return array        IDs if logs, false otherwise
126
	 */
127
	public function get_log_ids( $form_id = '' ) {
128
129
		// get Give_Logging class
130
		global $give_logs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
131
132
		// get log for this form
133
		$logs = $give_logs->get_logs( $form_id );
134
135
		if ( $logs ) {
136
			// make an array with all the donor IDs
137
			foreach ( $logs as $log ) {
138
				$log_ids[] = $log->ID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$log_ids was never initialized. Although not strictly required by PHP, it is generally a good practice to add $log_ids = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
139
			}
140
141
			return $log_ids;
0 ignored issues
show
Bug introduced by
The variable $log_ids does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
142
		}
143
144
		return null;
145
146
	}
147
148
	/**
149
	 * Get payment ID
150
	 *
151
	 * @since  1.0
152
	 * @access public
153
	 *
154
	 * @param  int $form_id Donation form id
155
	 *
156
	 * @return mixed
157
	 */
158
	public function get_payment_ids( $form_id = '' ) {
159
160
		global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
161
162
		$log_ids = $this->get_log_ids( $form_id );
163
164
		if ( $log_ids ) {
165
166
			$payment_ids = array();
167
168
			foreach ( $log_ids as $id ) {
169
				// get the payment ID for each corresponding log ID
170
				$payment_ids[] = get_post_meta( $id, '_give_log_payment_id', true );
171
			}
172
173
			// remove donors who have donated more than once so we can have unique avatars
174
			$unique_emails = array();
175
176
			foreach ( $payment_ids as $key => $id ) {
177
178
				$email = get_post_meta( $id, '_give_payment_user_email', true );
179
180
				if ( isset ( $give_options['give_donors_gravatars_has_gravatar_account'] ) ) {
181
					if ( ! $this->validate_gravatar( $email ) ) {
182
						continue;
183
					}
184
				}
185
186
				$unique_emails[ $id ] = get_post_meta( $id, '_give_payment_user_email', true );
187
188
			}
189
190
			// strip duplicate emails
191
			$unique_emails = array_unique( $unique_emails );
192
193
			// convert the unique IDs back into simple array
194
			foreach ( $unique_emails as $id => $email ) {
195
				$unique_ids[] = $id;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$unique_ids was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unique_ids = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
196
			}
197
198
			// randomize the payment IDs if enabled
199
			if ( isset( $give_options['give_donors_gravatars_random_gravatars'] ) ) {
200
				shuffle( $unique_ids );
201
			}
202
203
			// return our unique IDs
204
			return $unique_ids;
0 ignored issues
show
Bug introduced by
The variable $unique_ids does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
205
206
		}
207
208
	}
209
210
	/**
211
	 * Gravatars
212
	 *
213
	 * @since  1.0
214
	 * @access public
215
	 *
216
	 * @param  int    $form_id Donation form id.
217
	 * @param  string $title   Donors gravatars title.
218
	 *
219
	 * @return string
220
	 */
221
	public function gravatars( $form_id = false, $title = '' ) {
222
223
		// unique $payment_ids 
224
		$payment_ids = $this->get_payment_ids( $form_id );
225
226
		global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
227
228
		// return if no ID
229
		if ( ! $form_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $form_id of type false|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
230
			return;
231
		}
232
233
		// minimum amount of donations before showing gravatars
234
		// if the number of items in array is not greater or equal to the number specified, then exit
235
		if ( isset( $give_options['give_donors_gravatars_min_purchases_required'] ) && '' != $give_options['give_donors_gravatars_min_purchases_required'] ) {
236
			if ( ! ( count( $payment_ids ) >= $give_options['give_donors_gravatars_min_purchases_required'] ) ) {
237
				return;
238
			}
239
		}
240
241
		ob_start();
242
243
		$output = '';
244
		echo '<div id="give-purchase-gravatars">';
245
246
247
		if ( isset ( $title ) ) {
248
249
			if ( $title ) {
250
				echo apply_filters( 'give_donors_gravatars_title', '<h3 class="give-gravatars-title">' . esc_attr( $title ) . '</h3>' );
251
			} elseif ( isset( $give_options['give_donors_gravatars_heading'] ) ) {
252
				echo apply_filters( 'give_donors_gravatars_title', '<h3 class="give-gravatars-title">' . esc_attr( $give_options['give_donors_gravatars_heading'] ) . '</h2>' );
253
			}
254
255
		}
256
		echo '<ul class="give-purchase-gravatars-list">';
257
		$i = 0;
258
259
		if ( $payment_ids ) {
260
			foreach ( $payment_ids as $id ) {
261
262
				// Give saves a blank option even when the control is turned off, hence the extra check
263
				if ( isset( $give_options['give_donors_gravatars_maximum_number'] ) && '' != $give_options['give_donors_gravatars_maximum_number'] && $i == $give_options['give_donors_gravatars_maximum_number'] ) {
264
					continue;
265
				}
266
267
				// get the payment meta
268
				$payment_meta = get_post_meta( $id, '_give_payment_meta', true );
269
270
				// unserialize the payment meta
271
				$user_info = maybe_unserialize( $payment_meta['user_info'] );
272
273
				// get donor's first name
274
				$name = $user_info['first_name'];
275
276
				// get donor's email
277
				$email = get_post_meta( $id, '_give_payment_user_email', true );
278
279
				// set gravatar size and provide filter
280
				$size = isset( $give_options['give_donors_gravatars_gravatar_size'] ) ? apply_filters( 'give_donors_gravatars_gravatar_size', $give_options['give_donors_gravatars_gravatar_size'] ) : '';
281
282
				// default image
283
				$default_image = apply_filters( 'give_donors_gravatars_gravatar_default_image', false );
284
285
				// assemble output
286
				$output .= '<li>';
287
288
				$output .= get_avatar( $email, $size, $default_image, $name );
289
				$output .= '</li>';
290
291
				$i ++;
292
293
			} // end foreach
294
		}
295
296
		echo $output;
297
		echo '</ul>';
298
		echo '</div>';
299
300
		return apply_filters( 'give_donors_gravatars', ob_get_clean() );
301
	}
302
303
	/**
304
	 * Register widget
305
	 *
306
	 * @since  1.0
307
	 * @access public
308
	 *
309
	 * @return void
310
	 */
311
	public function register_widget() {
312
		register_widget( 'Give_Donors_Gravatars_Widget' );
313
	}
314
315
	/**
316
	 * Shortcode
317
	 *
318
	 * @since  1.0
319
	 * @access public
320
	 *
321
	 * @param  array  $atts    Shortcode attribures.
322
	 * @param  string $content Shortcode content.
323
	 *
324
	 * @return string
325
	 *
326
	 * @todo   Set the ID to get_the_ID() if ID parameter is not passed through. Otherwise it will incorrectly get other gravatars
327
	 */
328
	public function shortcode( $atts, $content = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $content is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
329
330
		$atts = shortcode_atts( array(
331
			'id'    => '',
332
			'title' => ''
333
		), $atts, 'give_donors_gravatars' );
334
335
		// if no ID is passed on single give_forms pages, get the correct ID
336
		if ( is_singular( 'give_forms' ) ) {
337
			$id = get_the_ID();
338
		}
339
340
		$content = $this->gravatars( $atts['id'], $atts['title'] );
341
342
		return $content;
343
344
	}
345
346
	/**
347
	 * Settings
348
	 *
349
	 * @since  1.0
350
	 * @access public
351
	 *
352
	 * @param  array $settings Gravatar settings.
353
	 *
354
	 * @return array           Gravatar settings.
355
	 */
356
	public function settings( $settings ) {
357
358
		$give_gravatar_settings = array(
359
			array(
360
				'name' => esc_html__( 'Donator Gravatars', 'give' ),
361
				'desc' => '<hr>',
362
				'id'   => 'give_title',
363
				'type' => 'give_title'
364
			),
365
			array(
366
				'name' => esc_html__( 'Heading', 'give' ),
367
				'desc' => esc_html__( 'The heading to display above the Gravatars.', 'give' ),
368
				'type' => 'text',
369
				'id'   => 'give_donors_gravatars_heading'
370
			),
371
			array(
372
				'name'    => esc_html__( 'Gravatar Size', 'give' ),
373
				'desc'    => esc_html__( 'The size of each Gravatar in pixels (512px maximum).', 'give' ),
374
				'type'    => 'text_small',
375
				'id'      => 'give_donors_gravatars_gravatar_size',
376
				'default' => '64'
377
			),
378
			array(
379
				'name' => esc_html__( 'Minimum Unique Donations Required', 'give' ),
380
				/* translators: %s: form singular label */
381
				'desc' => sprintf( esc_html__( 'The minimum number of unique donations a %s must have before the Gravatars are shown. Leave blank for no minimum.', 'give' ), strtolower( give_get_forms_label_singular() ) ),
382
				'type' => 'text_small',
383
				'id'   => 'give_donors_gravatars_min_purchases_required',
384
			),
385
			array(
386
				'name'    => esc_html__( 'Maximum Gravatars To Show', 'give' ),
387
				'desc'    => esc_html__( 'The maximum number of gravatars to show. Leave blank for no limit.', 'give' ),
388
				'type'    => 'text',
389
				'id'      => 'give_donors_gravatars_maximum_number',
390
				'default' => '20',
391
			),
392
			array(
393
				'name' => esc_html__( 'Gravatar Visibility', 'give' ),
394
				'desc' => esc_html__( 'Show only donors with a Gravatar account.', 'give' ),
395
				'id'   => 'give_donors_gravatars_has_gravatar_account',
396
				'type' => 'checkbox',
397
			),
398
			array(
399
				'name' => esc_html__( 'Randomize Gravatars', 'give' ),
400
				'desc' => esc_html__( 'Randomize the Gravatars.', 'give' ),
401
				'id'   => 'give_donors_gravatars_random_gravatars',
402
				'type' => 'checkbox',
403
			),
404
		);
405
406
		return array_merge( $settings, $give_gravatar_settings );
407
	}
408
409
}
410
411
412
/**
413
 * Give_Donors_Gravatars_Widget Class
414
 *
415
 * This class handles donors gravatars
416
 *
417
 * @since 1.0
418
 */
419
class Give_Donors_Gravatars_Widget extends WP_Widget {
420
421
	/**
422
	 * Widget constructor
423
	 *
424
	 * @since  1.0
425
	 * @access public
426
	 *
427
	 * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
428
	 */
429
	public function __construct() {
430
431
		$give_label_singular = function_exists( 'give_get_forms_label_singular' ) ? strtolower( give_get_forms_label_singular() ) : null;
432
433
		// widget settings
434
		$widget_ops = array(
435
			'classname'   => 'give-donors-gravatars',
436
			/* translators: 1: form singular label 2: form singular label */
437
			'description' => sprintf( esc_html__( 'Displays gravatars of people who have donated using your your %1$s. Will only show on the single %2$s page.', 'give' ), $give_label_singular, $give_label_singular )
438
		);
439
440
		// widget control settings
441
		$control_ops = array(
442
			'width'   => 250,
443
			'height'  => 350,
444
			'id_base' => 'give_gravatars_widget'
445
		);
446
447
		// create the widget
448
		parent::__construct(
449
			'give_donors_gravatars_widget',
450
			esc_html__( 'Give Donors Gravatars', 'give' ),
451
			$widget_ops,
452
			$control_ops
453
		);
454
455
	}
456
457
	/**
458
	 * Donors gravatars widget content
459
	 *
460
	 * Outputs the content of the widget
461
	 *
462
	 * @since  1.0
463
	 * @access public
464
	 *
465
	 * @param  array $args     Display arguments including 'before_title', 'after_title', 'before_widget', and 'after_widget'.
466
	 * @param  array $instance Settings for the current Links widget instance.
467
	 *
468
	 * @return void
469
	 */
470
	public function widget( $args, $instance ) {
471
		global $give_options;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
472
473
		//@TODO: Don't extract it!!!
474
		extract( $args );
475
476
		if ( ! is_singular( 'give_forms' ) ) {
477
			return;
478
		}
479
480
		// Variables from widget settings
481
		$title = apply_filters( 'widget_title', $instance['title'] );
482
483
		// Used by themes. Opens the widget
484
		echo $before_widget;
485
486
		// Display the widget title
487
		if ( $title ) {
488
			echo $before_title . $title . $after_title;
489
		}
490
491
		$gravatars = new Give_Donors_Gravatars();
492
493
		echo $gravatars->gravatars( get_the_ID(), null ); // remove title
494
495
		// Used by themes. Closes the widget
496
		echo $after_widget;
497
498
	}
499
500
	/**
501
	 * Update donors gravatars
502
	 *
503
	 * Processes widget options to be saved.
504
	 *
505
	 * @since  1.0
506
	 * @access public
507
	 *
508
	 * @param  array $new_instance New settings for this instance as input by the user via WP_Widget::form().
509
	 * @param  array $old_instance Old settings for this instance.
510
	 *
511
	 * @return array Updated settings to save.
512
	 */
513
	public function update( $new_instance, $old_instance ) {
514
515
		$instance = $old_instance;
516
517
		$instance['title'] = strip_tags( $new_instance['title'] );
518
519
		return $instance;
520
521
	}
522
523
	/**
524
	 * Output donors gravatars
525
	 *
526
	 * Displays the actual form on the widget page.
527
	 *
528
	 * @since  1.0
529
	 * @access public
530
	 *
531
	 * @param  array $instance Current settings.
532
	 *
533
	 * @return void
534
	 */
535
	public function form( $instance ) {
536
537
		// Set up some default widget settings.
538
		$defaults = array(
539
			'title' => '',
540
		);
541
542
		$instance = wp_parse_args( (array) $instance, $defaults ); ?>
543
544
		<!-- Title -->
545
		<p>
546
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'give' ) ?></label>
547
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $instance['title']; ?>" />
548
		</p>
549
550
		<?php
551
	}
552
553
}
554