Completed
Pull Request — master (#1731)
by Ravinder
17:37
created

pdf-reports.php ➔ give_draw_chart_image()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 119
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 95
nc 6
nop 0
dl 0
loc 119
rs 8.1935
c 0
b 0
f 0

How to fix   Long Method   

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 28 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
 * PDF Report Generation Functions.
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Reports
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly..
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Generate PDF Reports.
19
 *
20
 * Generates PDF report on donations and income for all forms for the current year.
21
 *
22
 * @since  1.0
23
 *
24
 * @param string $data
25
 *
26
 * @uses   give_pdf
27
 */
28
function give_generate_pdf( $data ) {
29
30
	if ( ! current_user_can( 'view_give_reports' ) ) {
31
		wp_die( __( 'You do not have permission to generate PDF sales reports.', 'give' ), __( 'Error', 'give' ), array( 'response' => 403 ) );
32
	}
33
34
	if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'give_generate_pdf' ) ) {
35
		wp_die( __( 'Nonce verification failed.', 'give' ), __( 'Error', 'give' ), array( 'response' => 403 ) );
36
	}
37
38
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/fpdf/fpdf.php';
39
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/fpdf/give_pdf.php';
40
41
	$daterange = utf8_decode(
42
		sprintf(
43
		/* translators: 1: start date 2: end date */
44
			__( '%1$s to %2$s', 'give' ),
45
			date_i18n( give_date_format(), mktime( 0, 0, 0, 1, 1, date( 'Y' ) ) ),
46
			date_i18n( give_date_format() )
47
		)
48
	);
49
50
    $categories_enabled = give_is_setting_enabled( give_get_option( 'categories', 'disabled' ) );
51
    $tags_enabled = give_is_setting_enabled( give_get_option( 'tags', 'disabled' ) );
52
53
	$pdf = new give_pdf();
54
	$pdf->AddPage( 'L', 'A4' );
55
56
	$pdf->SetTitle( utf8_decode( __( 'Donation report for the current year for all forms', 'give' ) ) );
57
	$pdf->SetAuthor( utf8_decode( __( 'Give - Democratizing Generosity', 'give' ) ) );
58
	$pdf->SetCreator( utf8_decode( __( 'Give - Democratizing Generosity', 'give' ) ) );
59
60
	$pdf->Image( apply_filters( 'give_pdf_export_logo', GIVE_PLUGIN_URL . 'assets/images/give-logo-small.png' ), 247, 8 );
61
62
	$pdf->SetMargins( 8, 8, 8 );
63
	$pdf->SetX( 8 );
64
65
	$pdf->SetFont( 'Helvetica', '', 16 );
66
	$pdf->SetTextColor( 50, 50, 50 );
67
	$pdf->Cell( 0, 3, utf8_decode( __( 'Donation report for the current year for all forms', 'give' ) ), 0, 2, 'L', false );
68
69
	$pdf->SetFont( 'Helvetica', '', 13 );
70
	$pdf->Ln();
71
	$pdf->SetTextColor( 150, 150, 150 );
72
	$pdf->Cell( 0, 6, utf8_decode( __( 'Date Range: ', 'give' ) ) . $daterange, 0, 2, 'L', false );
73
	$pdf->Ln();
74
	$pdf->SetTextColor( 50, 50, 50 );
75
	$pdf->SetFont( 'Helvetica', '', 14 );
76
	$pdf->Cell( 0, 10, utf8_decode( __( 'Table View', 'give' ) ), 0, 2, 'L', false );
77
	$pdf->SetFont( 'Helvetica', '', 12 );
78
79
	$pdf->SetFillColor( 238, 238, 238 );
80
	$pdf->Cell( 70, 6, utf8_decode( __( 'Form Name', 'give' ) ), 1, 0, 'L', true );
81
	$pdf->Cell( 30, 6, utf8_decode( __( 'Price', 'give' ) ), 1, 0, 'L', true );
82
83
    // Display Categories Heading only, if user has opted for it.
84
    if ( $categories_enabled ) {
85
	   $pdf->Cell( 45, 6, utf8_decode( __( 'Categories', 'give' ) ), 1, 0, 'L', true );
86
    }
87
88
    // Display Tags Heading only, if user has opted for it.
89
    if ( $tags_enabled ) {
90
	   $pdf->Cell( 45, 6, utf8_decode( __( 'Tags', 'give' ) ), 1, 0, 'L', true );
91
    }
92
93
	$pdf->Cell( 45, 6, utf8_decode( __( 'Number of Donations', 'give' ) ), 1, 0, 'L', true );
94
	$pdf->Cell( 45, 6, utf8_decode( __( 'Income to Date', 'give' ) ), 1, 1, 'L', true );
