Completed
Pull Request — develop (#26)
by Mario
04:52 queued 01:40
created

admin_transactions_controller::do_action()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 60
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 60
rs 8.6961
cc 6
eloc 32
nc 3
nop 1

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
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
/**
16
 * @property ContainerInterface       container         The phpBB log system
17
 * @property string                   id_prefix_name    Prefix name for identifier in the URL
18
 * @property string                   lang_key_prefix   Prefix for the messages thrown by exceptions
19
 * @property \phpbb\log\log           log               The phpBB log system.
20
 * @property string                   module_name       Name of the module currently used
21
 * @property \phpbb\request\request   request           Request object.
22
 * @property bool                     submit            State of submit $_POST variable
23
 * @property \phpbb\template\template template          Template object
24
 * @property string                   u_action          Action URL
25
 * @property \phpbb\user              user              User object.
26
 */
27
class admin_transactions_controller extends admin_main
28
{
29
	public $ppde_operator;
30
31
	protected $adm_relative_path;
32
	protected $auth;
33
	protected $db;
34
	protected $config;
35
	protected $entry_count;
36
	protected $last_page_offset;
37
	protected $phpbb_admin_path;
38
	protected $phpbb_root_path;
39
	protected $php_ext;
40
	protected $table_ppde_transactions;
41
42
	/**
43
	 * Constructor
44
	 *
45
	 * @param \phpbb\auth\auth                    $auth                       Authentication object
46
	 * @param \phpbb\db\driver\driver_interface   $db                         Database object
47
	 * @param \phpbb\config\config                $config                     Config object
48
	 * @param ContainerInterface                  $container
49
	 * @param \phpbb\log\log                      $log                        The phpBB log system
50
	 * @param \skouat\ppde\operators\transactions $ppde_operator_transactions Operator object
51
	 * @param \phpbb\request\request              $request                    Request object
52
	 * @param \phpbb\template\template            $template                   Template object
53
	 * @param \phpbb\user                         $user                       User object.
54
	 * @param string                              $adm_relative_path          phpBB admin relative path
55
	 * @param string                              $phpbb_root_path            phpBB root path
56
	 * @param string                              $php_ext                    phpEx
57
	 * @param string                              $table_ppde_transactions    Name of the table used to store data
58
	 *
59
	 * @access public
60
	 */
61
	public function __construct(\phpbb\auth\auth $auth, \phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, ContainerInterface $container, \phpbb\log\log $log, \skouat\ppde\operators\transactions $ppde_operator_transactions, \phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user, $adm_relative_path, $phpbb_root_path, $php_ext, $table_ppde_transactions)
62
	{
63
		$this->auth = $auth;
64
		$this->db = $db;
65
		$this->config = $config;
66
		$this->container = $container;
67
		$this->log = $log;
68
		$this->ppde_operator = $ppde_operator_transactions;
69
		$this->request = $request;
70
		$this->template = $template;
71
		$this->user = $user;
72
		$this->adm_relative_path = $adm_relative_path;
73
		$this->phpbb_admin_path = $phpbb_root_path . $adm_relative_path;
74
		$this->phpbb_root_path = $phpbb_root_path;
75
		$this->php_ext = $php_ext;
76
		$this->table_ppde_transactions = $table_ppde_transactions;
77
		parent::__construct(
78
			'transactions',
79
			'PPDE_DT',
80
			'transaction'
81
		);
82
	}
83
84
	/**
85
	 * Display the transactions list
86
	 *
87
	 * @param string $id     Module id
88
	 * @param string $mode   Module categorie
89
	 * @param string $action Action name
90
	 *
91
	 * @return null
92
	 * @access public
93
	 */
94
	public function display_transactions($id, $mode, $action)
95
	{
96
		// Set up general vars
97
		$start = $this->request->variable('start', 0);
98
		$deletemark = $this->request->is_set('delmarked');
99
		$deleteall = $this->request->is_set('delall');
100
		$marked = $this->request->variable('mark', array(0));
101
		// Sort keys
102
		$sort_days = $this->request->variable('st', 0);
103
		$sort_key = $this->request->variable('sk', 't');
104
		$sort_dir = $this->request->variable('sd', 'd');
105
106
		// Initiate an entity
107
		/** @type \skouat\ppde\entity\transactions $entity */
108
		$entity = $this->get_container_entity();
109
110
		// Delete entries if requested and able
111
		if (($deletemark || $deleteall) && $this->auth->acl_get('a_ppde_manage'))
112
		{
113
			if (confirm_box(true))
114
			{
115
				$where_sql = '';
116
117
				if ($deletemark && sizeof($marked))
118
				{
119
					$where_sql = $this->ppde_operator->build_marked_where_sql($marked);
120
				}
121
122
				if ($where_sql || $deleteall)
123
				{
124
					$entity->delete(0, '', $where_sql);
125
126
					$this->config->set('ppde_known_donors_count', $this->sql_query_update_stats('ppde_known_donors_count'), true);
127
					$this->config->set('ppde_anonymous_donors_count', $this->sql_query_update_stats('ppde_anonymous_donors_count'));
128
					$this->config->set('ppde_transactions_count', $this->sql_query_update_stats('ppde_transactions_count'), true);
129
130
					$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_' . $this->lang_key_prefix . '_PURGED', time());
131
				}
132
			}
133
			else
134
			{
135
				confirm_box(false, $this->user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
136
						'start'     => $start,
137
						'delmarked' => $deletemark,
138
						'delall'    => $deleteall,
139
						'mark'      => $marked,
140
						'st'        => $sort_days,
141
						'sk'        => $sort_key,
142
						'sd'        => $sort_dir,
143
						'i'         => $id,
144
						'mode'      => $mode,
145
						'action'    => $action))
146
				);
147
			}
148
		}
149
150
		$this->do_action($action);
151
152
		if (!$action)
153
		{
154
			/** @type \phpbb\pagination $pagination */
155
			$pagination = $this->container->get('pagination');
156
157
			// Sorting
158
			$limit_days = array(0 => $this->user->lang['ALL_ENTRIES'], 1 => $this->user->lang['1_DAY'], 7 => $this->user->lang['7_DAYS'], 14 => $this->user->lang['2_WEEKS'], 30 => $this->user->lang['1_MONTH'], 90 => $this->user->lang['3_MONTHS'], 180 => $this->user->lang['6_MONTHS'], 365 => $this->user->lang['1_YEAR']);
159
			$sort_by_text = array('txn' => $this->user->lang['PPDE_DT_SORT_TXN_ID'], 'u' => $this->user->lang['PPDE_DT_SORT_DONORS'], 'ipn' => $this->user->lang['PPDE_DT_SORT_IPN_STATUS'], 'ps' => $this->user->lang['PPDE_DT_SORT_PAYMENT_STATUS'], 't' => $this->user->lang['SORT_DATE']);
160
			$sort_by_sql = array('txn' => 'txn.txn_id', 'u' => 'u.username_clean', 'ipn' => 'txn.confirmed', 'ps' => 'txn.payment_status', 't' => 'txn.payment_date');
161
162
			$s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
163
			gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
164
165
			// Define where and sort sql for use in displaying transactions
166
			$sql_where = ($sort_days) ? (time() - ($sort_days * 86400)) : 0;
167
			$sql_sort = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');
168
169
			$keywords = utf8_normalize_nfc($this->request->variable('keywords', '', true));
170
			$keywords_param = !empty($keywords) ? '&amp;keywords=' . urlencode(htmlspecialchars_decode($keywords)) : '';
171
172
			// Grab log data
173
			$log_data = array();
174
			$log_count = 0;
175
176
			$this->view_txn_log($log_data, $log_count, $this->config['topics_per_page'], $start, $sql_where, $sql_sort, $keywords);
177
178
			$base_url = $this->u_action . '&amp;' . $u_sort_param . $keywords_param;
179
			$pagination->generate_template_pagination($base_url, 'pagination', 'start', $log_count, $this->config['topics_per_page'], $start);
180
181
			$this->template->assign_vars(array(
182
				'S_CLEARLOGS'  => $this->auth->acl_get('a_ppde_manage'),
183
				'S_KEYWORDS'   => $keywords,
184
				'S_LIMIT_DAYS' => $s_limit_days,
185
				'S_SORT_KEY'   => $s_sort_key,
186
				'S_SORT_DIR'   => $s_sort_dir,
187
				'S_TXN'        => $mode,
188
189
				'U_ACTION'     => $this->u_action . '&amp;' . $u_sort_param . $keywords_param . '&amp;start=' . $start,
190
			));
191
192
			foreach ($log_data as $row)
193
			{
194
				// Initiate vars to retrieve the 'payment_status' translation from the language key
195
				$payment_status_ary = $this->user->lang['PPDE_DT_PAYMENT_STATUS_VALUES'];
196
				$payment_status_name = strtolower($row['payment_status']);
197
198
				$this->template->assign_block_vars('log', array(
199
					'TNX_ID'           => $row['txn_id'],
200
					'USERNAME'         => $row['username_full'],
201
					'DATE'             => $this->user->format_date($row['payment_date']),
202
					'ID'               => $row['transaction_id'],
203
					'CONFIRMED'        => ($row['confirmed']) ? $this->user->lang['PPDE_DT_VERIFIED'] : $this->user->lang['PPDE_DT_UNVERIFIED'],
204
					'PAYMENT_STATUS'   => $payment_status_ary[$payment_status_name],
205
206
					'S_CONFIRMED'      => ($row['confirmed']) ? false : true,
207
					'S_PAYMENT_STATUS' => ($payment_status_name === 'completed') ? false : true,
208
				));
209
				unset($payment_status_name);
210
			}
211
		}
212
	}
