Test Failed
Push — hotfix/add-filter ( 4536ca )
by Ravinder
04:07
created

pdf-reports.php ➔ give_generate_pdf()   F

Complexity

Conditions 21
Paths 256

Size

Total Lines 176
Code Lines 112

Duplication

Lines 6
Ratio 3.41 %

Importance

Changes 0
Metric Value
cc 21
eloc 112
nc 256
nop 1
dl 6
loc 176
rs 3.6155
c 0
b 0
f 0

How to fix   Long Method    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
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 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 View Code Duplication
	if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'give_generate_pdf' ) ) {
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...
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
35
		wp_die( __( 'Nonce verification failed.', 'give' ), __( 'Error', 'give' ), array( 'response' => 403 ) );
36
	}
37
38 View Code Duplication
	if ( ! file_exists( GIVE_PLUGIN_DIR . '/includes/libraries/give-pdf.php' ) ) {
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...
39
		wp_die( __( 'Dependency missing.', 'give' ), __( 'Error', 'give' ), array( 'response' => 403 ) );
40
	}
41
42
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/give-pdf.php';
43
44
	$daterange = utf8_decode(
45
		sprintf(
46
		/* translators: 1: start date 2: end date */
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 8.
Loading history...
47
			__( '%1$s to %2$s', 'give' ),
48
			date_i18n( give_date_format(), mktime( 0, 0, 0, 1, 1, date( 'Y' ) ) ),
49
			date_i18n( give_date_format() )
50
		)
51
	);
52
53
	$categories_enabled = give_is_setting_enabled( give_get_option( 'categories', 'disabled' ) );
54
	$tags_enabled       = give_is_setting_enabled( give_get_option( 'tags', 'disabled' ) );
55
56
	$pdf          = new Give_PDF( 'L', 'mm', 'A', true, 'UTF-8', false );
57
	$default_font = apply_filters( 'give_pdf_default_font', 'Helvetica' );
58
	$custom_font  = 'dejavusans';
59
	$font_style   = '';
60
61
	if ( file_exists( GIVE_PLUGIN_DIR . '/includes/libraries/tcpdf/fonts/CODE2000.TTF' ) &&
62
	     in_array( give_get_currency(), array( 'RIAL', 'RUB' ) ) ) {
63
		TCPDF_FONTS::addTTFfont( GIVE_PLUGIN_DIR . '/includes/libraries/tcpdf/fonts/CODE2000.TTF', '' );
64
		$custom_font = 'CODE2000';
65
		$font_style  = 'B';
66
	}
67
68
	$pdf->AddPage( 'L', 'A4' );
69
	$pdf->setImageScale( 1.5 );
70
	$pdf->SetTitle( utf8_decode( __( 'Donation report for the current year for all forms', 'give' ) ) );
71
	$pdf->SetAuthor( utf8_decode( __( 'Give - Democratizing Generosity', 'give' ) ) );
72
	$pdf->SetCreator( utf8_decode( __( 'Give - Democratizing Generosity', 'give' ) ) );
73
74
	$pdf->Image( apply_filters( 'give_pdf_export_logo', GIVE_PLUGIN_URL . 'assets/images/give-logo-small.png' ), 247, 8 );
75
76
	$pdf->SetMargins( 8, 8, 8 );
77
	$pdf->SetX( 8 );
78
79
	$pdf->SetFont( $default_font, '', 16 );
80
	$pdf->SetTextColor( 50, 50, 50 );
81
	$pdf->Cell( 0, 3, utf8_decode( __( 'Donation report for the current year for all forms', 'give' ) ), 0, 2, 'L', false );
82
83
	$pdf->SetFont( $default_font, '', 13 );
84
	$pdf->SetTextColor( 150, 150, 150 );
85
	$pdf->Ln( 1 );
86
	$pdf->Cell( 0, 6, utf8_decode( __( 'Date Range: ', 'give' ) ) . $daterange, 0, 2, 'L', false );
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$daterange'
Loading history...
87
	$pdf->Ln();
88
	$pdf->SetTextColor( 50, 50, 50 );
89
	$pdf->SetFont( $default_font, '', 14 );
90
	$pdf->Cell( 0, 10, utf8_decode( __( 'Table View', 'give' ) ), 0, 2, 'L', false );
91
	$pdf->SetFont( $default_font, '', 12 );
92
93
	$pdf->SetFillColor( 238, 238, 238 );
94
	$pdf->SetTextColor( 0, 0, 0, 100 ); // Set Black color.
95
	$pdf->Cell( 50, 6, utf8_decode( __( 'Form Name', 'give' ) ), 1, 0, 'L', true );
96
	$pdf->Cell( 50, 6, utf8_decode( __( 'Price', 'give' ) ), 1, 0, 'L', true );
97
98
	// Display Categories Heading only, if user has opted for it.
99
	if ( $categories_enabled ) {
100
		$pdf->Cell( 45, 6, utf8_decode( __( 'Categories', 'give' ) ), 1, 0, 'L', true );
101
	}
