Completed
Pull Request — master (#1749)
by Devin
06:21
created

pdf-reports.php ➔ give_generate_pdf()   D

Complexity

Conditions 20
Paths 64

Size

Total Lines 171
Code Lines 107

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 20
eloc 107
nc 64
nop 1
dl 0
loc 171
rs 4.7294
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
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 = give_currency_filter( give_format_amount( $min ), '', true ) . ' - ' . give_currency_filter( give_format_amount( $max ), '', true );
124
			} else {
125
				$price = give_currency_filter( give_get_form_price( $form->ID ), '', true );
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 = give_currency_filter( give_get_form_earnings_stats( $form->ID ), '', true );
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
172
        // Fix: Minor Styling Alignment Issue for PDF
173
        if( $categories_enabled && $tags_enabled ) {
174
            $pdf->SetWidths( array( 280 ) );
175
        } elseif( $categories_enabled || $tags_enabled ) {
176
            $pdf->SetWidths( array( 235 ) );
177
        } else {
178
            $pdf->SetWidths( array( 190 ) );
179
        }
180
181
        $title = utf8_decode( __( 'No forms found.', 'give' ) );
182
		$pdf->Row( array( $title ) );
183
	}
184
185
	$pdf->Ln();
186
	$pdf->SetTextColor( 50, 50, 50 );
187
	$pdf->SetFont( 'Helvetica', '', 14 );
188
	$pdf->Cell( 0, 10, utf8_decode( __( 'Graph View', 'give' ) ), 0, 2, 'L', false );
189
	$pdf->SetFont( 'Helvetica', '', 12 );
190
191
	$image = html_entity_decode( urldecode( give_draw_chart_image() ) );
192
	$image = str_replace( ' ', '%20', $image );
193
194
	$pdf->SetX( 25 );
195
	$pdf->Image( $image . '&file=.png' );
196
	$pdf->Ln( 7 );
197
	$pdf->Output( apply_filters( 'give_sales_earnings_pdf_export_filename', 'give-report-' . date_i18n( 'Y-m-d' ) ) . '.pdf', 'D' );
198
}
199
200
add_action( 'give_generate_pdf', 'give_generate_pdf' );
201
202
/**
203
 * Draws Chart for PDF Report.
204
 *
205
 * Draws the sales and earnings chart for the PDF report and then retrieves the
206
 * URL of that chart to display on the PDF Report.
207
 *
208
 * @since  1.1.4.0
209
 * @uses   GoogleChart
210
 * @uses   GoogleChartData
211
 * @uses   GoogleChartShapeMarker
212
 * @uses   GoogleChartTextMarker
213
 * @uses   GoogleChartAxis
214
 * @return string $chart->getUrl() URL for the Google Chart
215
 */
216
function give_draw_chart_image() {
217
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/GoogleChart.php';
218
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartShapeMarker.php';
219
	require_once GIVE_PLUGIN_DIR . '/includes/libraries/googlechartlib/markers/GoogleChartTextMarker.php';
220
221
	$chart = new GoogleChart( 'lc', 900, 330 );
222
223
	$i        = 1;
224
	$earnings = "";
225
	$sales    = "";
226
227
	while ( $i <= 12 ) :
228
		$earnings .= give_get_earnings_by_date( null, $i, date( 'Y' ) ) . ",";
229
		$sales .= give_get_sales_by_date( null, $i, date( 'Y' ) ) . ",";
230
		$i ++;
231
	endwhile;
232
233
	$earnings_array = explode( ",", $earnings );
234
	$sales_array    = explode( ",", $sales );
235
236
	$i = 0;
237
	while ( $i <= 11 ) {
238
		if ( empty( $sales_array[ $i ] ) ) {
239
			$sales_array[ $i ] = 0;
240
		}
241
		$i ++;
242
	}
243
244
	$min_earnings   = 0;
245
	$max_earnings   = max( $earnings_array );
246
	$earnings_scale = round( $max_earnings, - 1 );
247
248
	$data = new GoogleChartData( array(
249
		$earnings_array[0],
250
		$earnings_array[1],
251
		$earnings_array[2],
252
		$earnings_array[3],
253
		$earnings_array[4],
254
		$earnings_array[5],
255
		$earnings_array[6],
256
		$earnings_array[7],
257
		$earnings_array[8],
258
		$earnings_array[9],
259
		$earnings_array[10],
260
		$earnings_array[11]
261
	) );
262
263
	$data->setLegend( __( 'Income', 'give' ) );
264
	$data->setColor( '1b58a3' );
265
	$chart->addData( $data );
266
267
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
268
	$shape_marker->setColor( '000000' );
269
	$shape_marker->setSize( 7 );
270
	$shape_marker->setBorder( 2 );
271
	$shape_marker->setData( $data );
272
	$chart->addMarker( $shape_marker );
273
274
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
275
	$value_marker->setColor( '000000' );
276
	$value_marker->setData( $data );
277
	$chart->addMarker( $value_marker );
278
279
	$data = new GoogleChartData( array(
280
		$sales_array[0],
281
		$sales_array[1],
282
		$sales_array[2],
283
		$sales_array[3],
284
		$sales_array[4],
285
		$sales_array[5],
286
		$sales_array[6],
287
		$sales_array[7],
288
		$sales_array[8],
289
		$sales_array[9],
290
		$sales_array[10],
291
		$sales_array[11]
292
	) );
293
	$data->setLegend( __( 'Donations', 'give' ) );
294
	$data->setColor( 'ff6c1c' );
295
	$chart->addData( $data );
296
297
	$chart->setTitle( __( 'Donations by Month for all Give Forms', 'give' ), '336699', 18 );
298
299
	$chart->setScale( 0, $max_earnings );
300
301
	$y_axis = new GoogleChartAxis( 'y' );
302
	$y_axis->setDrawTickMarks( true )->setLabels( array( 0, $max_earnings ) );
303
	$chart->addAxis( $y_axis );
304
305
	$x_axis = new GoogleChartAxis( 'x' );
306
	$x_axis->setTickMarks( 5 );
307
	$x_axis->setLabels( array(
308
		__( 'Jan', 'give' ),
309
		__( 'Feb', 'give' ),
310
		__( 'Mar', 'give' ),
311
		__( 'Apr', 'give' ),
312
		__( 'May', 'give' ),
313
		__( 'June', 'give' ),
314
		__( 'July', 'give' ),
315
		__( 'Aug', 'give' ),
316
		__( 'Sept', 'give' ),
317
		__( 'Oct', 'give' ),
318
		__( 'Nov', 'give' ),
319
		__( 'Dec', 'give' )
320
	) );
321
	$chart->addAxis( $x_axis );
322
323
	$shape_marker = new GoogleChartShapeMarker( GoogleChartShapeMarker::CIRCLE );
324
	$shape_marker->setSize( 6 );
325
	$shape_marker->setBorder( 2 );
326
	$shape_marker->setData( $data );
327
	$chart->addMarker( $shape_marker );
328
329
	$value_marker = new GoogleChartTextMarker( GoogleChartTextMarker::VALUE );
330
	$value_marker->setData( $data );
331
	$chart->addMarker( $value_marker );
332
333
	return $chart->getUrl();
334
}
335