213
214
	/**
215
	 * Returns count result for updating stats
216
	 *
217
	 * @param string $config_name
218
	 *
219
	 * @return int
220
	 * @access public
221
	 */
222
	public function sql_query_update_stats($config_name)
223
	{
224
		if (!$this->config->offsetExists($config_name))
225
		{
226
			trigger_error($this->user->lang('EXCEPTION_INVALID_CONFIG_NAME', $config_name), E_USER_WARNING);
227
		}
228
229
		$this->db->sql_query($this->make_stats_sql_update($config_name));
230
231
		return (int) $this->db->sql_fetchfield('count_result');
232
	}
233
234
	/**
235
	 * Build SQL query for updating stats
236
	 *
237
	 * @param string $type
238
	 *
239
	 * @return string
240
	 * @access private
241
	 */
242
	private function make_stats_sql_update($type)
243
	{
244
		switch ($type)
245
		{
246
			case 'ppde_transactions_count':
247
				$sql = $this->make_stats_sql_select('txn_id');
248
				$sql .= " WHERE confirmed = 1 AND payment_status = 'Completed'";
249
250
				return $sql;
251
			case 'ppde_known_donors_count':
252
				$sql = $this->make_stats_sql_select('payer_id');
253
				$sql .= ' LEFT JOIN ' . USERS_TABLE . ' u
254
				 					ON txn.user_id = u.user_id
255
								WHERE u.user_type = ' . USER_NORMAL . ' OR u.user_type = ' . USER_FOUNDER;
256
257
				return $sql;
258
			case 'ppde_anonymous_donors_count':
259
				$sql = $this->make_stats_sql_select('payer_id');
260
				$sql .= ' WHERE txn.user_id = ' . ANONYMOUS;
261
262
				return $sql;
263
			default:
264
				return $this->make_stats_sql_select('txn_id');
265
		}
266
	}