95
96
	$year       = date( 'Y' );
97
	$give_forms = get_posts( array( 'post_type' => 'give_forms', 'year' => $year, 'posts_per_page' => - 1 ) );
98
99
	if ( $give_forms ) {
100
		$pdf->SetWidths( array( 70, 30, 45, 45, 45, 45 ) );
101
102
		foreach ( $give_forms as $form ):
103
			$pdf->SetFillColor( 255, 255, 255 );
104
105
			$title = $form->post_title;
106
107
			if ( give_has_variable_prices( $form->ID ) ) {
108
109
				$prices = give_get_variable_prices( $form->ID );
110
111
				$first = $prices[0]['_give_amount'];
112
				$last  = array_pop( $prices );
113
				$last  = $last['_give_amount'];
114
115
				if ( $first < $last ) {
116
					$min = $first;
117
					$max = $last;
118
				} else {
119
					$min = $last;
120
					$max = $first;
121
				}
122
123
				$price = html_entity_decode( give_currency_filter( give_format_amount( $min ) ) . ' - ' . give_currency_filter( give_format_amount( $max ) ) );
124
			} else {
125
				$price = html_entity_decode( give_currency_filter( give_get_form_price( $form->ID ) ) );
126
			}
127
128
            // Display Categories Data only, if user has opted for it.
129
            if ( $categories_enabled ) {
130
                $categories = get_the_term_list( $form->ID, 'give_forms_category', '', ', ', '' );
131
                $categories = ! is_wp_error( $categories ) ? strip_tags( $categories ) : '';
132
            }
133
134
            // Display Tags Data only, if user has opted for it.
135
            if ( $tags_enabled ) {
136
                $tags = get_the_term_list( $form->ID, 'give_forms_tag', '', ', ', '' );
137
                $tags = ! is_wp_error( $tags ) ? strip_tags( $tags ) : '';
138
            }
139
140
			$sales    = give_get_form_sales_stats( $form->ID );
141
			$link     = get_permalink( $form->ID );
142
			$earnings = html_entity_decode( give_currency_filter( give_get_form_earnings_stats( $form->ID ) ) );
143
144
			if ( function_exists( 'iconv' ) ) {
145
				// Ensure characters like euro; are properly converted.
146
				$price    = iconv( 'UTF-8', 'windows-1252', utf8_encode( $price ) );
147
				$earnings = iconv( 'UTF-8', 'windows-1252', utf8_encode( $earnings ) );
148
			}
149
150
            // This will help filter data before appending it to PDF Receipt.
151
            $prepare_pdf_data = array();
152
            $prepare_pdf_data[] = $title;
153
            $prepare_pdf_data[] = $price;
154
155
            // Append Categories Data only, if user has opted for it.
156
            if ( $categories_enabled ) {
157
                $prepare_pdf_data[] = $categories;
0 ignored issues
show
Bug introduced by
The variable $categories 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...
158
            }
159
160
            // Append Tags Data only, if user has opted for it.
161
            if ( $tags_enabled ) {
162
                $prepare_pdf_data[] = $tags;
0 ignored issues
show
Bug introduced by
The variable $tags 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...
163
            }
164
165
            $prepare_pdf_data[] = $sales;
166
            $prepare_pdf_data[] = $earnings;
167
168
			$pdf->Row( $prepare_pdf_data );
169
		endforeach;
170
	} else {
171
		$pdf->SetWidths( array( 280 ) );
172
		$title = utf8_decode( __( 'No forms found.', 'give' ) );
173
		$pdf->Row( array( $title ) );
174
	}
175
176
	$pdf->Ln();
177
	$pdf->SetTextColor( 50, 50, 50 );
178
	$pdf->SetFont( 'Helvetica', '', 14 );
179
	$pdf->Cell( 0, 10, utf8_decode( __( 'Graph View', 'give' ) ), 0, 2, 'L', false );
180
	$pdf->SetFont( 'Helvetica', '', 12 );
181
182
	$image = html_entity_decode( urldecode( give_draw_chart_image() ) );
183
	$image = str_replace( ' ', '%20', $image );
184
185
	$pdf->SetX( 25 );
186
	$pdf->Image( $image . '&file=.png' );
187
	$pdf->Ln( 7 );
188
	$pdf->Output( apply_filters( 'give_sales_earnings_pdf_export_filename', 'give-report-' . date_i18n( 'Y-m-d' ) ) . '.pdf', 'D' );
