Completed
Pull Request — develop (#34)
by Mario
03:29
created

main_controller::get_donation_content_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 1
Metric Value
c 5
b 2
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
/**
3
 *
4
 * PayPal Donation extension for the phpBB Forum Software package.
5
 *
6
 * @copyright (c) 2015 Skouat
7
 * @license GNU General Public License, version 2 (GPL-2.0)
8
 *
9
 */
10
11
namespace skouat\ppde\controller;
12
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
class main_controller
16
{
17
	protected $auth;
18
	protected $config;
19
	protected $container;
20
	protected $extension_manager;
21
	protected $helper;
22
	protected $ppde_entity_currency;
23
	protected $ppde_entity_donation_pages;
24
	protected $ppde_entity_transactions;
25
	protected $ppde_operator_currency;
26
	protected $ppde_operator_donation_pages;
27
	protected $ppde_operator_transactions;
28
	protected $request;
29
	protected $template;
30
	protected $user;
31
	protected $root_path;
32
	protected $php_ext;
33
	/** @var array */
34
	protected $ext_meta = array();
35
	/** @var string */
36
	protected $ext_name;
37
	/** @var string */
38
	private $donation_body;
39
	/** @var array */
40
	private $donation_content_data;
41
	/** @var string */
42
	private $return_args_url;
43
	/** @var string */
44
	private $u_action;
45
46
	/**
47
	 * Constructor
48
	 *
49
	 * @param \phpbb\auth\auth                      $auth                         Auth object
50
	 * @param \phpbb\config\config                  $config                       Config object
51
	 * @param ContainerInterface                    $container                    Service container interface
52
	 * @param \phpbb\extension\manager              $extension_manager            An instance of the phpBB extension
53
	 *                                                                            manager
54
	 * @param \phpbb\controller\helper              $helper                       Controller helper object
55
	 * @param \skouat\ppde\entity\currency          $ppde_entity_currency         Currency entity object
56
	 * @param \skouat\ppde\entity\donation_pages    $ppde_entity_donation_pages   Donation pages entity object
57
	 * @param \skouat\ppde\entity\transactions      $ppde_entity_transactions     Transactions log entity object
58
	 * @param \skouat\ppde\operators\currency       $ppde_operator_currency       Currency operator object
59
	 * @param \skouat\ppde\operators\donation_pages $ppde_operator_donation_pages Donation pages operator object
60
	 * @param \skouat\ppde\operators\transactions   $ppde_operator_transactions   Transactions log operator object
61
	 * @param \phpbb\request\request                $request                      Request object
62
	 * @param \phpbb\template\template              $template                     Template object
63
	 * @param \phpbb\user                           $user                         User object
64
	 * @param string                                $root_path                    phpBB root path
65
	 * @param string                                $php_ext                      phpEx
66
	 *
67
	 * @return \skouat\ppde\controller\main_controller
68
	 * @access public
69
	 */
70
	public function __construct(\phpbb\auth\auth $auth, \phpbb\config\config $config, ContainerInterface $container, \phpbb\extension\manager $extension_manager, \phpbb\controller\helper $helper, \skouat\ppde\entity\currency $ppde_entity_currency, \skouat\ppde\entity\donation_pages $ppde_entity_donation_pages, \skouat\ppde\entity\transactions $ppde_entity_transactions, \skouat\ppde\operators\currency $ppde_operator_currency, \skouat\ppde\operators\donation_pages $ppde_operator_donation_pages, \skouat\ppde\operators\transactions $ppde_operator_transactions, \phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user, $root_path, $php_ext)
71
	{
72
		$this->auth = $auth;
73
		$this->config = $config;
74
		$this->container = $container;
75
		$this->extension_manager = $extension_manager;
76
		$this->helper = $helper;
77
		$this->ppde_entity_currency = $ppde_entity_currency;
78
		$this->ppde_entity_donation_pages = $ppde_entity_donation_pages;
79
		$this->ppde_entity_transactions = $ppde_entity_transactions;
80
		$this->ppde_operator_currency = $ppde_operator_currency;
81
		$this->ppde_operator_donation_pages = $ppde_operator_donation_pages;
82
		$this->ppde_operator_transactions = $ppde_operator_transactions;
83
		$this->request = $request;
84
		$this->template = $template;
85
		$this->user = $user;
86
		$this->root_path = $root_path;
87
		$this->php_ext = $php_ext;
88
	}
89
90
	public function handle()
91
	{
92
		// When this extension is disabled, redirect users back to the forum index
93
		// Else if user is not allowed to use it, disallow access to the extension main page
94
		if (empty($this->config['ppde_enable']))
95
		{
96
			redirect(append_sid("{$this->root_path}index.{$this->php_ext}"));
97
		}
98
		else if (!$this->can_use_ppde())
99
		{
100
			trigger_error('NOT_AUTHORISED');
101
		}
102
103
		$this->set_return_args_url($this->request->variable('return', 'body'));
104
105
		// Prepare message for display
106
		if ($this->get_donation_content_data($this->return_args_url))
107
		{
108
			$this->ppde_entity_donation_pages->get_vars();
109
			$this->donation_body = $this->ppde_entity_donation_pages->replace_template_vars($this->ppde_entity_donation_pages->get_message_for_display());
110
		}
111
112
		$this->template->assign_vars(array(
113
			'DEFAULT_CURRENCY'   => $this->build_currency_select_menu($this->config['ppde_default_currency']),
114
			'DONATION_BODY'      => $this->donation_body,
115
			'IMG_LOADER'         => '<img src="' . $this->root_path . '../ext/skouat/ppde/images/loader.gif' . '" />',
116
			'PPDE_DEFAULT_VALUE' => $this->config['ppde_default_value'] ? $this->config['ppde_default_value'] : 0,
117
			'PPDE_LIST_VALUE'    => $this->build_currency_value_select_menu(),
118
119
			'S_HIDDEN_FIELDS'    => $this->paypal_hidden_fields(),
120
			'S_PPDE_FORM_ACTION' => $this->get_paypal_url(),
121
			'S_RETURN_ARGS'      => $this->return_args_url,
122
			'S_SANDBOX'          => $this->use_sandbox(),
123
		));
124
125
		$this->display_stats();
126
127
		// Send all data to the template file
128
		return $this->send_data_to_template();
129
	}
130
131
	public function donorlist_handle()
132
	{
133
		// If the donorlist is not enabled, redirect users back to the forum index
134
		// Else if user is not allowed to view the donors list, disallow access to the extension page
135
		if (!$this->donorlist_is_enabled())
136
		{
137
			redirect(append_sid($this->root_path . 'index.' . $this->php_ext));
138
		}
139
		else if (!$this->can_view_ppde_donorlist())
140
		{
141
			trigger_error('NOT_AUTHORISED');
142
		}
143
144
		// Get needed container
145
		/** @type \phpbb\pagination $pagination */
146
		$pagination = $this->container->get('pagination');
147
		/** @type \phpbb\path_helper $path_helper */
148
		$path_helper = $this->container->get('path_helper');
149
150
		// Set up general vars
151
		$default_key = 'd';
152
		$sort_key = $this->request->variable('sk', $default_key);
153
		$sort_dir = $this->request->variable('sd', 'd');
154
		$start = $this->request->variable('start', 0);
155
156
		// Sorting and order
157
		$sort_key_sql = array('a' => 'amount', 'd' => 'txn.payment_date', 'u' => 'u.username_clean');
158
159
		if (!isset($sort_key_sql[$sort_key]))
160
		{
161
			$sort_key = $default_key;
162
		}
163
164
		$order_by = $sort_key_sql[$sort_key] . ' ' . (($sort_dir == 'a') ? 'ASC' : 'DESC');
165
166
		// Build a relevant pagination_url and sort_url
167
		// We do not use request_var() here directly to save some calls (not all variables are set)
168
		$check_params = array(
169
			'sk'    => array('sk', $default_key),
170
			'sd'    => array('sd', 'a'),
171
			'start' => array('start', 0),
172
		);
173
174
		$params = $this->check_params($check_params, array('start'));
175
		$sort_params = $this->check_params($check_params, array('sk', 'sd'));
176
177
		// Set '$this->u_action'
178
		$use_page = ($this->u_action) ? $this->u_action : $this->user->page['page_name'];
179
		$this->u_action = reapply_sid($path_helper->get_valid_page($use_page, $this->config['enable_mod_rewrite']));
180
181
		$pagination_url = append_sid($this->u_action, implode('&amp;', $params), true, false, true);
182
		$sort_url = $this->set_url_delim(append_sid($this->u_action, implode('&amp;', $sort_params), true, false, true), $sort_params);
183
184
		$get_donorlist_sql_ary = $this->ppde_operator_transactions->get_sql_donorlist_ary(false, $order_by);
185
		$total_donors = $this->ppde_operator_transactions->query_sql_count($get_donorlist_sql_ary, 'txn.user_id');
186
		$start = $pagination->validate_start($start, $this->config['topics_per_page'], $total_donors);
187
188
		$pagination->generate_template_pagination($pagination_url, 'pagination', 'start', $total_donors, $this->config['topics_per_page'], $start);
189
190
		// adds fields to the table schema needed by entity->import()
191
		$additional_table_schema = array(
192
			'item_username'    => array('name' => 'username', 'type' => 'string'),
193
			'item_user_colour' => array('name' => 'user_colour', 'type' => 'string'),
194
			'item_amount'      => array('name' => 'amount', 'type' => 'float'),
195
			'item_max_txn_id'  => array('name' => 'max_txn_id', 'type' => 'integer'),
196
		);
197
198
		$data_ary = $this->ppde_entity_transactions->get_data($this->ppde_operator_transactions->build_sql_donorlist_data($get_donorlist_sql_ary), $additional_table_schema, $this->config['topics_per_page'], $start);
199
200
		// Get default currency data from the database
201
		$default_currency_data = $this->get_default_currency_data($this->config['ppde_default_currency']);
202
		$this->template->assign_vars(array(
203
			'TOTAL_DONORS'    => $this->user->lang('PPDE_DONORS', $total_donors),
204
			'U_SORT_AMOUNT'   => $sort_url . 'sk=a&amp;sd=' . $this->set_sort_key($sort_key, 'a', $sort_dir),
205
			'U_SORT_DONATED'  => $sort_url . 'sk=d&amp;sd=' . $this->set_sort_key($sort_key, 'd', $sort_dir),
206
			'U_SORT_USERNAME' => $sort_url . 'sk=u&amp;sd=' . $this->set_sort_key($sort_key, 'u', $sort_dir),
207
		));
208
209
		foreach ($data_ary as $data)
210
		{
211
			$get_last_transaction_sql_ary = $this->ppde_operator_transactions->get_sql_donorlist_ary($data['max_txn_id']);
212
			$last_donation_data = $this->ppde_entity_transactions->get_data($this->ppde_operator_transactions->build_sql_donorlist_data($get_last_transaction_sql_ary));
213
			$this->template->assign_block_vars('donorrow', array(
214
				'PPDE_DONOR_USERNAME'       => get_username_string('full', $data['user_id'], $data['username'], $data['user_colour']),
215
				'PPDE_LAST_DONATED_AMOUNT'  => $this->currency_on_left(number_format($last_donation_data[0]['mc_gross'], 2), $default_currency_data[0]['currency_symbol'], (bool) $default_currency_data[0]['currency_on_left']),
216
				'PPDE_LAST_PAYMENT_DATE'    => $this->user->format_date($last_donation_data[0]['payment_date']),
217
				'PPDE_TOTAL_DONATED_AMOUNT' => $this->currency_on_left(number_format($data['amount'], 2), $default_currency_data[0]['currency_symbol'], (bool) $default_currency_data[0]['currency_on_left']),
218
			));
219
		}
220
221
		// Set "return_args_url" object before sending data to template
222
		$this->set_return_args_url('donorlist');
223
224
		// Send all data to the template file
225
		return $this->send_data_to_template();
226
	}
227
228
	/**
229
	 * Set the sort key value
230
	 *
231
	 * @param string $sk
232
	 * @param string $sk_comp
233
	 * @param string $sd
234
	 *
235
	 * @return string
236
	 * @access private
237
	 */
238
	private function set_sort_key($sk, $sk_comp, $sd)
239
	{
240
		return ($sk == $sk_comp && $sd == 'a') ? 'd' : 'a';
241
	}
242
243
	/**
244
	 * Simply adds an url or &amp; delimiter to the url when params is empty
245
	 *
246
	 * @param $url
247
	 * @param $params
248
	 *
249
	 * @return string
250
	 * @access private
251
	 */
252
	private function set_url_delim($url, $params)
253
	{
254
		return (empty($params)) ? $url . '?' : $url . '&amp;';
255
	}
256
257
	/**
258
	 * @param array    $params_ary
259
	 * @param string[] $excluded_keys
260
	 *
261
	 * @return array
262
	 * @access private
263
	 */
264
	private function check_params($params_ary, $excluded_keys)
265
	{
266
		$params = array();
267
268
		foreach ($params_ary as $key => $call)
269
		{
270
			if (!isset($_REQUEST[$key]))
271
			{
272
				continue;
273
			}
274
275
			$param = call_user_func_array('request_var', $call);
276
			$param = urlencode($key) . '=' . ((is_string($param)) ? urlencode($param) : $param);
277
278
			if (!in_array($key, $excluded_keys))
279
			{
280
				$params[] = $param;
281
			}
282
		}
283
284
		return $params;
285
	}
286
287
	/**
288
	 * @return bool
289
	 * @access public
290
	 */
291
	public function can_use_ppde()
292
	{
293
		return $this->auth->acl_get('u_ppde_use');
294
	}
295
296
	/**
297
	 * @return bool
298
	 * @access public
299
	 */
300
	public function can_view_ppde_donorlist()
301
	{
302
		return $this->auth->acl_get('u_ppde_view_donorlist');
303
	}
304
305
	/**
306
	 * @return bool
307
	 * @access private
308
	 */
309
	private function donorlist_is_enabled()
310
	{
311
		return $this->config['ppde_enable'] && $this->config['ppde_ipn_enable'] && $this->config['ppde_ipn_donorlist_enable'];
312
	}
313
314
	/**
315
	 * @param string $set_return_args_url
316
	 *
317
	 * @return null
318
	 * @access private
319
	 */
320
	private function set_return_args_url($set_return_args_url)
321
	{
322
		switch ($set_return_args_url)
323
		{
324
			case 'cancel':
325
			case 'success':
326
				$this->template->assign_vars(array(
327
					'L_PPDE_DONATION_TITLE' => $this->user->lang['PPDE_' . strtoupper($set_return_args_url) . '_TITLE'],
328
				));
329
				$this->return_args_url = $set_return_args_url;
330
				break;
331
			case 'donorlist':
332
				$this->template->assign_vars(array(
333
					'L_PPDE_DONORLIST_TITLE' => $this->user->lang['PPDE_DONORLIST_TITLE'],
334
				));
335
				$this->return_args_url = $set_return_args_url;
336
				break;
337
			default:
338
				$this->return_args_url = 'body';
339
		}
340
341
	}
342
343
	/**
344
	 * Get content of current donation pages
345
	 *
346
	 * @param string $return_args_url
347
	 *
348
	 * @return array
349
	 * @access private
350
	 */
351
	private function get_donation_content_data($return_args_url)
352
	{
353
		return $this->donation_content_data =
354
			$this->ppde_entity_donation_pages->get_data(
355
				$this->ppde_operator_donation_pages->build_sql_data($this->user->get_iso_lang_id(), $return_args_url));
356
	}
357
358
	/**
359
	 * Build pull down menu options of available currency
360
	 *
361
	 * @param int $config_value Currency identifier; default: 0
362
	 *
363
	 * @return null
364
	 * @access public
365
	 */
366
	public function build_currency_select_menu($config_value = 0)
367
	{
368
		// Grab the list of all enabled currencies; 0 is for all data
369
		$currency_items = $this->ppde_entity_currency->get_data($this->ppde_operator_currency->build_sql_data(0, true));
370
371
		// Process each rule menu item for pull-down
372
		foreach ($currency_items as $currency_item)
373
		{
374
			// Set output block vars for display in the template
375
			$this->template->assign_block_vars('options', array(
376
				'CURRENCY_ID'        => (int) $currency_item['currency_id'],
377
				'CURRENCY_ISO_CODE'  => $currency_item['currency_iso_code'],
378
				'CURRENCY_NAME'      => $currency_item['currency_name'],
379
				'CURRENCY_SYMBOL'    => $currency_item['currency_symbol'],
380
381
				'S_CURRENCY_DEFAULT' => $config_value == $currency_item['currency_id'],
382
			));
383
		}
384
		unset ($currency_items, $currency_item);
385
	}
386
387
	/**
388
	 * Build pull down menu options of available currency value
389
	 *
390
	 * @return string List of currency value set in ACP for dropdown menu
391
	 * @access private
392
	 */
393
	private function build_currency_value_select_menu()
394
	{
395
		$list_donation_value = '';
396
397
		if ($this->get_dropbox_status())
398
		{
399
			$donation_ary_value = explode(',', $this->config['ppde_dropbox_value']);
400
401
			foreach ($donation_ary_value as $value)
402
			{
403
				$int_value = $this->settype_dropbox_int_value($value);
404
				$list_donation_value .= !empty($int_value) ? '<option value="' . $int_value . '">' . $int_value . '</option>' : '';
405
			}
406
			unset($value);
407
		}
408
409
		return $list_donation_value;
410
	}
411
412
	/**
413
	 * Get dropbox config value
414
	 *
415
	 * @return bool
416
	 * @access private
417
	 */
418
	private function get_dropbox_status()
419
	{
420
		return $this->config['ppde_dropbox_enable'] && $this->config['ppde_dropbox_value'];
421
	}
422
423
	/**
424
	 * Force dropbox value to integer
425
	 *
426
	 * @param int $value
427
	 *
428
	 * @return int
429
	 * @access private
430
	 */
431
	private function settype_dropbox_int_value($value = 0)
432
	{
433
		if (settype($value, 'integer') && $value != 0)
434
		{
435
			return $value;
436
		}
437
438
		return 0;
439
	}
440
441
	/**
442
	 * Build PayPal hidden fields
443
	 *
444
	 * @return string PayPal hidden field needed to fill PayPal forms
445
	 * @access private
446
	 */
447
	private function paypal_hidden_fields()
448
	{
449
		return build_hidden_fields(array(
450
			'cmd'           => '_donations',
451
			'business'      => $this->get_account_id(),
452
			'item_name'     => $this->user->lang['PPDE_DONATION_TITLE_HEAD'] . ' ' . $this->config['sitename'],
453
			'no_shipping'   => 1,
454
			'return'        => $this->generate_paypal_return_url('success'),
455
			'notify_url'    => $this->generate_paypal_notify_return_url(),
456
			'cancel_return' => $this->generate_paypal_return_url('cancel'),
457
			'item_number'   => 'uid_' . $this->user->data['user_id'] . '_' . time(),
458
			'tax'           => 0,
459
			'bn'            => 'Board_Donate_WPS',
460
			'charset'       => 'utf-8',
461
		));
462
	}
463
464
	/**
465
	 * Get PayPal account id
466
	 *
467
	 * @return string $this Paypal account Identifier
468
	 * @access private
469
	 */
470
	private function get_account_id()
471
	{
472
		return $this->use_sandbox() ? $this->config['ppde_sandbox_address'] : $this->config['ppde_account_id'];
473
	}
474
475
	/**
476
	 * Check if Sandbox is enabled
477
	 *
478
	 * @return bool
479
	 * @access public
480
	 */
481
	public function use_sandbox()
482
	{
483
		return $this->use_ipn() && !empty($this->config['ppde_sandbox_enable']) && ((!empty($this->config['ppde_sandbox_founder_enable']) && ($this->user->data['user_type'] == USER_FOUNDER)) || empty($this->config['ppde_sandbox_founder_enable']));
484
	}
485
486
	/**
487
	 * Check if IPN is enabled
488
	 *
489
	 * @return bool
490
	 * @access public
491
	 */
492
	public function use_ipn()
493
	{
494
		return !empty($this->config['ppde_enable']) && !empty($this->config['ppde_ipn_enable']) && (!empty($this->config['ppde_curl_detected']) || !empty($this->config['ppde_fsockopen_detected']));
495
	}
496
497
	/**
498
	 * Generate PayPal return URL
499
	 *
500
	 * @param string $arg
501
	 *
502
	 * @return string
503
	 * @access private
504
	 */
505
	private function generate_paypal_return_url($arg)
506
	{
507
		return generate_board_url(true) . $this->helper->route('skouat_ppde_donate', array('return' => $arg));
508
	}
509
510
	/**
511
	 * Generate PayPal return notify URL
512
	 *
513
	 * @return string
514
	 * @access private
515
	 */
516
	private function generate_paypal_notify_return_url()
517
	{
518
		return generate_board_url(true) . $this->helper->route('skouat_ppde_ipn_listener');
519
	}
520
521
	/**
522
	 * Get PayPal URL
523
	 * Used in form and in IPN process
524
	 *
525
	 * @param bool $is_test_ipn
526
	 *
527
	 * @return string
528
	 * @access public
529
	 */
530
	public function get_paypal_url($is_test_ipn = false)
531
	{
532
		return ($is_test_ipn || $this->use_sandbox()) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';
533
	}
534
535
	/**
536
	 * Assign statistics vars to the template
537
	 *
538
	 * @return null
539
	 * @access public
540
	 */
541
	public function display_stats()
542
	{
543
		if ($this->config['ppde_goal_enable'] || $this->config['ppde_raised_enable'] || $this->config['ppde_used_enable'])
544
		{
545
			// Get data from the database
546
			$default_currency_data = $this->get_default_currency_data($this->config['ppde_default_currency']);
547
548
			$this->template->assign_vars(array(
549
				'PPDE_GOAL_ENABLE'   => $this->config['ppde_goal_enable'],
550
				'PPDE_RAISED_ENABLE' => $this->config['ppde_raised_enable'],
551
				'PPDE_USED_ENABLE'   => $this->config['ppde_used_enable'],
552
553
				'L_PPDE_GOAL'        => $this->get_ppde_goal_langkey($default_currency_data[0]['currency_symbol'], (bool) $default_currency_data[0]['currency_on_left']),
554
				'L_PPDE_RAISED'      => $this->get_ppde_raised_langkey($default_currency_data[0]['currency_symbol'], (bool) $default_currency_data[0]['currency_on_left']),
555
				'L_PPDE_USED'        => $this->get_ppde_used_langkey($default_currency_data[0]['currency_symbol'], (bool) $default_currency_data[0]['currency_on_left']),
556
			));
557
558
			// Generate statistics percent for display
559
			$this->generate_stats_percent();
560
		}
561
	}
562
563
	/**
564
	 * Get default currency symbol
565
	 *
566
	 * @param int $id
567
	 *
568
	 * @return array
569
	 * @access public
570
	 */
571
	public function get_default_currency_data($id = 0)
572
	{
573
		return $this->ppde_entity_currency->get_data($this->ppde_operator_currency->build_sql_data($id, true));
574
	}
575
576
	/**
577
	 * Retrieve the language key for donation goal
578
	 *
579
	 * @param string $currency_symbol Currency symbol
580
	 * @param bool   $on_left         Symbol position
581
	 *
582
	 * @return string
583
	 * @access public
584
	 */
585
	public function get_ppde_goal_langkey($currency_symbol, $on_left = true)
586
	{
587
		if ((int) $this->config['ppde_goal'] <= 0)
588
		{
589
			$l_ppde_goal = $this->user->lang['PPDE_DONATE_NO_GOAL'];
590
		}
591 View Code Duplication
		else if ((int) $this->config['ppde_goal'] < (int) $this->config['ppde_raised'])
592
		{
593
			$l_ppde_goal = $this->user->lang['PPDE_DONATE_GOAL_REACHED'];
594
		}
595
		else
596
		{
597
			$l_ppde_goal = $this->user->lang('PPDE_DONATE_GOAL_RAISE', $this->currency_on_left((int) $this->config['ppde_goal'], $currency_symbol, $on_left));
598
		}
599
600
		return $l_ppde_goal;
601
	}
602
603
	/**
604
	 * Put the currency on the left or on the right of the amount
605
	 *
606
	 * @param int    $value
607
	 * @param string $currency
608
	 * @param bool   $on_left
609
	 *
610
	 * @return string
611
	 * @access public
612
	 */
613
	public function currency_on_left($value, $currency, $on_left = true)
614
	{
615
		return $on_left ? $currency . $value : $value . $currency;
616
	}
617
618
	/**
619
	 * Retrieve the language key for donation raised
620
	 *
621
	 * @param string $currency_symbol Currency symbol
622
	 * @param bool   $on_left         Symbol position
623
	 *
624
	 * @return string
625
	 * @access public
626
	 */
627
	public function get_ppde_raised_langkey($currency_symbol, $on_left = true)
628
	{
629 View Code Duplication
		if ((int) $this->config['ppde_raised'] <= 0)
630
		{
631
			$l_ppde_raised = $this->user->lang['PPDE_DONATE_NOT_RECEIVED'];
632
		}
633
		else
634
		{
635
			$l_ppde_raised = $this->user->lang('PPDE_DONATE_RECEIVED', $this->currency_on_left((int) $this->config['ppde_raised'], $currency_symbol, $on_left));
636
		}
637
638
		return $l_ppde_raised;
639
	}
640
641
	/**
642
	 * Retrieve the language key for donation used
643
	 *
644
	 * @param string $currency_symbol Currency symbol
645
	 * @param bool   $on_left         Symbol position
646
	 *
647
	 * @return string
648
	 * @access public
649
	 */
650
	public function get_ppde_used_langkey($currency_symbol, $on_left = true)
651
	{
652
		if ((int) $this->config['ppde_used'] <= 0)
653
		{
654
			$l_ppde_used = $this->user->lang['PPDE_DONATE_NOT_USED'];
655
		}
656
		else if ((int) $this->config['ppde_used'] < (int) $this->config['ppde_raised'])
657
		{
658
			$l_ppde_used = $this->user->lang('PPDE_DONATE_USED', $this->currency_on_left((int) $this->config['ppde_used'], $currency_symbol, $on_left), $this->currency_on_left((int) $this->config['ppde_raised'], $currency_symbol, $on_left));
659
		}
660
		else
661
		{
662
			$l_ppde_used = $this->user->lang('PPDE_DONATE_USED_EXCEEDED', $this->currency_on_left((int) $this->config['ppde_used'], $currency_symbol, $on_left));
663
		}
664
665
		return $l_ppde_used;
666
	}
667
668
	/**
669
	 * Generate statistics percent for display
670
	 *
671
	 * @return null
672
	 * @access private
673
	 */
674
	private function generate_stats_percent()
675
	{
676 View Code Duplication
		if ($this->is_ppde_goal_stats())
1 ignored issue
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...
677
		{
678
			$percent = $this->percent_value((int) $this->config['ppde_raised'], (int) $this->config['ppde_goal']);
679
			$this->assign_vars_stats_percent($percent, 'GOAL_NUMBER');
680
			$this->template->assign_var('PPDE_CSS_GOAL_NUMBER', $this->ppde_css_classname($percent));
681
		}
682
683 View Code Duplication
		if ($this->is_ppde_used_stats())
1 ignored issue
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...
684
		{
685
			$percent = $this->percent_value((int) $this->config['ppde_used'], (int) $this->config['ppde_raised']);
686
			$this->assign_vars_stats_percent($percent, 'USED_NUMBER');
687
			$this->template->assign_var('PPDE_CSS_USED_NUMBER', $this->ppde_css_classname($percent, true));
688
		}
689
	}
690
691
	/**
692
	 * Checks if stats can be displayed
693
	 *
694
	 * @return bool
695
	 * @access private
696
	 */
697
	private function is_ppde_goal_stats()
698
	{
699
		return $this->config['ppde_goal_enable'] && (int) $this->config['ppde_goal'] > 0;
700
	}
701
702
	/**
703
	 * Checks if stats can be displayed
704
	 *
705
	 * @return bool
706
	 * @access private
707
	 */
708
	private function is_ppde_used_stats()
709
	{
710
		return $this->config['ppde_used_enable'] && (int) $this->config['ppde_raised'] > 0 && (int) $this->config['ppde_used'] > 0;
711
	}
712
713
714
	/**
715
	 * Returns percent value
716
	 *
717
	 * @param integer $multiplicand
718
	 * @param integer $dividend
719
	 *
720
	 * @return float
721
	 * @access private
722
	 */
723
	private function percent_value($multiplicand, $dividend)
724
	{
725
		return round(($multiplicand * 100) / $dividend, 2);
726
	}
727
728
	/**
729
	 * Assign statistics percent vars to template
730
	 *
731
	 * @param float  $percent
732
	 * @param string $type
733
	 *
734
	 * @return null
735
	 * @access private
736
	 */
737
	private function assign_vars_stats_percent($percent, $type)
738
	{
739
		$this->template->assign_vars(array(
740
			'PPDE_' . $type => $percent,
741
			'S_' . $type    => !empty($type) ? true : false,
742
		));
743
	}
744
745
	/**
746
	 * Returns the CSS class name based on the percent of stats
747
	 *
748
	 * @param float $value
749
	 * @param bool  $reverse
750
	 *
751
	 * @return string
752
	 * @access private
753
	 */
754
	private function ppde_css_classname($value, $reverse = false)
755
	{
756
		$css_reverse = '';
757
758
		if ($reverse && $value < 100)
759
		{
760
			$value = 100 - $value;
761
			$css_reverse = '-reverse';
762
		}
763
764
		switch ($value)
765
		{
766
			case ($value <= 10):
767
				return 'ten' . $css_reverse;
768
			case ($value <= 20):
769
				return 'twenty' . $css_reverse;
770
			case ($value <= 30):
771
				return 'thirty' . $css_reverse;
772
			case ($value <= 40):
773
				return 'forty' . $css_reverse;
774
			case ($value <= 50):
775
				return 'fifty' . $css_reverse;
776
			case ($value <= 60):
777
				return 'sixty' . $css_reverse;
778
			case ($value <= 70):
779
				return 'seventy' . $css_reverse;
780
			case ($value <= 80):
781
				return 'eighty' . $css_reverse;
782
			case ($value <= 90):
783
				return 'ninety' . $css_reverse;
784
			case ($value < 100):
785
				return 'hundred' . $css_reverse;
786
			default:
787
				return $reverse ? 'red' : 'green';
788
		}
789
	}
790
791
	/**
792
	 * Send data to the template file
793
	 *
794
	 * @return \Symfony\Component\HttpFoundation\Response
795
	 * @access private
796
	 */
797
	private function send_data_to_template()
798
	{
799
		switch ($this->return_args_url)
800
		{
801
			case 'cancel':
802
			case 'success':
803
				return $this->helper->render('donate_body.html', $this->user->lang('PPDE_' . strtoupper($this->return_args_url) . '_TITLE'));
804
			case 'donorlist':
805
				return $this->helper->render('donorlist_body.html', $this->user->lang('PPDE_DONORLIST_TITLE'));
806
			default:
807
				return $this->helper->render('donate_body.html', $this->user->lang('PPDE_DONATION_TITLE'));
808
		}
809
	}
810
811
	/**
812
	 * Do action if it's the first time the extension is accessed
813
	 *
814
	 * @return null
815
	 * @access public
816
	 */
817
	public function first_start()
818
	{
819
		if ($this->config['ppde_first_start'])
820
		{
821
			$this->set_curl_info();
822
			$this->set_remote_detected();
823
			$this->config['ppde_first_start'] = false;
824
		}
825
	}
826
827
	/**
828
	 * Check if cURL is available
829
	 *
830
	 * @param bool $check_version
831
	 *
832
	 * @return array|bool
833
	 * @access public
834
	 */
835
	public function check_curl($check_version = false)
836
	{
837
		if (function_exists('curl_version') && $check_version)
838
		{
839
			return curl_version();
840
		}
841
842
		if (function_exists('curl_init') && function_exists('curl_exec'))
843
		{
844
			$this->get_ext_meta();
845
846
			$ch = curl_init($this->ext_meta['extra']['version-check']['host']);
847
848
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
849
850
			$response = curl_exec($ch);
851
			$response_status = strval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
852
853
			curl_close($ch);
854
855
			return ($response !== false || $response_status !== '0') ? true : false;
856
		}
857
858
		return false;
859
	}
860
861
	/**
862
	 * Set config value for cURL version
863
	 *
864
	 * @return null
865
	 * @access public
866
	 */
867
	public function set_curl_info()
868
	{
869
		// Get cURL version informations
870
		if ($curl_info = $this->check_curl(true))
871
		{
872
			$this->config->set('ppde_curl_version', $curl_info['version']);
873
			$this->config->set('ppde_curl_ssl_version', $curl_info['ssl_version']);
874
		}
875
	}
876
877
	/**
878
	 * Set config value for cURL and fsockopen
879
	 *
880
	 * @return null
881
	 * @access public
882
	 */
883
	public function set_remote_detected()
884
	{
885
		$this->config->set('ppde_curl_detected', $this->check_curl());
886
		$this->config->set('ppde_fsock_detected', $this->check_fsockopen());
887
	}
888
889
	/**
890
	 * Get extension metadata
891
	 *
892
	 * @return null
893
	 * @access protected
894
	 */
895
	protected function get_ext_meta()
896
	{
897
		if (empty($this->ext_meta))
898
		{
899
			$this->load_metadata();
900
		}
901
	}
902
903
	/**
904
	 * Load metadata for this extension
905
	 *
906
	 * @return array
907
	 * @access public
908
	 */
909
	public function load_metadata()
910
	{
911
		// Retrieve the extension name based on the namespace of this file
912
		$this->retrieve_ext_name();
913
914
		// If they've specified an extension, let's load the metadata manager and validate it.
915
		if ($this->ext_name)
916
		{
917
			$md_manager = new \phpbb\extension\metadata_manager($this->ext_name, $this->config, $this->extension_manager, $this->template, $this->user, $this->root_path);
918
919
			try
920
			{
921
				$this->ext_meta = $md_manager->get_metadata('all');
922
			}
923
			catch (\phpbb\extension\exception $e)
924
			{
925
				trigger_error($e, E_USER_WARNING);
926
			}
927
		}
928
929
		return $this->ext_meta;
930
	}
931
932
	/**
933
	 * Retrieve the extension name
934
	 *
935
	 * @return null
936
	 * @access protected
937
	 */
938
	protected function retrieve_ext_name()
939
	{
940
		$namespace_ary = explode('\\', __NAMESPACE__);
941
		$this->ext_name = $namespace_ary[0] . '/' . $namespace_ary[1];
942
	}
943
944
	/**
945
	 * Check if fsockopen is available
946
	 *
947
	 * @return bool
948
	 * @access public
949
	 */
950
	public function check_fsockopen()
951
	{
952
		if (function_exists('fsockopen'))
953
		{
954
			$this->get_ext_meta();
955
956
			$url = parse_url($this->ext_meta['extra']['version-check']['host']);
957
958
			$fp = @fsockopen($url['path'], 80);
959
960
			return ($fp !== false) ? true : false;
961
		}
962
963
		return false;
964
	}
965
}
966