267
268
	/**
269
	 * Make body of SQL query for stats calculation.
270
	 *
271
	 * @param string $field_name Name of the field
272
	 *
273
	 * @return string
274
	 * @access private
275
	 */
276
	private function make_stats_sql_select($field_name)
277
	{
278
		return 'SELECT COUNT(DISTINCT txn.' . $field_name . ') AS count_result
279
				FROM ' . $this->table_ppde_transactions . ' txn';
280
	}
281
282
	/**
283
	 * Do action regarding the value of $action
284
	 *
285
	 * @param $action
286
	 *
287
	 * @return null
288
	 * @access private
289
	 */
290
	private function do_action($action)
291
	{
292
		// Action: view
293
		if ($action == 'view')
294
		{
295
			// Request Identifier of the transaction
296
			$transaction_id = $this->request->variable('id', 0);
297
298
			// Initiate an entity
299
			/** @type \skouat\ppde\entity\currency $entity */
300
			$entity = $this->get_container_entity();
301
302
			// add field username to the table schema needed by entity->import()
303
			$additional_table_schema = array('item_username' => array('name' => 'username', 'type' => 'string'));
304
305
			// Grab transaction data
306
			$data_ary = $entity->get_data($this->ppde_operator->build_sql_data($transaction_id), $additional_table_schema);
307
308
			foreach ($data_ary as $data)
309
			{
310
				// Initiate vars to retrieve the 'payment_status' translation from the language key
311
				$payment_status_ary = $this->user->lang['PPDE_DT_PAYMENT_STATUS_VALUES'];
312
313
				$this->template->assign_vars(array(
314
					'S_CONVERT'      => ($data['settle_amount'] == 0 && empty($data['exchange_rate'])) ? false : true,
315
316
					'TXN_ID'         => $data['txn_id'],
317
318
					'BOARD_USERNAME' => $data['username'],
319
					'NAME'           => $data['first_name'] . ' ' . $data['last_name'],
320
					'PAYER_EMAIL'    => $data['payer_email'],
321
					'PAYER_ID'       => $data['payer_id'],
322
					'PAYER_STATUS'   => ($data['payer_status']) ? $this->user->lang['PPDE_DT_VERIFIED'] : $this->user->lang['PPDE_DT_UNVERIFIED'],
323
324
					'RECEIVER_EMAIL' => $data['receiver_email'],
325
					'RECEIVER_ID'    => $data['receiver_id'],
326
327
					'MC_GROSS'       => $data['mc_gross'] . ' ' . $data['mc_currency'],
328
					'MC_FEE'         => '-' . $data['mc_fee'] . ' ' . $data['mc_currency'],
329
					'MC_NET'         => $data['net_amount'] . ' ' . $data['mc_currency'],
330
331
					'CONVERT_FROM'   => '-' . $data['net_amount'] . ' ' . $data['mc_currency'],
332
					'SETTLE_AMOUNT'  => $data['settle_amount'] . ' ' . $data['settle_currency'],
333
					'EXCHANGE_RATE'  => '1 ' . $data['mc_currency'] . ' = ' . $data['exchange_rate'] . ' ' . $data['settle_currency'],
334
335
					'ITEM_NAME'      => $data['item_name'],
336
					'ITEM_NUMBER'    => $data['item_number'],
337
					'PAYMENT_DATE'   => $this->user->format_date($data['payment_date']),
338
					'PAYMENT_STATUS' => $payment_status_ary[strtolower($data['payment_status'])],
339
				));
340
			}
341
342
			$this->template->assign_vars(array(
343
				'U_ACTION' => $this->u_action,
344
				'U_BACK'   => $this->u_action,
345
346
				'S_VIEW'   => true,
347
			));
348
		}
349
	}