189
}
190
191
add_action( 'give_generate_pdf', 'give_generate_pdf' );
192
193
/**
194
 * Draws Chart for PDF Report.
195
 *
196
 * Draws the sales and earnings chart for the PDF report and then retrieves the
197
 * URL of that chart to display on the PDF Report.
198
 *
199
 * @since  1.1.4.0
200
 * @uses   GoogleChart
201
 * @uses   GoogleChartData
202
 * @uses   GoogleChartShapeMarker
203
 * @uses   GoogleChartTextMarker
204
 * @uses   GoogleChartAxis
205
 * @return string $chart->getUrl() URL for the Google Chart
206
 */
207
function give_draw_chart_image() {
208
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/GoogleChart.php';
209
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartShapeMarker.php';
210
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartTextMarker.php';
211
212
	$chart = new GoogleChart( 'lc', 900, 330 );
213
214
	$i        = 1;
215
	$earnings = "";
216
	$sales    = "";
217
218
	while ( $i <= 12 ) :
219
		$earnings .= give_get_earnings_by_date( null, $i, date( 'Y' ) ) . ",";
220
		$sales .= give_get_sales_by_date( null, $i, date( 'Y' ) ) . ",";
221
		$i ++;
222
	endwhile;
223
224
	$earnings_array = explode( ",", $earnings );
225
	$sales_array    = explode( ",", $sales );
226
227
	$i = 0;
228
	while ( $i <= 11 ) {
229
		if ( empty( $sales_array[ $i ] ) ) {
230
			$sales_array[ $i ] = 0;
231
		}
232
		$i ++;
233
	}
234
235
	$min_earnings   = 0;
236
	$max_earnings   = max( $earnings_array );
237
	$earnings_scale = round( $max_earnings, - 1 );
238
239
	$data = new GoogleChartData( array(
240
		$earnings_array[0],
241
		$earnings_array[1],
242
		$earnings_array[2],
243
		$earnings_array[3],
244
		$earnings_array[4],
245
		$earnings_array[5],
246
		$earnings_array[6],
247
		$earnings_array[7],
248
		$earnings_array[8],
249
		$earnings_array[9],
250
		$earnings_array[10],
251
		$earnings_array[11]
252
	) );
253
254
	$data->setLegend( __( 'Income', 'give' ) );
255
	$data->setColor( '1b58a3' );
256
	$chart->addData( $data );
257
258
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
259
	$shape_marker->setColor( '000000' );
260
	$shape_marker->setSize( 7 );
261
	$shape_marker->setBorder( 2 );
262
	$shape_marker->setData( $data );
263
	$chart->addMarker( $shape_marker );
264
265
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
266
	$value_marker->setColor( '000000' );
267
	$value_marker->setData( $data );
268
	$chart->addMarker( $value_marker );
269
270
	$data = new GoogleChartData( array(
271
		$sales_array[0],
272
		$sales_array[1],
273
		$sales_array[2],
274
		$sales_array[3],
275
		$sales_array[4],
276
		$sales_array[5],
277
		$sales_array[6],
278
		$sales_array[7],
279
		$sales_array[8],
280
		$sales_array[9],
281
		$sales_array[10],
282
		$sales_array[11]
283
	) );
284
	$data->setLegend( __( 'Donations', 'give' ) );
285
	$data->setColor( 'ff6c1c' );
286
	$chart->addData( $data );
287
288
	$chart->setTitle( __( 'Donations by Month for all Give Forms', 'give' ), '336699', 18 );
289
290
	$chart->setScale( 0, $max_earnings );
291
292
	$y_axis = new GoogleChartAxis( 'y' );
293
	$y_axis->setDrawTickMarks( true )->setLabels( array( 0, $max_earnings ) );
294
	$chart->addAxis( $y_axis );
295
296
	$x_axis = new GoogleChartAxis( 'x' );
297
	$x_axis->setTickMarks( 5 );
298
	$x_axis->setLabels( array(
299
		__( 'Jan', 'give' ),
300
		__( 'Feb', 'give' ),
301
		__( 'Mar', 'give' ),
302
		__( 'Apr', 'give' ),
303
		__( 'May', 'give' ),
304
		__( 'June', 'give' ),
305
		__( 'July', 'give' ),
306
		__( 'Aug', 'give' ),
307
		__( 'Sept', 'give' ),
308
		__( 'Oct', 'give' ),
309
		__( 'Nov', 'give' ),
310
		__( 'Dec', 'give' )
311
	) );
312
	$chart->addAxis( $x_axis );
313
314
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
315
	$shape_marker->setSize( 6 );
316
	$shape_marker->setBorder( 2 );
317
	$shape_marker->setData( $data );
318
	$chart->addMarker( $shape_marker );
319
320
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
321
	$value_marker->setData( $data );
322
	$chart->addMarker( $value_marker );
323
324
	return $chart->getUrl();
325
}
326