102
103
	// Display Tags Heading only, if user has opted for it.
104
	if ( $tags_enabled ) {
105
		$pdf->Cell( 45, 6, utf8_decode( __( 'Tags', 'give' ) ), 1, 0, 'L', true );
106
	}
107
108
	$pdf->Cell( 45, 6, utf8_decode( __( 'Number of Donations', 'give' ) ), 1, 0, 'L', true );
109
	$pdf->Cell( 45, 6, utf8_decode( __( 'Income to Date', 'give' ) ), 1, 1, 'L', true );
110
111
	// Set Custom Font to support various currencies.
112
	$pdf->SetFont( apply_filters( 'give_pdf_custom_font', $custom_font ), $font_style, 12 );
113
114
	$year       = date( 'Y' );
115
	$give_forms = get_posts( array(
116
		'post_type'      => 'give_forms',
117
		'year'           => $year,
118
		'posts_per_page' => - 1,
119
		'supply_filter'  => false,
120
	) );
121
122
	if ( $give_forms ) {
123
		$pdf->SetWidths( array( 50, 50, 45, 45, 45, 45 ) );
124
125
		foreach ( $give_forms as $form ):
126
			$pdf->SetFillColor( 255, 255, 255 );
127
128
			$title = $form->post_title;
129
130
			if ( give_has_variable_prices( $form->ID ) ) {
131
				$price = html_entity_decode( give_price_range( $form->ID, false ) );
132
			} else {
133
				$price = give_currency_filter( give_get_form_price( $form->ID ), '', true );
134
			}
135
136
			// Display Categories Data only, if user has opted for it.
137
			$categories = array();
138
			if ( $categories_enabled ) {
139
				$categories = get_the_term_list( $form->ID, 'give_forms_category', '', ', ', '' );
140
				$categories = ! is_wp_error( $categories ) ? strip_tags( $categories ) : '';
141
			}
142
143
			// Display Tags Data only, if user has opted for it.
144
			$tags = array();
145
			if ( $tags_enabled ) {
146
				$tags = get_the_term_list( $form->ID, 'give_forms_tag', '', ', ', '' );
147
				$tags = ! is_wp_error( $tags ) ? strip_tags( $tags ) : '';
148
			}
149
150
			$sales    = give_get_form_sales_stats( $form->ID );
151
			$earnings = give_currency_filter( give_format_amount( give_get_form_earnings_stats( $form->ID ), array( 'sanitize' => false, ) ), '', true );
152
153
			// This will help filter data before appending it to PDF Receipt.
154
			$prepare_pdf_data   = array();
155
			$prepare_pdf_data[] = $title;
156
			$prepare_pdf_data[] = $price;
157
158
			// Append Categories Data only, if user has opted for it.
159
			if ( $categories_enabled ) {
160
				$prepare_pdf_data[] = $categories;
161
			}
162
163
			// Append Tags Data only, if user has opted for it.
164
			if ( $tags_enabled ) {
165
				$prepare_pdf_data[] = $tags;
166
			}
167
168
			$prepare_pdf_data[] = $sales;
169
			$prepare_pdf_data[] = $earnings;
170
171
			$pdf->Row( $prepare_pdf_data );
172
173
		endforeach;
174
	} else {
175
176
		// Fix: Minor Styling Alignment Issue for PDF.
177
		if ( $categories_enabled && $tags_enabled ) {
178
			$no_found_width = 280;
179
		} elseif ( $categories_enabled || $tags_enabled ) {
180
			$no_found_width = 235;
181
		} else {
182
			$no_found_width = 190;
183
		}
184
		$title = utf8_decode( __( 'No forms found.', 'give' ) );
185
		$pdf->MultiCell( $no_found_width, 5, $title, 1, 'C', false, 1, '', '', true, 0, false, true, 0, 'T', false );
186
	}// End if().
187
	$pdf->Ln();
188
	$pdf->SetTextColor( 50, 50, 50 );
189
	$pdf->SetFont( $default_font, '', 14 );
190
191
	// Output Graph on a new page.
192
	$pdf->AddPage( 'L', 'A4' );
193
	$pdf->Cell( 0, 10, utf8_decode( __( 'Graph View', 'give' ) ), 0, 2, 'L', false );
194
	$pdf->SetFont( $default_font, '', 12 );
195
196
	$image = html_entity_decode( urldecode( give_draw_chart_image() ) );
197
	$image = str_replace( ' ', '%20', $image );
198
199
	$pdf->SetX( 25 );
200
	$pdf->Image( $image . '&file=.png' );
201
	$pdf->Ln( 7 );
202
	$pdf->Output( apply_filters( 'give_sales_earnings_pdf_export_filename', 'give-report-' . date_i18n( 'Y-m-d' ) ) . '.pdf', 'D' );