350
351
	/**
352
	 * View log
353
	 *
354
	 * @param array  &$log         The result array with the logs
355
	 * @param mixed  &$log_count   If $log_count is set to false, we will skip counting all entries in the
356
	 *                             database. Otherwise an integer with the number of total matching entries is returned.
357
	 * @param int    $limit        Limit the number of entries that are returned
358
	 * @param int    $offset       Offset when fetching the log entries, f.e. when paginating
359
	 * @param int    $limit_days
360
	 * @param string $sort_by      SQL order option, e.g. 'l.log_time DESC'
361
	 * @param string $keywords     Will only return log entries that have the keywords in log_operation or log_data
362
	 *
363
	 * @return int Returns the offset of the last valid page, if the specified offset was invalid
364
	 *                               (too high)
365
	 * @access private
366
	 */
367
	private function view_txn_log(&$log, &$log_count, $limit = 0, $offset = 0, $limit_days = 0, $sort_by = 'txn.payment_date DESC', $keywords = '')
368
	{
369
		$count_logs = ($log_count !== false);
370
371
		$log = $this->get_logs($count_logs, $limit, $offset, $limit_days, $sort_by, $keywords);
372
		$log_count = $this->get_log_count();
373
374
		return $this->get_valid_offset();
375
	}
376
377
	/**
378
	 * @param bool   $count_logs
379
	 * @param int    $limit
380
	 * @param int    $offset
381
	 * @param int    $log_time
382
	 * @param string $sort_by
383
	 * @param string $keywords
384
	 *
385
	 * @return array $log
386
	 * @access private
387
	 */
388
	private function get_logs($count_logs = true, $limit = 0, $offset = 0, $log_time = 0, $sort_by = 'txn.payment_date DESC', $keywords = '')
389
	{
390
		$this->entry_count = 0;
391
		$this->last_page_offset = $offset;
392
		$url_ary = array();
393
394
		if ($this->get_container_entity()->is_in_admin() && $this->phpbb_admin_path)
395
		{
396
			$url_ary['profile_url'] = append_sid($this->phpbb_admin_path . 'index.' . $this->php_ext, 'i=users&amp;mode=overview');
397
			$url_ary['txn_url'] = append_sid($this->phpbb_admin_path . 'index.' . $this->php_ext, 'i=-skouat-ppde-acp-ppde_module&amp;mode=transactions');
398
399
		}
400
		else
401
		{
402
			$url_ary['profile_url'] = append_sid($this->phpbb_root_path . 'memberlist.' . $this->php_ext, 'mode=viewprofile');
403
			$url_ary['txn_url'] = '';
404
		}
405
406
		$get_logs_sql_ary = $this->ppde_operator->get_logs_sql_ary($keywords, $sort_by, $log_time);
407
408
		if ($count_logs)
409
		{
410
			$this->entry_count = $this->ppde_operator->query_sql_count($get_logs_sql_ary, 'txn.transaction_id');
411
412
			if ($this->entry_count == 0)
413
			{
414
				// Save the queries, because there are no logs to display
415
				$this->last_page_offset = 0;
416
417
				return array();
418
			}
419
420
			// Return the user to the last page that is valid
421
			while ($this->last_page_offset >= $this->entry_count)
422
			{
423
				$this->last_page_offset = max(0, $this->last_page_offset - $limit);
424
			}
425
		}
426
427
		return $this->ppde_operator->build_log_ary($get_logs_sql_ary, $url_ary, $limit, $this->last_page_offset);
428
	}
429
430
	/**
431
	 * {@inheritDoc}
432
	 */
433
	public function get_log_count()
434
	{
435
		return ($this->entry_count) ? $this->entry_count : 0;
436
	}
437
438
	/**
439
	 * {@inheritDoc}
440
	 */
441
	public function get_valid_offset()
442
	{
443
		return ($this->last_page_offset) ? $this->last_page_offset : 0;
444
	}
445
}
446