Passed
Push — develop-3.2.x-2.2 ( 69b928...55159b )
by Mario
02:15
created

transactions_controller::build_args_array()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 47
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 28
nc 5
nop 3
dl 0
loc 47
rs 8.5386
c 0
b 0
f 0
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\admin;
12
13
use phpbb\auth\auth;
14
use phpbb\config\config;
15
use phpbb\language\language;
16
use phpbb\log\log;
17
use phpbb\request\request;
18
use phpbb\template\template;
19
use phpbb\user;
20
use phpbb\user_loader;
21
use skouat\ppde\actions\core;
22
use skouat\ppde\actions\currency;
23
use skouat\ppde\exception\transaction_exception;
24
use skouat\ppde\operators\transactions;
25
use Symfony\Component\DependencyInjection\ContainerInterface;
26
27
/**
28
 * @property config             config             Config object
29
 * @property ContainerInterface container          Service container interface
30
 * @property string             id_prefix_name     Prefix name for identifier in the URL
31
 * @property string             lang_key_prefix    Prefix for the messages thrown by exceptions
32
 * @property language           language           Language user object
33
 * @property log                log                The phpBB log system.
34
 * @property string             module_name        Name of the module currently used
35
 * @property request            request            Request object.
36
 * @property bool               submit             State of submit $_POST variable
37
 * @property template           template           Template object
38
 * @property string             u_action           Action URL
39
 * @property user               user               User object.
40
 * @property user_loader        user_loader        User loader object
41
 */