203
}
204
205
add_action( 'give_generate_pdf', 'give_generate_pdf' );
206
207
/**
208
 * Draws Chart for PDF Report.
209
 *
210
 * Draws the sales and earnings chart for the PDF report and then retrieves the
211
 * URL of that chart to display on the PDF Report.
212
 *
213
 * @since  1.1.4.0
214
 * @uses   GoogleChart
215
 * @uses   GoogleChartData
216
 * @uses   GoogleChartShapeMarker
217
 * @uses   GoogleChartTextMarker
218
 * @uses   GoogleChartAxis
219
 * @return string $chart->getUrl() URL for the Google Chart
220
 */
221
function give_draw_chart_image() {
222
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/GoogleChart.php';
223
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartShapeMarker.php';
224
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartTextMarker.php';
225
226
	$chart = new GoogleChart( 'lc', 900, 330 );
227
228
	$i        = 1;
229
	$earnings = "";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
230
	$sales    = "";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
231
232
	while ( $i <= 12 ) :
233
		$earnings .= give_get_earnings_by_date( null, $i, date( 'Y' ) ) . ",";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal , does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
234
		$sales    .= give_get_sales_by_date( null, $i, date( 'Y' ) ) . ",";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal , does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
235
		$i ++;
236
	endwhile;
237
238
	$earnings_array = explode( ",", $earnings );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal , does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
239
	$sales_array    = explode( ",", $sales );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal , does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
240
241
	$i = 0;
242
	while ( $i <= 11 ) {
243
		if ( empty( $sales_array[ $i ] ) ) {
244
			$sales_array[ $i ] = 0;
245
		}
246
		$i ++;
247
	}
248
249
	$min_earnings   = 0;
0 ignored issues
show
Unused Code introduced by
$min_earnings is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
250
	$max_earnings   = max( $earnings_array );
251
	$earnings_scale = round( $max_earnings, - 1 );
0 ignored issues
show
Unused Code introduced by
$earnings_scale is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
252
253
	$data = new GoogleChartData( array(
254
		$earnings_array[0],
255
		$earnings_array[1],
256
		$earnings_array[2],
257
		$earnings_array[3],
258
		$earnings_array[4],
259
		$earnings_array[5],
260
		$earnings_array[6],
261
		$earnings_array[7],
262
		$earnings_array[8],
263
		$earnings_array[9],
264
		$earnings_array[10],
265
		$earnings_array[11],
266
	) );
267
268
	$data->setLegend( __( 'Income', 'give' ) );
269
	$data->setColor( '1b58a3' );
270
	$chart->addData( $data );
271
272
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
273
	$shape_marker->setColor( '000000' );
274
	$shape_marker->setSize( 7 );
275
	$shape_marker->setBorder( 2 );
276
	$shape_marker->setData( $data );
277
	$chart->addMarker( $shape_marker );
278
279
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
280
	$value_marker->setColor( '000000' );
281
	$value_marker->setData( $data );
282
	$chart->addMarker( $value_marker );
283
284
	$data = new GoogleChartData( array(
285
		$sales_array[0],
286
		$sales_array[1],
287
		$sales_array[2],
288
		$sales_array[3],
289
		$sales_array[4],
290
		$sales_array[5],
291
		$sales_array[6],
292
		$sales_array[7],
293
		$sales_array[8],
294
		$sales_array[9],
295
		$sales_array[10],
296
		$sales_array[11],
297
	) );
298
	$data->setLegend( __( 'Donations', 'give' ) );
299
	$data->setColor( 'ff6c1c' );
300
	$chart->addData( $data );
301
302
	$chart->setTitle( __( 'Donations by Month for all Give Forms', 'give' ), '336699', 18 );
303
304
	$chart->setScale( 0, $max_earnings );
305
306
	$y_axis = new GoogleChartAxis( 'y' );
307
	$y_axis->setDrawTickMarks( true )->setLabels( array( 0, $max_earnings ) );
308
	$chart->addAxis( $y_axis );
309
310
	$x_axis = new GoogleChartAxis( 'x' );
311
	$x_axis->setTickMarks( 5 );
312
	$x_axis->setLabels( array(
313
		__( 'Jan', 'give' ),
314
		__( 'Feb', 'give' ),
315
		__( 'Mar', 'give' ),
316
		__( 'Apr', 'give' ),
317
		__( 'May', 'give' ),
318
		__( 'June', 'give' ),
319
		__( 'July', 'give' ),
320
		__( 'Aug', 'give' ),
321
		__( 'Sept', 'give' ),
322
		__( 'Oct', 'give' ),
323
		__( 'Nov', 'give' ),
324
		__( 'Dec', 'give' ),
325
	) );
326
	$chart->addAxis( $x_axis );
327
328
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
329
	$shape_marker->setSize( 6 );
330
	$shape_marker->setBorder( 2 );
331
	$shape_marker->setData( $data );
332
	$chart->addMarker( $shape_marker );
333
334
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
335
	$value_marker->setData( $data );
336
	$chart->addMarker( $value_marker );
337
338
	return $chart->getUrl();
339
}
340