42
class transactions_controller extends admin_main
43
{
44
	public $ppde_operator;
45
	protected $adm_relative_path;
46
	protected $auth;
47
	protected $user_loader;
48
	protected $entry_count;
49
	protected $last_page_offset;
50
	protected $php_ext;
51
	protected $phpbb_admin_path;
52
	protected $phpbb_root_path;
53
	protected $ppde_actions;
54
	protected $ppde_actions_currency;
55
	protected $ppde_entity;
56
	protected $table_prefix;
57
	protected $table_ppde_transactions;
58
59
	/**
60
	 * Constructor
61
	 *
62
	 * @param auth                             $auth                       Authentication object
63
	 * @param config                           $config                     Config object
64
	 * @param ContainerInterface               $container                  Service container interface
65
	 * @param language                         $language                   Language user object
66
	 * @param log                              $log                        The phpBB log system
67
	 * @param core                             $ppde_actions               PPDE actions object
68
	 * @param currency                         $ppde_actions_currency      PPDE currency actions object
69
	 * @param \skouat\ppde\entity\transactions $ppde_entity_transactions   Entity object
70
	 * @param transactions                     $ppde_operator_transactions Operator object
71
	 * @param request                          $request                    Request object
72
	 * @param template                         $template                   Template object
73
	 * @param user                             $user                       User object.
74
	 * @param user_loader                      $user_loader                User loader object
75
	 * @param string                           $adm_relative_path          phpBB admin relative path
76
	 * @param string                           $phpbb_root_path            phpBB root path
77
	 * @param string                           $php_ext                    phpEx
78
	 * @param string                           $table_prefix               The table prefix
79
	 * @param string                           $table_ppde_transactions    Name of the table used to store data
80
	 *
81
	 * @access public
82
	 */
83
	public function __construct(
84
		auth $auth,
85
		config $config,
86
		ContainerInterface $container,
87
		language $language,
88
		log $log,
89
		core $ppde_actions,
90
		currency $ppde_actions_currency,
91
		\skouat\ppde\entity\transactions $ppde_entity_transactions,
92
		transactions $ppde_operator_transactions,
93
		request $request,
94
		template $template,
95
		user $user,
96
		user_loader $user_loader,
97
		$adm_relative_path,
98
		$phpbb_root_path,
99
		$php_ext,
100
		$table_prefix,
101
		$table_ppde_transactions
102
	)
103
	{
104
		$this->auth = $auth;
105
		$this->config = $config;
106
		$this->container = $container;
107
		$this->language = $language;
108
		$this->log = $log;
109
		$this->ppde_actions = $ppde_actions;
110
		$this->ppde_actions_currency = $ppde_actions_currency;
111
		$this->ppde_entity = $ppde_entity_transactions;
112
		$this->ppde_operator = $ppde_operator_transactions;
113
		$this->request = $request;
114
		$this->template = $template;
115
		$this->user = $user;
116
		$this->user_loader = $user_loader;
117
		$this->adm_relative_path = $adm_relative_path;
118
		$this->phpbb_admin_path = $phpbb_root_path . $adm_relative_path;
119
		$this->phpbb_root_path = $phpbb_root_path;
120
		$this->php_ext = $php_ext;
121
		$this->table_prefix = $table_prefix;
122
		$this->table_ppde_transactions = $table_ppde_transactions;
123
		parent::__construct(
124
			'transactions',
125
			'PPDE_DT',
126
			'transaction'
127
		);
128
	}
129
130
	/**
131
	 * Display the transactions list
132
	 *
133
	 * @param string $id     Module id
134
	 * @param string $mode   Module categorie
135
	 * @param string $action Action name
136
	 *
137
	 * @return void
138
	 * @access public
139
	 */
140
	public function display_transactions($id, $mode, $action)
141
	{
142
		// Gets vars from REQUEST/POST then build a array of them
143
		$args = $this->build_args_array($id, $mode, $action);
144
145
		// Does the action regarding the action provided
146
		$action = $this->do_action($args);
147
148
		// Proceed if no action to do
149
		if (empty($action))
150
		{
151
			/** @type \phpbb\pagination $pagination */
152
			$pagination = $this->container->get('pagination');
153
154
			// Sorting
155
			$limit_days = array(
156
				0   => $this->language->lang('ALL_ENTRIES'),
157
				1   => $this->language->lang('1_DAY'),
158
				7   => $this->language->lang('7_DAYS'),
159
				14  => $this->language->lang('2_WEEKS'),
160
				30  => $this->language->lang('1_MONTH'),
161
				90  => $this->language->lang('3_MONTHS'),
162
				180 => $this->language->lang('6_MONTHS'),
163
				365 => $this->language->lang('1_YEAR'),
164
			);
165
			$sort_by_text = array(
166
				'txn'      => $this->language->lang('PPDE_DT_SORT_TXN_ID'),
167
				'u'        => $this->language->lang('PPDE_DT_SORT_DONORS'),
168
				'ipn'      => $this->language->lang('PPDE_DT_SORT_IPN_STATUS'),
169
				'ipn_test' => $this->language->lang('PPDE_DT_SORT_IPN_TYPE'),
170
				'ps'       => $this->language->lang('PPDE_DT_SORT_PAYMENT_STATUS'),
171
				't'        => $this->language->lang('SORT_DATE'),
172
			);
173
			$sort_by_sql = array(
174
				'txn'      => 'txn.txn_id',
175
				'u'        => 'u.username_clean',
176
				'ipn'      => 'txn.confirmed',
177
				'ipn_test' => 'txn.test_ipn',
178
				'ps'       => 'txn.payment_status',
179
				't'        => 'txn.payment_date',
180
			);
181
182
			$s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
183
			gen_sort_selects($limit_days, $sort_by_text, $args['hidden_fields']['st'], $args['hidden_fields']['sk'], $args['hidden_fields']['sd'], $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
184
185
			// Define where and sort sql for use in displaying transactions
186
			$sql_where = ($args['hidden_fields']['st']) ? (time() - ($args['hidden_fields']['st'] * 86400)) : 0;
187
			$sql_sort = $sort_by_sql[$args['hidden_fields']['sk']] . ' ' . (($args['hidden_fields']['sd'] == 'd') ? 'DESC' : 'ASC');
188
189
			$keywords = $this->request->variable('keywords', '', true);
190
			$keywords_param = !empty($keywords) ? '&amp;keywords=' . urlencode(htmlspecialchars_decode($keywords)) : '';
191
192
			// Grab log data
193
			$log_data = array();
194
			$log_count = 0;
195
196
			$this->view_txn_log($log_data, $log_count, (int) $this->config['topics_per_page'], $args['hidden_fields']['start'], $sql_where, $sql_sort, $keywords);
197
198
			$base_url = $this->u_action . '&amp;' . $u_sort_param . $keywords_param;
199
			$pagination->generate_template_pagination($base_url, 'pagination', 'start', $log_count, (int) $this->config['topics_per_page'], $args['hidden_fields']['start']);
200
201
			$this->template->assign_vars(array(
202
				'S_CLEARLOGS'  => $this->auth->acl_get('a_ppde_manage'),
203
				'S_KEYWORDS'   => $keywords,
204
				'S_LIMIT_DAYS' => $s_limit_days,
205
				'S_SORT_KEY'   => $s_sort_key,
206
				'S_SORT_DIR'   => $s_sort_dir,
207
				'S_TXN'        => $mode,
208
				'U_ACTION'     => $this->u_action . '&amp;' . $u_sort_param . $keywords_param . '&amp;start=' . $args['hidden_fields']['start'],
209
			));
210
211
			array_map(array($this, 'display_log_assign_template_vars'), $log_data);
212
		}
213
	}
214
215
	/**
216
	 * Gets vars from POST then build a array of them
217
	 *
218
	 * @param string $id     Module id
219
	 * @param string $mode   Module categorie
220
	 * @param string $action Action name
221
	 *
222
	 * @return array
223
	 * @access private
224
	 */
225
	private function build_args_array($id, $mode, $action)
226
	{
227
		$args = array(
228
			'action'        => $action,
229
			'hidden_fields' => array(
230
				'start'     => $this->request->variable('start', 0),
231
				'delall'    => $this->request->variable('delall', false, false, \phpbb\request\request_interface::POST),
232
				'delmarked' => $this->request->variable('delmarked', false, false, \phpbb\request\request_interface::POST),
233
				'mark'      => $this->request->variable('mark', array(0)),
234
				'st'        => $this->request->variable('st', 0),
235
				'sk'        => $this->request->variable('sk', 't'),
236
				'sd'        => $this->request->variable('sd', 'd'),
237
			),
238
		);
239
240
		// Prepares args depending actions
241
		if (($args['hidden_fields']['delmarked'] || $args['hidden_fields']['delall']) && $this->auth->acl_get('a_ppde_manage'))
242
		{
243
			$args = array(
244
				'action'        => 'delete',
245
				'hidden_fields' => array(
246
					'i'    => $id,
247
					'mode' => $mode,
248
				),
249
			);
250
		}
251
		else if ($this->request->is_set('approve'))
252
		{
253
			$args = array(
254
				'action'        => 'approve',
255
				'hidden_fields' => array(
256
					'approve'             => true,
257
					'id'                  => $this->request->variable('id', 0),
258
					'txn_errors_approved' => $this->request->variable('txn_errors_approved', 0),
259
				),
260
			);
261
		}
262
		else if ($this->request->is_set('add'))
263
		{
264
			$args['action'] = 'add';
265
		}
266
		else if ($this->request->is_set_post('change'))
267
		{
268
			$args['action'] = 'change';
269
		}
270
271
		return $args;
272
	}
273
274
	/**
275
	 * Does the action regarding the action provided
276
	 *
277
	 * @param array $args Array of arguments required for the action
278
	 *
279
	 * @return string
280
	 * @access private
281
	 */
282
	private function do_action($args)
283
	{
284
		switch ($args['action'])
285
		{
286
			case 'view':
287
				// Request Identifier of the transaction
288
				$transaction_id = $this->request->variable('id', 0);
289
290
				// add field username to the table schema needed by entity->import()
291
				$additional_table_schema = array(
292
					'item_username'    => array('name' => 'username', 'type' => 'string'),
293
					'item_user_colour' => array('name' => 'user_colour', 'type' => 'string'),
294
				);
295
296
				// Grab transaction data
297
				$data_ary = $this->ppde_entity->get_data($this->ppde_operator->build_sql_data($transaction_id), $additional_table_schema);
298
299
				array_map(array($this, 'action_assign_template_vars'), $data_ary);
300
301
				$this->template->assign_vars(array(
302
					'U_FIND_USERNAME' => append_sid($this->phpbb_root_path . 'memberlist.' . $this->php_ext, 'mode=searchuser&amp;form=view_transactions&amp;field=username&amp;select_single=true'),
303
					'U_ACTION'        => $this->u_action,
304
					'U_BACK'          => $this->u_action,
305
					'S_VIEW'          => true,
306
				));
307
			break;
308
			case 'delete':
309
				if (confirm_box(true))
310
				{
311
					$where_sql = '';
312
313
					if ($args['hidden_fields']['delmarked'] && count($args['hidden_fields']['mark']))
314
					{
315
						$where_sql = $this->ppde_operator->build_marked_where_sql($args['hidden_fields']['mark']);
316
					}
317
318
					if ($where_sql || $args['hidden_fields']['delall'])
319
					{
320
						$this->ppde_entity->delete(0, '', $where_sql, $args['hidden_fields']['delall']);
321
						$this->ppde_actions->set_ipn_test_properties(true);
322
						$this->ppde_actions->update_overview_stats();
323
						$this->ppde_actions->set_ipn_test_properties(false);
324
						$this->ppde_actions->update_overview_stats();
325
						$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_' . $this->lang_key_prefix . '_PURGED', time());
326
					}
327
				}
328
				else
329
				{
330
					confirm_box(false, $this->language->lang('CONFIRM_OPERATION'), build_hidden_fields($args['hidden_fields']));
331
				}
332
				// Clear $action status
333
				$args['action'] = '';
334
			break;
335
			case 'approve':
336
				if (confirm_box(true))
337
				{
338
					$transaction_id = (int) $args['hidden_fields']['id'];
339
					$txn_approved = !empty($args['hidden_fields']['txn_errors_approved']) ? false : true;
340
341
					// Update DB record
342
					$this->ppde_entity->load($transaction_id);
343
					$this->ppde_entity->set_txn_errors_approved($txn_approved);
344
					$this->ppde_entity->save(false);
345
346
					// Prepare transaction settings before doing actions
347
					$this->ppde_actions->set_transaction_data($this->ppde_entity->get_data($this->ppde_operator->build_sql_data($transaction_id)));
348
					$this->ppde_actions->set_ipn_test_properties($this->ppde_entity->get_test_ipn());
349
					$this->ppde_actions->is_donor_is_member();
350
351
					$this->do_transactions_actions(!$this->ppde_actions->get_ipn_test() && $this->ppde_actions->get_donor_is_member());
352
353
					$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_' . $this->lang_key_prefix . '_UPDATED', time());
354
				}
355
				else
356
				{
357
					confirm_box(false, $this->language->lang('CONFIRM_OPERATION'), build_hidden_fields($args['hidden_fields']));
358
				}
359
				// Clear $action status
360
				$args['action'] = '';
361
			break;
362
			case 'add':
363
				$errors = array();
364
365
				$transaction_data = $this->request_transaction_vars();
366
367
				if ($this->request->is_set_post('submit'))
368
				{
369
					try
370
					{
371
						$data_ary = $this->build_data_ary($transaction_data);
372
373
						$this->ppde_actions->log_to_db($data_ary);
374
375
						// Prepare transaction settings before doing actions
376
						$this->ppde_actions->set_transaction_data($transaction_data);
377
						$this->ppde_actions->is_donor_is_member();
378
379
						$this->do_transactions_actions($this->ppde_actions->get_donor_is_member() && !$transaction_data['MT_ANONYMOUS']);
380
381
						$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_PPDE_MT_ADDED', time(), array($transaction_data['MT_USERNAME']));
382
						trigger_error($this->language->lang('PPDE_MT_ADDED') . adm_back_link($this->u_action));
383
					}
384
					catch (transaction_exception $e)
385
					{
386
						$errors = $e->get_errors();
387
					}
388
				}
389
390
				$this->ppde_actions_currency->build_currency_select_menu((int) $this->config['ppde_default_currency']);
391
392
				$this->s_error_assign_template_vars($errors);
393
394
				$this->template->assign_vars($transaction_data);
395
396
				$this->template->assign_vars(array(
397
					'U_ACTION'             => $this->u_action,
398
					'U_BACK'               => $this->u_action,
399
					'S_ADD'                => true,
400
					'ANONYMOUS_USER_ID'    => ANONYMOUS,
401
					'U_FIND_USERNAME'      => append_sid($this->phpbb_root_path . 'memberlist.' . $this->php_ext, 'mode=searchuser&amp;form=manual_transaction&amp;field=username&amp;select_single=true'),
402
					'PAYMENT_TIME_FORMATS' => $this->get_payment_time_examples(),
403
				));
404
			break;
405
			case 'change':
406
407
				$username = $this->request->variable('username', '', true);
408
409
				if ($this->request->is_set('u') && $username === '')
410
				{
411
					$user_id = ANONYMOUS;
412
				}
413
				else
414
				{
415
					$user_id = $this->user_loader->load_user_by_username($username);
416
417
					if ($user_id == ANONYMOUS)
418
					{
419
						trigger_error($this->language->lang('NO_USER') . adm_back_link($this->u_action), E_USER_WARNING);
420
					}
421
				}
422
423
				// Request Identifier of the transaction
424
				$transaction_id = $this->request->variable('id', 0);
425
426
				$this->ppde_entity->load($transaction_id);
427
428
				if (!$this->ppde_entity->data_exists($this->ppde_entity->build_sql_data_exists()))
429
				{
430
					trigger_error($this->language->lang('PPDE_DT_NO_TRANSACTION') . adm_back_link($this->u_action), E_USER_WARNING);
431
				}
432
433
				$log_action = $this->ppde_entity
434
					->set_user_id($user_id)
435
					->add_edit_data()
436
				;
437
438
				$this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_' . $this->lang_key_prefix . '_' . strtoupper($log_action));
439
				trigger_error($this->language->lang($this->lang_key_prefix . '_' . strtoupper($log_action)) . adm_back_link($this->u_action));
440
			break;
441
		}
442
443
		return $args['action'];
444
	}
445
446
	/**
447
	 * Does actions for validated transaction
448
	 *
449
	 * @param bool $is_member
450
	 *
451
	 * @return void
452
	 * @access private
453
	 */
454
	private function do_transactions_actions($is_member)
455
	{
456
		$this->ppde_actions->update_overview_stats();
457
		$this->ppde_actions->update_raised_amount();
458
459
		if ($is_member)
460
		{
461
			$this->ppde_actions->update_donor_stats();
462
			$this->ppde_actions->donors_group_user_add();
463
			$this->ppde_actions->notification->notify_donor_donation_received();
464
		}
465
	}
466
467
	/**
468
	 * Returns requested data from manual transaction form
469
	 *
470
	 * @return array
471
	 * @access private
472
	 */
473
	private function request_transaction_vars()
474
	{
475
		return array(
476
			'MT_ANONYMOUS'          => $this->request->is_set('u'),
477
			'MT_USERNAME'           => $this->request->variable('username', '', true),
478
			'MT_FIRST_NAME'         => $this->request->variable('first_name', '', true),
479
			'MT_LAST_NAME'          => $this->request->variable('last_name', '', true),
480
			'MT_PAYER_EMAIL'        => $this->request->variable('payer_email', '', true),
481
			'MT_RESIDENCE_COUNTRY'  => $this->request->variable('residence_country', ''),
482
			'MT_MC_GROSS'           => $this->request->variable('mc_gross', (float) 0),
483
			'MT_MC_CURRENCY'        => $this->request->variable('mc_currency', ''),
484
			'MT_MC_FEE'             => $this->request->variable('mc_fee', (float) 0),
485
			'MT_PAYMENT_DATE_YEAR'  => $this->request->variable('payment_date_year', (int) $this->user->format_date(time(), 'Y')),
486
			'MT_PAYMENT_DATE_MONTH' => $this->request->variable('payment_date_month', (int) $this->user->format_date(time(), 'n')),
487
			'MT_PAYMENT_DATE_DAY'   => $this->request->variable('payment_date_day', (int) $this->user->format_date(time(), 'j')),
488
			'MT_PAYMENT_TIME'       => $this->request->variable('payment_time', $this->user->format_date(time(), 'H:i:s')),
489
			'MT_MEMO'               => $this->request->variable('memo', '', true),
490
		);
491
	}
492
493
	/**
494
	 * Returns a list of valid times that the user can provide in the manual transaction form
495
	 *
496
	 * @return array Array of strings representing the current time, each in a different format
497
	 * @access private
498
	 */
499
	private function get_payment_time_examples()
500
	{
501
		$formats = array(
502
			'H:i:s',
503
			'G:i',
504
			'h:i:s a',
505
			'g:i A',
506
		);
507
508
		$examples = array();
509
510
		foreach ($formats as $format)
511
		{
512
			$examples[] = $this->user->format_date(time(), $format);
513
		}
514
515
		return $examples;
516
	}
517
518
	/**
519
	 * View log
520
	 *
521
	 * @param array  &$log         The result array with the logs
522
	 * @param mixed  &$log_count   If $log_count is set to false, we will skip counting all entries in the
523
	 *                             database. Otherwise an integer with the number of total matching entries is returned.
524
	 * @param int     $limit       Limit the number of entries that are returned
525
	 * @param int     $offset      Offset when fetching the log entries, f.e. when paginating
526
	 * @param int     $limit_days
527
	 * @param string  $sort_by     SQL order option, e.g. 'l.log_time DESC'
528
	 * @param string  $keywords    Will only return log entries that have the keywords in log_operation or log_data
529
	 *
530
	 * @return int Returns the offset of the last valid page, if the specified offset was invalid (too high)
531
	 * @access private
532
	 */
533
	private function view_txn_log(&$log, &$log_count, $limit = 0, $offset = 0, $limit_days = 0, $sort_by = 'txn.payment_date DESC', $keywords = '')
534
	{
535
		$count_logs = ($log_count !== false);
536
537
		$log = $this->get_logs($count_logs, $limit, $offset, $limit_days, $sort_by, $keywords);
538
		$log_count = $this->get_log_count();
539
540
		return $this->get_valid_offset();
541
	}
542
543
	/**
544
	 * @param bool   $count_logs
545
	 * @param int    $limit
546
	 * @param int    $offset
547
	 * @param int    $log_time
548
	 * @param string $sort_by
549
	 * @param string $keywords
550
	 *
551
	 * @return array $log
552
	 * @access private
553
	 */
554
	private function get_logs($count_logs = true, $limit = 0, $offset = 0, $log_time = 0, $sort_by = 'txn.payment_date DESC', $keywords = '')
555
	{
556
		$this->entry_count = 0;
557
		$this->last_page_offset = $offset;
558
		$url_ary = array();
559
560
		if ($this->ppde_entity->is_in_admin() && $this->phpbb_admin_path)
561
		{
562
			$url_ary['profile_url'] = append_sid($this->phpbb_admin_path . 'index.' . $this->php_ext, 'i=users&amp;mode=overview');
563
			$url_ary['txn_url'] = append_sid($this->phpbb_admin_path . 'index.' . $this->php_ext, 'i=-skouat-ppde-acp-ppde_module&amp;mode=transactions');
564
565
		}
566
		else
567
		{
568
			$url_ary['profile_url'] = append_sid($this->phpbb_root_path . 'memberlist.' . $this->php_ext, 'mode=viewprofile');
569
			$url_ary['txn_url'] = '';
570
		}
571
572
		$get_logs_sql_ary = $this->ppde_operator->get_logs_sql_ary($keywords, $sort_by, $log_time);
573
574
		if ($count_logs)
575
		{
576
			$this->entry_count = $this->ppde_operator->query_sql_count($get_logs_sql_ary, 'txn.transaction_id');
577
578
			if ($this->entry_count == 0)
579
			{
580
				// Save the queries, because there are no logs to display
581
				$this->last_page_offset = 0;
582
583
				return array();
584
			}
585
586
			// Return the user to the last page that is valid
587
			while ($this->last_page_offset >= $this->entry_count)
588
			{
589
				$this->last_page_offset = max(0, $this->last_page_offset - $limit);
590
			}
591
		}
592
593
		return $this->ppde_operator->build_log_ary($get_logs_sql_ary, $url_ary, $limit, $this->last_page_offset);
594
	}
595
596
	/**
597
	 * @return integer
598
	 */
599
	public function get_log_count()
600
	{
601
		return ($this->entry_count) ? (int) $this->entry_count : 0;
602
	}
603
604
	/**
605
	 * @return integer
606
	 */
607
	public function get_valid_offset()
608
	{
609
		return ($this->last_page_offset) ? (int) $this->last_page_offset : 0;
610
	}
611
612
	/**
613
	 * Prepare data array() before send it to $this->entity
614
	 *
615
	 * @param array $transaction_data
616
	 *
617
	 * @return array
618
	 * @throws transaction_exception
619
	 */
620
	private function build_data_ary($transaction_data)
621
	{
622
		$errors = array();
623
624
		if ($this->request->is_set('u') && $transaction_data['MT_USERNAME'] === '')
625
		{
626
			$user_id = ANONYMOUS;
627
		}
628
		else
629
		{
630
			$user_ary = $this->ppde_operator->query_donor_user_data('username', $transaction_data['MT_USERNAME']);
631
632
			if ($user_ary)
633
			{
634
				$user_id = $user_ary['user_id'];
635
			}
636
			else
637
			{
638
				$errors[] = $this->language->lang('PPDE_MT_DONOR_NOT_FOUND', $transaction_data['MT_USERNAME']);
639
			}
640
		}
641
642
		if ($transaction_data['MT_MC_GROSS'] <= 0)
643
		{
644
			$errors[] = $this->language->lang('PPDE_MT_MC_GROSS_TOO_LOW');
645
		}
646
647
		if ($transaction_data['MT_MC_FEE'] < 0)
648
		{
649
			$errors[] = $this->language->lang('PPDE_MT_MC_FEE_NEGATIVE');
650
		}
651
652
		if ($transaction_data['MT_MC_FEE'] >= $transaction_data['MT_MC_GROSS'])
653
		{
654
			$errors[] = $this->language->lang('PPDE_MT_MC_FEE_TOO_HIGH');
655
		}
656
657
		$payment_date = implode('-', [
658
			$transaction_data['MT_PAYMENT_DATE_YEAR'],
659
			$transaction_data['MT_PAYMENT_DATE_MONTH'],
660
			$transaction_data['MT_PAYMENT_DATE_DAY'],
661
		]);
662
663
		$payment_date_timestamp_at_midnight = $this->user->get_timestamp_from_format('Y-m-d H:i:s', $payment_date . ' 00:00:00');
664
665
		if ($payment_date_timestamp_at_midnight === false)
0 ignored issues
show
introduced by
The condition $payment_date_timestamp_at_midnight === false is always false.
Loading history...
666
		{
667
			$errors[] = $this->language->lang('PPDE_MT_PAYMENT_DATE_ERROR', $payment_date);
668
		}
669
670
		$payment_time = $transaction_data['MT_PAYMENT_TIME'];
671
		$payment_time_timestamp = strtotime($payment_time);
672
673
		if ($payment_time_timestamp === false)
674
		{
675
			$errors[] = $this->language->lang('PPDE_MT_PAYMENT_TIME_ERROR', $payment_time);
676
		}
677
678
		// Normalize payment time to start from today at midnight
679
		$payment_time_timestamp_from_midnight = $payment_time_timestamp - strtotime('00:00:00');
680
681
		$payment_date_time = $payment_date_timestamp_at_midnight + $payment_time_timestamp_from_midnight;
682
683
		if ($payment_date_time > time())
684
		{
685
			$errors[] = $this->language->lang('PPDE_MT_PAYMENT_DATE_FUTURE', $this->user->format_date($payment_date_time));
686
		}
687
688
		if ($errors)
689
		{
690
			throw (new transaction_exception())->set_errors($errors);
691
		}
692
693
		return array(
694
			'business'          => $this->config['ppde_account_id'],
695
			'confirmed'         => true,
696
			'exchange_rate'     => '',
697
			'first_name'        => $transaction_data['MT_FIRST_NAME'],
698
			'item_name'         => '',
699
			'item_number'       => implode('_', ['uid', $user_id, time()]),
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $user_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
700
			'last_name'         => $transaction_data['MT_LAST_NAME'],
701
			'mc_currency'       => $transaction_data['MT_MC_CURRENCY'],
702
			'mc_gross'          => $transaction_data['MT_MC_GROSS'],
703
			'mc_fee'            => $transaction_data['MT_MC_FEE'],
704
			'net_amount'        => (float) 0, // This value is calculated in core_actions:log_to_db()
705
			'parent_txn_id'     => '',
706
			'payer_email'       => $transaction_data['MT_PAYER_EMAIL'],
707
			'payer_id'          => '',
708
			'payer_status'      => '',
709
			'payment_date'      => $payment_date_time,
710
			'payment_status'    => 'Completed',
711
			'payment_type'      => '',
712
			'memo'              => $transaction_data['MT_MEMO'],
713
			'receiver_id'       => '',
714
			'receiver_email'    => '',
715
			'residence_country' => strtoupper($transaction_data['MT_RESIDENCE_COUNTRY']),
716
			'settle_amount'     => (float) 0,
717
			'settle_currency'   => '',
718
			'test_ipn'          => false,
719
			'txn_errors'        => '',
720
			'txn_id'            => 'PPDE' . gen_rand_string(13),
721
			'txn_type'          => 'ppde_manual_donation',
722
			'user_id'           => $user_id,
723
		);
724
	}
725
726
	/**
727
	 * Set log output vars for display in the template
728
	 *
729
	 * @param array $row
730
	 *
731
	 * @return void
732
	 * @access protected
733
	 */
734
	protected function display_log_assign_template_vars($row)
735
	{
736
		$this->template->assign_block_vars('log', array(
737
			'CONFIRMED'        => ($row['confirmed']) ? $this->language->lang('PPDE_DT_VERIFIED') : $this->language->lang('PPDE_DT_UNVERIFIED'),
738
			'DATE'             => $this->user->format_date($row['payment_date']),
739
			'ID'               => $row['transaction_id'],
740
			'PAYMENT_STATUS'   => $this->language->lang(array('PPDE_DT_PAYMENT_STATUS_VALUES', strtolower($row['payment_status']))),
741
			'TNX_ID'           => $row['txn_id'],
742
			'USERNAME'         => $row['username_full'],
743
			'S_CONFIRMED'      => (bool) $row['confirmed'],
744
			'S_PAYMENT_STATUS' => (strtolower($row['payment_status']) === 'completed') ? true : false,
745
			'S_TXN_ERRORS'     => !empty($row['txn_errors']),
746
			'S_TEST_IPN'       => (bool) $row['test_ipn'],
747
		));
748
	}
749
750
	/**
751
	 * Set output vars for display in the template
752
	 *
753
	 * @param array $data
754
	 *
755
	 * @return void
756
	 * @access protected
757
	 */
758
	protected function action_assign_template_vars($data)
759
	{
760
		$s_hidden_fields = build_hidden_fields(array(
761
			'id'                  => $data['transaction_id'],
762
			'txn_errors_approved' => $data['txn_errors_approved'],
763
		));
764
765
		$currency_mc_data = $this->ppde_actions_currency->get_currency_data($data['mc_currency']);
766
		$currency_settle_data = $this->ppde_actions_currency->get_currency_data($data['settle_currency']);
767
768
		$this->template->assign_vars(array(
769
			'BOARD_USERNAME' => get_username_string('full', $data['user_id'], $data['username'], $data['user_colour'], $this->language->lang('GUEST'), append_sid($this->phpbb_admin_path . 'index.' . $this->php_ext, 'i=users&amp;mode=overview')),
770
			'EXCHANGE_RATE'  => '1 ' . $data['mc_currency'] . ' = ' . $data['exchange_rate'] . ' ' . $data['settle_currency'],
771
			'ITEM_NAME'      => $data['item_name'],
772
			'ITEM_NUMBER'    => $data['item_number'],
773
			'MC_GROSS'       => $this->ppde_actions_currency->format_currency($data['mc_gross'], $currency_mc_data[0]['currency_iso_code'], $currency_mc_data[0]['currency_symbol'], (bool) $currency_mc_data[0]['currency_on_left']),
774
			'MC_FEE'         => $this->ppde_actions_currency->format_currency($data['mc_fee'], $currency_mc_data[0]['currency_iso_code'], $currency_mc_data[0]['currency_symbol'], (bool) $currency_mc_data[0]['currency_on_left']),
775
			'MC_NET'         => $this->ppde_actions_currency->format_currency($data['net_amount'], $currency_mc_data[0]['currency_iso_code'], $currency_mc_data[0]['currency_symbol'], (bool) $currency_mc_data[0]['currency_on_left']),
776
			'MEMO'           => $data['memo'],
777
			'NAME'           => $data['first_name'] . ' ' . $data['last_name'],
778
			'PAYER_EMAIL'    => $data['payer_email'],
779
			'PAYER_ID'       => $data['payer_id'],
780
			'PAYER_STATUS'   => $data['payer_status'] ? $this->language->lang('PPDE_DT_VERIFIED') : $this->language->lang('PPDE_DT_UNVERIFIED'),
781
			'PAYMENT_DATE'   => $this->user->format_date($data['payment_date']),
782
			'PAYMENT_STATUS' => $this->language->lang(array('PPDE_DT_PAYMENT_STATUS_VALUES', strtolower($data['payment_status']))),
783
			'RECEIVER_EMAIL' => $data['receiver_email'],
784
			'RECEIVER_ID'    => $data['receiver_id'],
785
			'SETTLE_AMOUNT'  => $this->ppde_actions_currency->format_currency($data['settle_amount'], $currency_settle_data[0]['currency_iso_code'], $currency_settle_data[0]['currency_symbol'], (bool) $currency_settle_data[0]['currency_on_left']),
786
			'TXN_ID'         => $data['txn_id'],
787
788
			'L_PPDE_DT_SETTLE_AMOUNT'         => $this->language->lang('PPDE_DT_SETTLE_AMOUNT', $data['settle_currency']),
789
			'L_PPDE_DT_EXCHANGE_RATE_EXPLAIN' => $this->language->lang('PPDE_DT_EXCHANGE_RATE_EXPLAIN', $this->user->format_date($data['payment_date'])),
790
			'S_CONVERT'                       => ($data['settle_amount'] == 0 && empty($data['exchange_rate'])) ? false : true,
791
			'S_ERROR'                         => !empty($data['txn_errors']),
792
			'S_ERROR_APPROVED'                => !empty($data['txn_errors_approved']),
793
			'S_HIDDEN_FIELDS'                 => $s_hidden_fields,
794
			'ERROR_MSG'                       => (!empty($data['txn_errors'])) ? $data['txn_errors'] : '',
795
		));
796
	}
797
}
798