Passed
Push — release-2.1 ( 0c2197...207d2d )
by Jeremy
05:47
created

ManagePaid.php ➔ ModifySubscription()   F

Complexity

Conditions 51
Paths > 20000

Size

Total Lines 350

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 51
nc 429496.7295
nop 0
dl 0
loc 350
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains all the administration functions for subscriptions.
5
 * (and some more than that :P)
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines http://www.simplemachines.org
11
 * @copyright 2018 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * The main entrance point for the 'Paid Subscription' screen, calling
22
 * the right function based on the given sub-action.
23
 * It defaults to sub-action 'view'.
24
 * Accessed from ?action=admin;area=paidsubscribe.
25
 * It requires admin_forum permission for admin based actions.
26
 */
27
function ManagePaidSubscriptions()
28
{
29
	global $context, $txt, $modSettings;
30
31
	// Load the required language and template.
32
	loadLanguage('ManagePaid');
33
	loadTemplate('ManagePaid');
34
35
	if (!empty($modSettings['paid_enabled']))
36
		$subActions = array(
37
			'modify' => array('ModifySubscription', 'admin_forum'),
38
			'modifyuser' => array('ModifyUserSubscription', 'admin_forum'),
39
			'settings' => array('ModifySubscriptionSettings', 'admin_forum'),
40
			'view' => array('ViewSubscriptions', 'admin_forum'),
41
			'viewsub' => array('ViewSubscribedUsers', 'admin_forum'),
42
		);
43
	else
44
		$subActions = array(
45
			'settings' => array('ModifySubscriptionSettings', 'admin_forum'),
46
		);
47
48
	// Default the sub-action to 'view subscriptions', but only if they have already set things up..
49
	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : (!empty($modSettings['paid_currency_symbol']) && !empty($modSettings['paid_enabled']) ? 'view' : 'settings');
50
51
	// Make sure you can do this.
52
	isAllowedTo($subActions[$_REQUEST['sa']][1]);
53
54
	$context['page_title'] = $txt['paid_subscriptions'];
55
56
	// Tabs for browsing the different subscription functions.
57
	$context[$context['admin_menu_name']]['tab_data'] = array(
58
		'title' => $txt['paid_subscriptions'],
59
		'help' => '',
60
		'description' => $txt['paid_subscriptions_desc'],
61
	);
62
	if (!empty($modSettings['paid_enabled']))
63
		$context[$context['admin_menu_name']]['tab_data']['tabs'] = array(
64
			'view' => array(
65
				'description' => $txt['paid_subs_view_desc'],
66
			),
67
			'settings' => array(
68
				'description' => $txt['paid_subs_settings_desc'],
69
			),
70
		);
71
72
	call_integration_hook('integrate_manage_subscriptions', array(&$subActions));
73
74
	// Call the right function for this sub-action.
75
	call_helper($subActions[$_REQUEST['sa']][0]);
76
}
77
78
/**
79
 * Set any setting related to paid subscriptions, i.e.
80
 * modify which payment methods are to be used.
81
 * It requires the moderate_forum permission
82
 * Accessed from ?action=admin;area=paidsubscribe;sa=settings.
83
 *
84
 * @param bool $return_config Whether or not to return the $config_vars array (used for admin search)
85
 * @return void|array Returns nothing or returns the config_vars array if $return_config is true
86
 */
87
function ModifySubscriptionSettings($return_config = false)
88
{
89
	global $context, $txt, $modSettings, $sourcedir, $smcFunc, $scripturl;
90
91
	if (!empty($modSettings['paid_enabled']))
92
	{
93
		// If the currency is set to something different then we need to set it to other for this to work and set it back shortly.
94
		$modSettings['paid_currency'] = !empty($modSettings['paid_currency_code']) ? $modSettings['paid_currency_code'] : '';
95
		if (!empty($modSettings['paid_currency_code']) && !in_array($modSettings['paid_currency_code'], array('usd', 'eur', 'gbp', 'cad', 'aud')))
96
			$modSettings['paid_currency'] = 'other';
97
98
		// These are all the default settings.
99
		$config_vars = array(
100
				array('check', 'paid_enabled'),
101
			'',
102
				array('select', 'paid_email', array(0 => $txt['paid_email_no'], 1 => $txt['paid_email_error'], 2 => $txt['paid_email_all']), 'subtext' => $txt['paid_email_desc']),
103
				array('email', 'paid_email_to', 'subtext' => $txt['paid_email_to_desc'], 'size' => 60),
104
			'',
105
				'dummy_currency' => array('select', 'paid_currency', array('usd' => $txt['usd'], 'eur' => $txt['eur'], 'gbp' => $txt['gbp'], 'cad' => $txt['cad'], 'aud' => $txt['aud'], 'other' => $txt['other']), 'javascript' => 'onchange="toggleOther();"'),
106
				array('text', 'paid_currency_code', 'subtext' => $txt['paid_currency_code_desc'], 'size' => 5, 'force_div_id' => 'custom_currency_code_div'),
107
				array('text', 'paid_currency_symbol', 'subtext' => $txt['paid_currency_symbol_desc'], 'size' => 8, 'force_div_id' => 'custom_currency_symbol_div'),
108
				array('check', 'paidsubs_test', 'subtext' => $txt['paidsubs_test_desc'], 'onclick' => 'return document.getElementById(\'paidsubs_test\').checked ? confirm(\'' . $txt['paidsubs_test_confirm'] . '\') : true;'),
109
		);
110
111
		// Now load all the other gateway settings.
112
		$gateways = loadPaymentGateways();
113
		foreach ($gateways as $gateway)
114
		{
115
			$gatewayClass = new $gateway['display_class']();
116
			$setting_data = $gatewayClass->getGatewaySettings();
117
			if (!empty($setting_data))
118
			{
119
				$config_vars[] = array('title', $gatewayClass->title, 'text_label' => (isset($txt['paidsubs_gateway_title_' . $gatewayClass->title]) ? $txt['paidsubs_gateway_title_' . $gatewayClass->title] : $gatewayClass->title));
120
				$config_vars = array_merge($config_vars, $setting_data);
121
			}
122
		}
123
124
		$context['settings_message'] = $txt['paid_note'];
125
		$context[$context['admin_menu_name']]['current_subsection'] = 'settings';
126
		$context['settings_title'] = $txt['settings'];
127
128
		// We want javascript for our currency options.
129
		addInlineJavaScript('
130
		function toggleOther()
131
		{
132
			var otherOn = document.getElementById("paid_currency").value == \'other\';
133
			var currencydd = document.getElementById("custom_currency_code_div_dd");
134
135
			if (otherOn)
136
			{
137
				document.getElementById("custom_currency_code_div").style.display = "";
138
				document.getElementById("custom_currency_symbol_div").style.display = "";
139
140
				if (currencydd)
141
				{
142
					document.getElementById("custom_currency_code_div_dd").style.display = "";
143
					document.getElementById("custom_currency_symbol_div_dd").style.display = "";
144
				}
145
			}
146
			else
147
			{
148
				document.getElementById("custom_currency_code_div").style.display = "none";
149
				document.getElementById("custom_currency_symbol_div").style.display = "none";
150
151
				if (currencydd)
152
				{
153
					document.getElementById("custom_currency_symbol_div_dd").style.display = "none";
154
					document.getElementById("custom_currency_code_div_dd").style.display = "none";
155
				}
156
			}
157
		}
158
		toggleOther();', true);
159
	}
160
	else
161
	{
162
		$config_vars = array(
163
			array('check', 'paid_enabled'),
164
		);
165
		$context['settings_title'] = $txt['paid_subscriptions'];
166
	}
167
168
	// Just searching?
169
	if ($return_config)
170
		return $config_vars;
171
172
	// Get the settings template fired up.
173
	require_once($sourcedir . '/ManageServer.php');
174
175
	// Some important context stuff
176
	$context['page_title'] = $txt['settings'];
177
	$context['sub_template'] = 'show_settings';
178
179
	// Get the final touches in place.
180
	$context['post_url'] = $scripturl . '?action=admin;area=paidsubscribe;save;sa=settings';
181
182
	// Saving the settings?
183
	if (isset($_GET['save']))
184
	{
185
		checkSession();
186
187
		$old = !empty($modSettings['paid_enabled']);
188
		$new = !empty($_POST['paid_enabled']);
189
		if ($old != $new)
190
		{
191
			// So we're changing this fundamental status. Great.
192
			$smcFunc['db_query']('', '
193
				UPDATE {db_prefix}scheduled_tasks
194
				SET disabled = {int:disabled}
195
				WHERE task = {string:task}',
196
				array(
197
					'disabled' => $new ? 0 : 1,
198
					'task' => 'paid_subscriptions',
199
				)
200
			);
201
202
			// This may well affect the next trigger, whether we're enabling or not.
203
			require_once($sourcedir . '/ScheduledTasks.php');
204
			CalculateNextTrigger('paid_subscriptions');
205
		}
206
207
		// Check the email addresses were actually email addresses.
208
		if (!empty($_POST['paid_email_to']))
209
		{
210
			$email_addresses = array();
211
			foreach (explode(',', $_POST['paid_email_to']) as $email)
212
			{
213
				$email = trim($email);
214
				if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL))
215
					$email_addresses[] = $email;
216
				$_POST['paid_email_to'] = implode(',', $email_addresses);
217
			}
218
		}
219
220
		// Can only handle this stuff if it's already enabled...
221
		if (!empty($modSettings['paid_enabled']))
222
		{
223
			// Sort out the currency stuff.
224
			if ($_POST['paid_currency'] != 'other')
225
			{
226
				$_POST['paid_currency_code'] = $_POST['paid_currency'];
227
				$_POST['paid_currency_symbol'] = $txt[$_POST['paid_currency'] . '_symbol'];
228
			}
229
			unset($config_vars['dummy_currency']);
230
		}
231
232
		saveDBSettings($config_vars);
233
		$_SESSION['adm-save'] = true;
234
235
		redirectexit('action=admin;area=paidsubscribe;sa=settings');
236
	}
237
238
	// Prepare the settings...
239
	prepareDBSettingContext($config_vars);
240
}
241
242
/**
243
 * View a list of all the current subscriptions
244
 * Requires the admin_forum permission.
245
 * Accessed from ?action=admin;area=paidsubscribe;sa=view.
246
 */
247
function ViewSubscriptions()
248
{
249
	global $context, $txt, $modSettings, $sourcedir, $scripturl;
250
251
	// Not made the settings yet?
252
	if (empty($modSettings['paid_currency_symbol']))
253
		fatal_lang_error('paid_not_set_currency', false, $scripturl . '?action=admin;area=paidsubscribe;sa=settings');
0 ignored issues
show
Bug introduced by
$scripturl . '?action=ad...dsubscribe;sa=settings' of type string is incompatible with the type array expected by parameter $sprintf of fatal_lang_error(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

253
		fatal_lang_error('paid_not_set_currency', false, /** @scrutinizer ignore-type */ $scripturl . '?action=admin;area=paidsubscribe;sa=settings');
Loading history...
254
255
	// Some basic stuff.
256
	$context['page_title'] = $txt['paid_subs_view'];
257
	loadSubscriptions();
258
259
	$listOptions = array(
260
		'id' => 'subscription_list',
261
		'title' => $txt['subscriptions'],
262
		'items_per_page' => $modSettings['defaultMaxListItems'],
263
		'base_href' => $scripturl . '?action=admin;area=paidsubscribe;sa=view',
264
		'get_items' => array(
265
			'function' => function($start, $items_per_page) use ($context)
266
			{
267
				$subscriptions = array();
268
				$counter = 0;
269
				$start++;
270
271
				foreach ($context['subscriptions'] as $data)
272
				{
273
					if (++$counter < $start)
274
						continue;
275
					elseif ($counter == $start + $items_per_page)
276
						break;
277
278
					$subscriptions[] = $data;
279
				}
280
				return $subscriptions;
281
			},
282
		),
283
		'get_count' => array(
284
			'function' => function() use ($context)
285
			{
286
				return count($context['subscriptions']);
287
			},
288
		),
289
		'no_items_label' => $txt['paid_none_yet'],
290
		'columns' => array(
291
			'name' => array(
292
				'header' => array(
293
					'value' => $txt['paid_name'],
294
					'style' => 'width: 35%;',
295
				),
296
				'data' => array(
297
					'function' => function($rowData) use ($scripturl)
298
					{
299
						return sprintf('<a href="%1$s?action=admin;area=paidsubscribe;sa=viewsub;sid=%2$s">%3$s</a>', $scripturl, $rowData['id'], $rowData['name']);
300
					},
301
				),
302
			),
303
			'cost' => array(
304
				'header' => array(
305
					'value' => $txt['paid_cost'],
306
				),
307
				'data' => array(
308
					'function' => function($rowData) use ($txt)
309
					{
310
						return $rowData['flexible'] ? '<em>' . $txt['flexible'] . '</em>' : $rowData['cost'] . ' / ' . $rowData['length'];
311
					},
312
				),
313
			),
314
			'pending' => array(
315
				'header' => array(
316
					'value' => $txt['paid_pending'],
317
					'style' => 'width: 18%;',
318
					'class' => 'centercol',
319
				),
320
				'data' => array(
321
					'db_htmlsafe' => 'pending',
322
					'class' => 'centercol',
323
				),
324
			),
325
			'finished' => array(
326
				'header' => array(
327
					'value' => $txt['paid_finished'],
328
					'class' => 'centercol',
329
				),
330
				'data' => array(
331
					'db_htmlsafe' => 'finished',
332
					'class' => 'centercol',
333
				),
334
			),
335
			'total' => array(
336
				'header' => array(
337
					'value' => $txt['paid_active'],
338
					'class' => 'centercol',
339
				),
340
				'data' => array(
341
					'db_htmlsafe' => 'total',
342
					'class' => 'centercol',
343
				),
344
			),
345
			'is_active' => array(
346
				'header' => array(
347
					'value' => $txt['paid_is_active'],
348
					'class' => 'centercol',
349
				),
350
				'data' => array(
351
					'function' => function($rowData) use ($txt)
352
					{
353
						return '<span style="color: ' . ($rowData['active'] ? 'green' : 'red') . '">' . ($rowData['active'] ? $txt['yes'] : $txt['no']) . '</span>';
354
					},
355
					'class' => 'centercol',
356
				),
357
			),
358
			'modify' => array(
359
				'data' => array(
360
					'function' => function($rowData) use ($txt, $scripturl)
361
					{
362
						return '<a href="' . $scripturl . '?action=admin;area=paidsubscribe;sa=modify;sid=' . $rowData['id'] . '">' . $txt['modify'] . '</a>';
363
					},
364
					'class' => 'centercol',
365
				),
366
			),
367
			'delete' => array(
368
				'data' => array(
369
					'function' => function($rowData) use ($scripturl, $txt)
370
					{
371
						return '<a href="' . $scripturl . '?action=admin;area=paidsubscribe;sa=modify;delete;sid=' . $rowData['id'] . '">' . $txt['delete'] . '</a>';
372
					},
373
					'class' => 'centercol',
374
				),
375
			),
376
		),
377
		'form' => array(
378
			'href' => $scripturl . '?action=admin;area=paidsubscribe;sa=modify',
379
		),
380
		'additional_rows' => array(
381
			array(
382
				'position' => 'above_table_headers',
383
				'value' => '<input type="submit" name="add" value="' . $txt['paid_add_subscription'] . '" class="button">',
384
			),
385
			array(
386
				'position' => 'below_table_data',
387
				'value' => '<input type="submit" name="add" value="' . $txt['paid_add_subscription'] . '" class="button">',
388
			),
389
		),
390
	);
391
392
	require_once($sourcedir . '/Subs-List.php');
393
	createList($listOptions);
394
395
	$context['sub_template'] = 'show_list';
396
	$context['default_list'] = 'subscription_list';
397
}
398
399
/**
400
 * Adding, editing and deleting subscriptions.
401
 * Accessed from ?action=admin;area=paidsubscribe;sa=modify.
402
 */
403
function ModifySubscription()
404
{
405
	global $context, $txt, $smcFunc;
406
407
	$context['sub_id'] = isset($_REQUEST['sid']) ? (int) $_REQUEST['sid'] : 0;
408
	$context['action_type'] = $context['sub_id'] ? (isset($_REQUEST['delete']) ? 'delete' : 'edit') : 'add';
409
410
	// Setup the template.
411
	$context['sub_template'] = $context['action_type'] == 'delete' ? 'delete_subscription' : 'modify_subscription';
412
	$context['page_title'] = $txt['paid_' . $context['action_type'] . '_subscription'];
413
414
	// Delete it?
415
	if (isset($_POST['delete_confirm']) && isset($_REQUEST['delete']))
416
	{
417
		checkSession();
418
		validateToken('admin-pmsd');
419
420
		// Before we delete the subscription we need to find out if anyone currently has said subscription.
421
		$request = $smcFunc['db_query']('', '
422
			SELECT ls.id_member, ls.old_id_group, mem.id_group, mem.additional_groups
423
			FROM {db_prefix}log_subscribed AS ls
424
				INNER JOIN {db_prefix}members AS mem ON (ls.id_member = mem.id_member)
425
			WHERE id_subscribe = {int:current_subscription}
426
				AND status = {int:is_active}',
427
			array(
428
				'current_subscription' => $context['sub_id'],
429
				'is_active' => 1,
430
			)
431
		);
432
		$members = array();
433
		while ($row = $smcFunc['db_fetch_assoc']($request))
434
		{
435
			$id_member = array_shift($row);
436
			$members[$id_member] = $row;
437
		}
438
		$smcFunc['db_free_result']($request);
439
440
		// If there are any members with this subscription, we have to do some more work before we go any further.
441
		if (!empty($members))
442
		{
443
			$request = $smcFunc['db_query']('', '
444
				SELECT id_group, add_groups
445
				FROM {db_prefix}subscriptions
446
				WHERE id_subscribe = {int:current_subscription}',
447
				array(
448
					'current_subscription' => $context['sub_id'],
449
				)
450
			);
451
			$id_group = 0;
452
			$add_groups = '';
453
			if ($smcFunc['db_num_rows']($request))
454
				list ($id_group, $add_groups) = $smcFunc['db_fetch_row']($request);
455
			$smcFunc['db_free_result']($request);
456
457
			$changes = array();
458
459
			// Is their group changing? This subscription may not have changed primary group.
460
			if (!empty($id_group))
461
			{
462
				foreach ($members as $id_member => $member_data)
463
				{
464
					// If their current primary group isn't what they had before the subscription, and their current group was
465
					// granted by the sub, remove it.
466
					if ($member_data['old_id_group'] != $member_data['id_group'] && $member_data['id_group'] == $id_group)
467
						$changes[$id_member]['id_group'] = $member_data['old_id_group'];
468
				}
469
			}
470
471
			// Did this subscription add secondary groups?
472
			if (!empty($add_groups))
473
			{
474
				$add_groups = explode(',', $add_groups);
475
				foreach ($members as $id_member => $member_data)
476
				{
477
					// First let's get their groups sorted.
478
					$current_groups = explode(',', $member_data['additional_groups']);
479
					$new_groups = implode(',', array_diff($current_groups, $add_groups));
480
					if ($new_groups != $member_data['additional_groups'])
481
						$changes[$id_member]['additional_groups'] = $new_groups;
482
				}
483
			}
484
485
			// We're going through changes...
486
			if (!empty($changes))
487
				foreach ($changes as $id_member => $new_values)
488
					updateMemberData($id_member, $new_values);
489
		}
490
491
		// Delete the subscription
492
		$smcFunc['db_query']('', '
493
			DELETE FROM {db_prefix}subscriptions
494
			WHERE id_subscribe = {int:current_subscription}',
495
			array(
496
				'current_subscription' => $context['sub_id'],
497
			)
498
		);
499
500
		// And delete any subscriptions to it to clear the phantom data too.
501
		$smcFunc['db_query']('', '
502
			DELETE FROM {db_prefix}log_subscribed
503
			WHERE id_subscribe = {int:current_subscription}',
504
			array(
505
				'current_subscription' => $context['sub_id'],
506
			)
507
		);
508
509
		call_integration_hook('integrate_delete_subscription', array($context['sub_id']));
510
511
		redirectexit('action=admin;area=paidsubscribe;view');
512
	}
513
514
	// Saving?
515
	if (isset($_POST['save']))
516
	{
517
		checkSession();
518
519
		// Some cleaning...
520
		$isActive = isset($_POST['active']) ? 1 : 0;
521
		$isRepeatable = isset($_POST['repeatable']) ? 1 : 0;
522
		$allowpartial = isset($_POST['allow_partial']) ? 1 : 0;
523
		$reminder = isset($_POST['reminder']) ? (int) $_POST['reminder'] : 0;
524
		$emailComplete = strlen($_POST['emailcomplete']) > 10 ? trim($_POST['emailcomplete']) : '';
525
526
		// Is this a fixed one?
527
		if ($_POST['duration_type'] == 'fixed')
528
		{
529
			// There are sanity check limits on these things.
530
			$limits = array(
531
				'D' => 90,
532
				'W' => 52,
533
				'M' => 24,
534
				'Y' => 5,
535
			);
536
			if (empty($_POST['span_unit']) || empty($limits[$_POST['span_unit']]) || empty($_POST['span_value']) || $_POST['span_value'] < 1)
537
				fatal_lang_error('paid_invalid_duration', false);
538
539
			if ($_POST['span_value'] > $limits[$_POST['span_unit']])
540
				fatal_lang_error('paid_invalid_duration_' . $_POST['span_unit'], false);
541
542
			// Clean the span.
543
			$span = $_POST['span_value'] . $_POST['span_unit'];
544
545
			// Sort out the cost.
546
			$cost = array('fixed' => sprintf('%01.2f', strtr($_POST['cost'], ',', '.')));
547
548
			// There needs to be something.
549
			if (empty($_POST['span_value']) || empty($_POST['cost']))
550
				fatal_lang_error('paid_no_cost_value');
551
		}
552
		// Flexible is harder but more fun ;)
553
		else
554
		{
555
			$span = 'F';
556
557
			$cost = array(
558
				'day' => sprintf('%01.2f', strtr($_POST['cost_day'], ',', '.')),
559
				'week' => sprintf('%01.2f', strtr($_POST['cost_week'], ',', '.')),
560
				'month' => sprintf('%01.2f', strtr($_POST['cost_month'], ',', '.')),
561
				'year' => sprintf('%01.2f', strtr($_POST['cost_year'], ',', '.')),
562
			);
563
564
			if (empty($_POST['cost_day']) && empty($_POST['cost_week']) && empty($_POST['cost_month']) && empty($_POST['cost_year']))
565
				fatal_lang_error('paid_all_freq_blank');
566
		}
567
		$cost = $smcFunc['json_encode']($cost);
568
569
		// Having now validated everything that might throw an error, let's also now deal with the token.
570
		validateToken('admin-pms');
571
572
		// Yep, time to do additional groups.
573
		$addgroups = array();
574
		if (!empty($_POST['addgroup']))
575
			foreach ($_POST['addgroup'] as $id => $dummy)
576
				$addgroups[] = (int) $id;
577
		$addgroups = implode(',', $addgroups);
578
579
		// Is it new?!
580
		if ($context['action_type'] == 'add')
581
		{
582
			$id_subscribe = $smcFunc['db_insert']('',
583
				'{db_prefix}subscriptions',
584
				array(
585
					'name' => 'string-60', 'description' => 'string-255', 'active' => 'int', 'length' => 'string-4', 'cost' => 'string',
586
					'id_group' => 'int', 'add_groups' => 'string-40', 'repeatable' => 'int', 'allow_partial' => 'int', 'email_complete' => 'string',
587
					'reminder' => 'int',
588
				),
589
				array(
590
					$_POST['name'], $_POST['desc'], $isActive, $span, $cost,
591
					$_POST['prim_group'], $addgroups, $isRepeatable, $allowpartial, $emailComplete,
592
					$reminder,
593
				),
594
				array('id_subscribe'),
595
				1
596
			);
597
		}
598
		// Otherwise must be editing.
599
		else
600
		{
601
			// Don't do groups if there are active members
602
			$request = $smcFunc['db_query']('', '
603
				SELECT COUNT(*)
604
				FROM {db_prefix}log_subscribed
605
				WHERE id_subscribe = {int:current_subscription}
606
					AND status = {int:is_active}',
607
				array(
608
					'current_subscription' => $context['sub_id'],
609
					'is_active' => 1,
610
				)
611
			);
612
			list ($disableGroups) = $smcFunc['db_fetch_row']($request);
613
			$smcFunc['db_free_result']($request);
614
615
			$smcFunc['db_query']('substring', '
616
				UPDATE {db_prefix}subscriptions
617
					SET name = SUBSTRING({string:name}, 1, 60), description = SUBSTRING({string:description}, 1, 255), active = {int:is_active},
618
					length = SUBSTRING({string:length}, 1, 4), cost = {string:cost}' . ($disableGroups ? '' : ', id_group = {int:id_group},
619
					add_groups = {string:additional_groups}') . ', repeatable = {int:repeatable}, allow_partial = {int:allow_partial},
620
					email_complete = {string:email_complete}, reminder = {int:reminder}
621
				WHERE id_subscribe = {int:current_subscription}',
622
				array(
623
					'is_active' => $isActive,
624
					'id_group' => !empty($_POST['prim_group']) ? $_POST['prim_group'] : 0,
625
					'repeatable' => $isRepeatable,
626
					'allow_partial' => $allowpartial,
627
					'reminder' => $reminder,
628
					'current_subscription' => $context['sub_id'],
629
					'name' => $_POST['name'],
630
					'description' => $_POST['desc'],
631
					'length' => $span,
632
					'cost' => $cost,
633
					'additional_groups' => !empty($addgroups) ? $addgroups : '',
634
					'email_complete' => $emailComplete,
635
				)
636
			);
637
		}
638
		call_integration_hook('integrate_save_subscription', array(($context['action_type'] == 'add' ? $id_subscribe : $context['sub_id']), $_POST['name'], $_POST['desc'], $isActive, $span, $cost, $_POST['prim_group'], $addgroups, $isRepeatable, $allowpartial, $emailComplete, $reminder));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $id_subscribe does not seem to be defined for all execution paths leading up to this point.
Loading history...
639
640
		redirectexit('action=admin;area=paidsubscribe;view');
641
	}
642
643
	// Defaults.
644
	if ($context['action_type'] == 'add')
645
	{
646
		$context['sub'] = array(
647
			'name' => '',
648
			'desc' => '',
649
			'cost' => array(
650
				'fixed' => 0,
651
			),
652
			'span' => array(
653
				'value' => '',
654
				'unit' => 'D',
655
			),
656
			'prim_group' => 0,
657
			'add_groups' => array(),
658
			'active' => 1,
659
			'repeatable' => 1,
660
			'allow_partial' => 0,
661
			'duration' => 'fixed',
662
			'email_complete' => '',
663
			'reminder' => 0,
664
		);
665
	}
666
	// Otherwise load up all the details.
667
	else
668
	{
669
		$request = $smcFunc['db_query']('', '
670
			SELECT name, description, cost, length, id_group, add_groups, active, repeatable, allow_partial, email_complete, reminder
671
			FROM {db_prefix}subscriptions
672
			WHERE id_subscribe = {int:current_subscription}
673
			LIMIT 1',
674
			array(
675
				'current_subscription' => $context['sub_id'],
676
			)
677
		);
678
		while ($row = $smcFunc['db_fetch_assoc']($request))
679
		{
680
			// Sort the date.
681
			preg_match('~(\d*)(\w)~', $row['length'], $match);
682
			if (isset($match[2]))
683
			{
684
				$span_value = $match[1];
685
				$span_unit = $match[2];
686
			}
687
			else
688
			{
689
				$span_value = 0;
690
				$span_unit = 'D';
691
			}
692
693
			// Is this a flexible one?
694
			if ($row['length'] == 'F')
695
				$isFlexible = true;
696
			else
697
				$isFlexible = false;
698
699
			$context['sub'] = array(
700
				'name' => $row['name'],
701
				'desc' => $row['description'],
702
				'cost' => $smcFunc['json_decode']($row['cost'], true),
703
				'span' => array(
704
					'value' => $span_value,
705
					'unit' => $span_unit,
706
				),
707
				'prim_group' => $row['id_group'],
708
				'add_groups' => explode(',', $row['add_groups']),
709
				'active' => $row['active'],
710
				'repeatable' => $row['repeatable'],
711
				'allow_partial' => $row['allow_partial'],
712
				'duration' => $isFlexible ? 'flexible' : 'fixed',
713
				'email_complete' => $smcFunc['htmlspecialchars']($row['email_complete']),
714
				'reminder' => $row['reminder'],
715
			);
716
		}
717
		$smcFunc['db_free_result']($request);
718
719
		// Does this have members who are active?
720
		$request = $smcFunc['db_query']('', '
721
			SELECT COUNT(*)
722
			FROM {db_prefix}log_subscribed
723
			WHERE id_subscribe = {int:current_subscription}
724
				AND status = {int:is_active}',
725
			array(
726
				'current_subscription' => $context['sub_id'],
727
				'is_active' => 1,
728
			)
729
		);
730
		list ($context['disable_groups']) = $smcFunc['db_fetch_row']($request);
731
		$smcFunc['db_free_result']($request);
732
	}
733
734
	// Load up all the groups.
735
	$request = $smcFunc['db_query']('', '
736
		SELECT id_group, group_name
737
		FROM {db_prefix}membergroups
738
		WHERE id_group != {int:moderator_group}
739
			AND min_posts = {int:min_posts}',
740
		array(
741
			'moderator_group' => 3,
742
			'min_posts' => -1,
743
		)
744
	);
745
	$context['groups'] = array();
746
	while ($row = $smcFunc['db_fetch_assoc']($request))
747
		$context['groups'][$row['id_group']] = $row['group_name'];
748
	$smcFunc['db_free_result']($request);
749
750
	// This always happens.
751
	createToken($context['action_type'] == 'delete' ? 'admin-pmsd' : 'admin-pms');
752
}
753
754
/**
755
 * View all the users subscribed to a particular subscription.
756
 * Requires the admin_forum permission.
757
 * Accessed from ?action=admin;area=paidsubscribe;sa=viewsub.
758
 *
759
 * Subscription ID is required, in the form of $_GET['sid'].
760
 */
761
function ViewSubscribedUsers()
762
{
763
	global $context, $txt, $scripturl, $smcFunc, $sourcedir, $modSettings;
764
765
	// Setup the template.
766
	$context['page_title'] = $txt['viewing_users_subscribed'];
767
768
	// ID of the subscription.
769
	$context['sub_id'] = (int) $_REQUEST['sid'];
770
771
	// Load the subscription information.
772
	$request = $smcFunc['db_query']('', '
773
		SELECT id_subscribe, name, description, cost, length, id_group, add_groups, active
774
		FROM {db_prefix}subscriptions
775
		WHERE id_subscribe = {int:current_subscription}',
776
		array(
777
			'current_subscription' => $context['sub_id'],
778
		)
779
	);
780
	// Something wrong?
781
	if ($smcFunc['db_num_rows']($request) == 0)
782
		fatal_lang_error('no_access', false);
783
	// Do the subscription context.
784
	$row = $smcFunc['db_fetch_assoc']($request);
785
	$context['subscription'] = array(
786
		'id' => $row['id_subscribe'],
787
		'name' => $row['name'],
788
		'desc' => $row['description'],
789
		'active' => $row['active'],
790
	);
791
	$smcFunc['db_free_result']($request);
792
793
	// Are we searching for people?
794
	$search_string = isset($_POST['ssearch']) && !empty($_POST['sub_search']) ? ' AND COALESCE(mem.real_name, {string:guest}) LIKE {string:search}' : '';
795
	$search_vars = empty($_POST['sub_search']) ? array() : array('search' => '%' . $_POST['sub_search'] . '%', 'guest' => $txt['guest']);
796
797
	$listOptions = array(
798
		'id' => 'subscribed_users_list',
799
		'title' => sprintf($txt['view_users_subscribed'], $row['name']),
800
		'items_per_page' => $modSettings['defaultMaxListItems'],
801
		'base_href' => $scripturl . '?action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id'],
802
		'default_sort_col' => 'name',
803
		'get_items' => array(
804
			'function' => 'list_getSubscribedUsers',
805
			'params' => array(
806
				$context['sub_id'],
807
				$search_string,
808
				$search_vars,
809
			),
810
		),
811
		'get_count' => array(
812
			'function' => 'list_getSubscribedUserCount',
813
			'params' => array(
814
				$context['sub_id'],
815
				$search_string,
816
				$search_vars,
817
			),
818
		),
819
		'no_items_label' => $txt['no_subscribers'],
820
		'columns' => array(
821
			'name' => array(
822
				'header' => array(
823
					'value' => $txt['who_member'],
824
					'style' => 'width: 20%;',
825
				),
826
				'data' => array(
827
					'function' => function($rowData) use ($scripturl, $txt)
828
					{
829
						return $rowData['id_member'] == 0 ? $txt['guest'] : '<a href="' . $scripturl . '?action=profile;u=' . $rowData['id_member'] . '">' . $rowData['name'] . '</a>';
830
					},
831
				),
832
				'sort' => array(
833
					'default' => 'name',
834
					'reverse' => 'name DESC',
835
				),
836
			),
837
			'status' => array(
838
				'header' => array(
839
					'value' => $txt['paid_status'],
840
					'style' => 'width: 10%;',
841
				),
842
				'data' => array(
843
					'db_htmlsafe' => 'status_text',
844
				),
845
				'sort' => array(
846
					'default' => 'status',
847
					'reverse' => 'status DESC',
848
				),
849
			),
850
			'payments_pending' => array(
851
				'header' => array(
852
					'value' => $txt['paid_payments_pending'],
853
					'style' => 'width: 15%;',
854
				),
855
				'data' => array(
856
					'db_htmlsafe' => 'pending',
857
				),
858
				'sort' => array(
859
					'default' => 'payments_pending',
860
					'reverse' => 'payments_pending DESC',
861
				),
862
			),
863
			'start_time' => array(
864
				'header' => array(
865
					'value' => $txt['start_date'],
866
					'style' => 'width: 20%;',
867
				),
868
				'data' => array(
869
					'db_htmlsafe' => 'start_date',
870
					'class' => 'smalltext',
871
				),
872
				'sort' => array(
873
					'default' => 'start_time',
874
					'reverse' => 'start_time DESC',
875
				),
876
			),
877
			'end_time' => array(
878
				'header' => array(
879
					'value' => $txt['end_date'],
880
					'style' => 'width: 20%;',
881
				),
882
				'data' => array(
883
					'db_htmlsafe' => 'end_date',
884
					'class' => 'smalltext',
885
				),
886
				'sort' => array(
887
					'default' => 'end_time',
888
					'reverse' => 'end_time DESC',
889
				),
890
			),
891
			'modify' => array(
892
				'header' => array(
893
					'style' => 'width: 10%;',
894
					'class' => 'centercol',
895
				),
896
				'data' => array(
897
					'function' => function($rowData) use ($scripturl, $txt)
898
					{
899
						return '<a href="' . $scripturl . '?action=admin;area=paidsubscribe;sa=modifyuser;lid=' . $rowData['id'] . '">' . $txt['modify'] . '</a>';
900
					},
901
					'class' => 'centercol',
902
				),
903
			),
904
			'delete' => array(
905
				'header' => array(
906
					'style' => 'width: 4%;',
907
					'class' => 'centercol',
908
				),
909
				'data' => array(
910
					'function' => function($rowData)
911
					{
912
						return '<input type="checkbox" name="delsub[' . $rowData['id'] . ']">';
913
					},
914
					'class' => 'centercol',
915
				),
916
			),
917
		),
918
		'form' => array(
919
			'href' => $scripturl . '?action=admin;area=paidsubscribe;sa=modifyuser;sid=' . $context['sub_id'],
920
		),
921
		'additional_rows' => array(
922
			array(
923
				'position' => 'below_table_data',
924
				'value' => '
925
					<input type="submit" name="add" value="' . $txt['add_subscriber'] . '" class="button">
926
					<input type="submit" name="finished" value="' . $txt['complete_selected'] . '" data-confirm="' . $txt['complete_are_sure'] . '" class="button you_sure">
927
					<input type="submit" name="delete" value="' . $txt['delete_selected'] . '" data-confirm="' . $txt['delete_are_sure'] . '" class="button you_sure">
928
				',
929
			),
930
			array(
931
				'position' => 'top_of_list',
932
				'value' => '
933
					<div class="flow_auto">
934
						<input type="submit" name="ssearch" value="' . $txt['search_sub'] . '" class="button" style="margin-top: 3px;">
935
						<input type="text" name="sub_search" value="" class="floatright">
936
					</div>
937
				',
938
			),
939
		),
940
	);
941
942
	require_once($sourcedir . '/Subs-List.php');
943
	createList($listOptions);
944
945
	$context['sub_template'] = 'show_list';
946
	$context['default_list'] = 'subscribed_users_list';
947
}
948
949
/**
950
 * Returns how many people are subscribed to a paid subscription.
951
 * @todo refactor away
952
 *
953
 * @param int $id_sub The ID of the subscription
954
 * @param string $search_string A search string
955
 * @param array $search_vars An array of variables for the search string
956
 * @return int The number of subscribed users matching the given parameters
957
 */
958
function list_getSubscribedUserCount($id_sub, $search_string, $search_vars = array())
959
{
960
	global $smcFunc;
961
962
	// Get the total amount of users.
963
	$request = $smcFunc['db_query']('', '
964
		SELECT COUNT(*) AS total_subs
965
		FROM {db_prefix}log_subscribed AS ls
966
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
967
		WHERE ls.id_subscribe = {int:current_subscription} ' . $search_string . '
968
			AND (ls.end_time != {int:no_end_time} OR ls.payments_pending != {int:no_pending_payments})',
969
		array_merge($search_vars, array(
970
			'current_subscription' => $id_sub,
971
			'no_end_time' => 0,
972
			'no_pending_payments' => 0,
973
		))
974
	);
975
	list ($memberCount) = $smcFunc['db_fetch_row']($request);
976
	$smcFunc['db_free_result']($request);
977
978
	return $memberCount;
979
}
980
981
/**
982
 * Return the subscribed users list, for the given parameters.
983
 * @todo refactor outta here
984
 *
985
 * @param int $start The item to start with (for pagination purposes)
986
 * @param int $items_per_page How many items to show on each page
987
 * @param string $sort A string indicating how to sort the results
988
 * @param int $id_sub The ID of the subscription
989
 * @param string $search_string A search string
990
 * @param array $search_vars The variables for the search string
991
 * @return array An array of information about the subscribed users matching the given parameters
992
 */
993
function list_getSubscribedUsers($start, $items_per_page, $sort, $id_sub, $search_string, $search_vars = array())
994
{
995
	global $smcFunc, $txt;
996
997
	$request = $smcFunc['db_query']('', '
998
		SELECT ls.id_sublog, COALESCE(mem.id_member, 0) AS id_member, COALESCE(mem.real_name, {string:guest}) AS name, ls.start_time, ls.end_time,
999
			ls.status, ls.payments_pending
1000
		FROM {db_prefix}log_subscribed AS ls
1001
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
1002
		WHERE ls.id_subscribe = {int:current_subscription} ' . $search_string . '
1003
			AND (ls.end_time != {int:no_end_time} OR ls.payments_pending != {int:no_payments_pending})
1004
		ORDER BY {raw:sort}
1005
		LIMIT {int:start}, {int:max}',
1006
		array_merge($search_vars, array(
1007
			'current_subscription' => $id_sub,
1008
			'no_end_time' => 0,
1009
			'no_payments_pending' => 0,
1010
			'guest' => $txt['guest'],
1011
			'sort' => $sort,
1012
			'start' => $start,
1013
			'max' => $items_per_page,
1014
		))
1015
	);
1016
	$subscribers = array();
1017
	while ($row = $smcFunc['db_fetch_assoc']($request))
1018
		$subscribers[] = array(
1019
			'id' => $row['id_sublog'],
1020
			'id_member' => $row['id_member'],
1021
			'name' => $row['name'],
1022
			'start_date' => timeformat($row['start_time'], false),
1023
			'end_date' => $row['end_time'] == 0 ? 'N/A' : timeformat($row['end_time'], false),
1024
			'pending' => $row['payments_pending'],
1025
			'status' => $row['status'],
1026
			'status_text' => $row['status'] == 0 ? ($row['payments_pending'] == 0 ? $txt['paid_finished'] : $txt['paid_pending']) : $txt['paid_active'],
1027
		);
1028
	$smcFunc['db_free_result']($request);
1029
1030
	return $subscribers;
1031
}
1032
1033
/**
1034
 * Edit or add a user subscription.
1035
 * Accessed from ?action=admin;area=paidsubscribe;sa=modifyuser.
1036
 */
1037
function ModifyUserSubscription()
1038
{
1039
	global $context, $txt, $modSettings, $smcFunc;
1040
1041
	loadSubscriptions();
1042
1043
	$context['log_id'] = isset($_REQUEST['lid']) ? (int) $_REQUEST['lid'] : 0;
1044
	$context['sub_id'] = isset($_REQUEST['sid']) ? (int) $_REQUEST['sid'] : 0;
1045
	$context['action_type'] = $context['log_id'] ? 'edit' : 'add';
1046
1047
	// Setup the template.
1048
	$context['sub_template'] = 'modify_user_subscription';
1049
	$context['page_title'] = $txt[$context['action_type'] . '_subscriber'];
1050
1051
	// If we haven't been passed the subscription ID get it.
1052
	if ($context['log_id'] && !$context['sub_id'])
1053
	{
1054
		$request = $smcFunc['db_query']('', '
1055
			SELECT id_subscribe
1056
			FROM {db_prefix}log_subscribed
1057
			WHERE id_sublog = {int:current_log_item}',
1058
			array(
1059
				'current_log_item' => $context['log_id'],
1060
			)
1061
		);
1062
		if ($smcFunc['db_num_rows']($request) == 0)
1063
			fatal_lang_error('no_access', false);
1064
		list ($context['sub_id']) = $smcFunc['db_fetch_row']($request);
1065
		$smcFunc['db_free_result']($request);
1066
	}
1067
1068
	if (!isset($context['subscriptions'][$context['sub_id']]))
1069
		fatal_lang_error('no_access', false);
1070
	$context['current_subscription'] = $context['subscriptions'][$context['sub_id']];
1071
1072
	// Searching?
1073
	if (isset($_POST['ssearch']))
1074
	{
1075
		return ViewSubscribedUsers();
1076
	}
1077
	// Saving?
1078
	elseif (isset($_REQUEST['save_sub']))
1079
	{
1080
		checkSession();
1081
1082
		// Work out the dates...
1083
		$starttime = mktime($_POST['hour'], $_POST['minute'], 0, $_POST['month'], $_POST['day'], $_POST['year']);
1084
		$endtime = mktime($_POST['hourend'], $_POST['minuteend'], 0, $_POST['monthend'], $_POST['dayend'], $_POST['yearend']);
1085
1086
		// Status.
1087
		$status = $_POST['status'];
1088
1089
		// New one?
1090
		if (empty($context['log_id']))
1091
		{
1092
			// Find the user...
1093
			$request = $smcFunc['db_query']('', '
1094
				SELECT id_member, id_group
1095
				FROM {db_prefix}members
1096
				WHERE real_name = {string:name}
1097
				LIMIT 1',
1098
				array(
1099
					'name' => $_POST['name'],
1100
				)
1101
			);
1102
			if ($smcFunc['db_num_rows']($request) == 0)
1103
				fatal_lang_error('error_member_not_found');
1104
1105
			list ($id_member, $id_group) = $smcFunc['db_fetch_row']($request);
1106
			$smcFunc['db_free_result']($request);
1107
1108
			// Ensure the member doesn't already have a subscription!
1109
			$request = $smcFunc['db_query']('', '
1110
				SELECT id_subscribe
1111
				FROM {db_prefix}log_subscribed
1112
				WHERE id_subscribe = {int:current_subscription}
1113
					AND id_member = {int:current_member}',
1114
				array(
1115
					'current_subscription' => $context['sub_id'],
1116
					'current_member' => $id_member,
1117
				)
1118
			);
1119
			if ($smcFunc['db_num_rows']($request) != 0)
1120
				fatal_lang_error('member_already_subscribed');
1121
			$smcFunc['db_free_result']($request);
1122
1123
			// Actually put the subscription in place.
1124
			if ($status == 1)
1125
				addSubscription($context['sub_id'], $id_member, 0, $starttime, $endtime);
1126
			else
1127
			{
1128
				$smcFunc['db_insert']('',
1129
					'{db_prefix}log_subscribed',
1130
					array(
1131
						'id_subscribe' => 'int', 'id_member' => 'int', 'old_id_group' => 'int', 'start_time' => 'int',
1132
						'end_time' => 'int', 'status' => 'int','pending_details' => 'string-65534'
1133
					),
1134
					array(
1135
						$context['sub_id'], $id_member, $id_group, $starttime,
1136
						$endtime, $status, $smcFunc['json_encode'](array())
1137
					),
1138
					array('id_sublog')
1139
				);
1140
1141
			}
1142
		}
1143
		// Updating.
1144
		else
1145
		{
1146
			$request = $smcFunc['db_query']('', '
1147
				SELECT id_member, status
1148
				FROM {db_prefix}log_subscribed
1149
				WHERE id_sublog = {int:current_log_item}',
1150
				array(
1151
					'current_log_item' => $context['log_id'],
1152
				)
1153
			);
1154
			if ($smcFunc['db_num_rows']($request) == 0)
1155
				fatal_lang_error('no_access', false);
1156
1157
			list ($id_member, $old_status) = $smcFunc['db_fetch_row']($request);
1158
			$smcFunc['db_free_result']($request);
1159
1160
			// Pick the right permission stuff depending on what the status is changing from/to.
1161
			if ($old_status == 1 && $status != 1)
1162
				removeSubscription($context['sub_id'], $id_member);
1163
			elseif ($status == 1 && $old_status != 1)
1164
			{
1165
				addSubscription($context['sub_id'], $id_member, 0, $starttime, $endtime);
1166
			}
1167
			else
1168
			{
1169
				$smcFunc['db_query']('', '
1170
					UPDATE {db_prefix}log_subscribed
1171
					SET start_time = {int:start_time}, end_time = {int:end_time}, status = {int:status}
1172
					WHERE id_sublog = {int:current_log_item}',
1173
					array(
1174
						'start_time' => $starttime,
1175
						'end_time' => $endtime,
1176
						'status' => $status,
1177
						'current_log_item' => $context['log_id'],
1178
					)
1179
				);
1180
			}
1181
		}
1182
1183
		// Done - redirect...
1184
		redirectexit('action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id']);
1185
	}
1186
	// Deleting?
1187
	elseif (isset($_REQUEST['delete']) || isset($_REQUEST['finished']))
1188
	{
1189
		checkSession();
1190
1191
		// Do the actual deletes!
1192
		if (!empty($_REQUEST['delsub']))
1193
		{
1194
			$toDelete = array();
1195
			foreach ($_REQUEST['delsub'] as $id => $dummy)
1196
				$toDelete[] = (int) $id;
1197
1198
			$request = $smcFunc['db_query']('', '
1199
				SELECT id_subscribe, id_member
1200
				FROM {db_prefix}log_subscribed
1201
				WHERE id_sublog IN ({array_int:subscription_list})',
1202
				array(
1203
					'subscription_list' => $toDelete,
1204
				)
1205
			);
1206
			while ($row = $smcFunc['db_fetch_assoc']($request))
1207
				removeSubscription($row['id_subscribe'], $row['id_member'], isset($_REQUEST['delete']));
1208
			$smcFunc['db_free_result']($request);
1209
		}
1210
		redirectexit('action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id']);
1211
	}
1212
1213
	// Default attributes.
1214
	if ($context['action_type'] == 'add')
1215
	{
1216
		$context['sub'] = array(
1217
			'id' => 0,
1218
			'start' => array(
1219
				'year' => (int) strftime('%Y', time()),
1220
				'month' => (int) strftime('%m', time()),
1221
				'day' => (int) strftime('%d', time()),
1222
				'hour' => (int) strftime('%H', time()),
1223
				'min' => (int) strftime('%M', time()) < 10 ? '0' . (int) strftime('%M', time()) : (int) strftime('%M', time()),
1224
				'last_day' => 0,
1225
			),
1226
			'end' => array(
1227
				'year' => (int) strftime('%Y', time()),
1228
				'month' => (int) strftime('%m', time()),
1229
				'day' => (int) strftime('%d', time()),
1230
				'hour' => (int) strftime('%H', time()),
1231
				'min' => (int) strftime('%M', time()) < 10 ? '0' . (int) strftime('%M', time()) : (int) strftime('%M', time()),
1232
				'last_day' => 0,
1233
			),
1234
			'status' => 1,
1235
		);
1236
		$context['sub']['start']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['sub']['start']['month'] == 12 ? 1 : $context['sub']['start']['month'] + 1, 0, $context['sub']['start']['month'] == 12 ? $context['sub']['start']['year'] + 1 : $context['sub']['start']['year']));
1237
		$context['sub']['end']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['sub']['end']['month'] == 12 ? 1 : $context['sub']['end']['month'] + 1, 0, $context['sub']['end']['month'] == 12 ? $context['sub']['end']['year'] + 1 : $context['sub']['end']['year']));
1238
1239
		if (isset($_GET['uid']))
1240
		{
1241
			$request = $smcFunc['db_query']('', '
1242
				SELECT real_name
1243
				FROM {db_prefix}members
1244
				WHERE id_member = {int:current_member}',
1245
				array(
1246
					'current_member' => (int) $_GET['uid'],
1247
				)
1248
			);
1249
			list ($context['sub']['username']) = $smcFunc['db_fetch_row']($request);
1250
			$smcFunc['db_free_result']($request);
1251
		}
1252
		else
1253
			$context['sub']['username'] = '';
1254
	}
1255
	// Otherwise load the existing info.
1256
	else
1257
	{
1258
		$request = $smcFunc['db_query']('', '
1259
			SELECT ls.id_sublog, ls.id_subscribe, ls.id_member, start_time, end_time, status, payments_pending, pending_details,
1260
				COALESCE(mem.real_name, {string:blank_string}) AS username
1261
			FROM {db_prefix}log_subscribed AS ls
1262
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
1263
			WHERE ls.id_sublog = {int:current_subscription_item}
1264
			LIMIT 1',
1265
			array(
1266
				'current_subscription_item' => $context['log_id'],
1267
				'blank_string' => '',
1268
			)
1269
		);
1270
		if ($smcFunc['db_num_rows']($request) == 0)
1271
			fatal_lang_error('no_access', false);
1272
		$row = $smcFunc['db_fetch_assoc']($request);
1273
		$smcFunc['db_free_result']($request);
1274
1275
		// Any pending payments?
1276
		$context['pending_payments'] = array();
1277
		if (!empty($row['pending_details']))
1278
		{
1279
			$pending_details = $smcFunc['json_decode']($row['pending_details'], true);
1280
			foreach ($pending_details as $id => $pending)
1281
			{
1282
				// Only this type need be displayed.
1283
				if ($pending[3] == 'payback')
1284
				{
1285
					// Work out what the options were.
1286
					$costs = $smcFunc['json_decode']($context['current_subscription']['real_cost'], true);
1287
1288
					if ($context['current_subscription']['real_length'] == 'F')
1289
					{
1290
						foreach ($costs as $duration => $cost)
1291
						{
1292
							if ($cost != 0 && $cost == $pending[1] && $duration == $pending[2])
1293
								$context['pending_payments'][$id] = array(
1294
									'desc' => sprintf($modSettings['paid_currency_symbol'], $cost . '/' . $txt[$duration]),
1295
								);
1296
						}
1297
					}
1298
					elseif ($costs['fixed'] == $pending[1])
1299
					{
1300
						$context['pending_payments'][$id] = array(
1301
							'desc' => sprintf($modSettings['paid_currency_symbol'], $costs['fixed']),
1302
						);
1303
					}
1304
				}
1305
			}
1306
1307
			// Check if we are adding/removing any.
1308
			if (isset($_GET['pending']))
1309
			{
1310
				foreach ($pending_details as $id => $pending)
1311
				{
1312
					// Found the one to action?
1313
					if ($_GET['pending'] == $id && $pending[3] == 'payback' && isset($context['pending_payments'][$id]))
1314
					{
1315
						// Flexible?
1316
						if (isset($_GET['accept']))
1317
							addSubscription($context['current_subscription']['id'], $row['id_member'], $context['current_subscription']['real_length'] == 'F' ? strtoupper(substr($pending[2], 0, 1)) : 0);
1318
						unset($pending_details[$id]);
1319
1320
						$new_details = $smcFunc['json_encode']($pending_details);
1321
1322
						// Update the entry.
1323
						$smcFunc['db_query']('', '
1324
							UPDATE {db_prefix}log_subscribed
1325
							SET payments_pending = payments_pending - 1, pending_details = {string:pending_details}
1326
							WHERE id_sublog = {int:current_subscription_item}',
1327
							array(
1328
								'current_subscription_item' => $context['log_id'],
1329
								'pending_details' => $new_details,
1330
							)
1331
						);
1332
1333
						// Reload
1334
						redirectexit('action=admin;area=paidsubscribe;sa=modifyuser;lid=' . $context['log_id']);
1335
					}
1336
				}
1337
			}
1338
		}
1339
1340
		$context['sub_id'] = $row['id_subscribe'];
1341
		$context['sub'] = array(
1342
			'id' => 0,
1343
			'start' => array(
1344
				'year' => (int) strftime('%Y', $row['start_time']),
1345
				'month' => (int) strftime('%m', $row['start_time']),
1346
				'day' => (int) strftime('%d', $row['start_time']),
1347
				'hour' => (int) strftime('%H', $row['start_time']),
1348
				'min' => (int) strftime('%M', $row['start_time']) < 10 ? '0' . (int) strftime('%M', $row['start_time']) : (int) strftime('%M', $row['start_time']),
1349
				'last_day' => 0,
1350
			),
1351
			'end' => array(
1352
				'year' => (int) strftime('%Y', $row['end_time']),
1353
				'month' => (int) strftime('%m', $row['end_time']),
1354
				'day' => (int) strftime('%d', $row['end_time']),
1355
				'hour' => (int) strftime('%H', $row['end_time']),
1356
				'min' => (int) strftime('%M', $row['end_time']) < 10 ? '0' . (int) strftime('%M', $row['end_time']) : (int) strftime('%M', $row['end_time']),
1357
				'last_day' => 0,
1358
			),
1359
			'status' => $row['status'],
1360
			'username' => $row['username'],
1361
		);
1362
		$context['sub']['start']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['sub']['start']['month'] == 12 ? 1 : $context['sub']['start']['month'] + 1, 0, $context['sub']['start']['month'] == 12 ? $context['sub']['start']['year'] + 1 : $context['sub']['start']['year']));
1363
		$context['sub']['end']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['sub']['end']['month'] == 12 ? 1 : $context['sub']['end']['month'] + 1, 0, $context['sub']['end']['month'] == 12 ? $context['sub']['end']['year'] + 1 : $context['sub']['end']['year']));
1364
	}
1365
1366
	loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
1367
}
1368
1369
/**
1370
 * Reapplies all subscription rules for each of the users.
1371
 *
1372
 * @param array $users An array of user IDs
1373
 */
1374
function reapplySubscriptions($users)
1375
{
1376
	global $smcFunc;
1377
1378
	// Make it an array.
1379
	if (!is_array($users))
0 ignored issues
show
introduced by
The condition is_array($users) is always true.
Loading history...
1380
		$users = array($users);
1381
1382
	// Get all the members current groups.
1383
	$groups = array();
1384
	$request = $smcFunc['db_query']('', '
1385
		SELECT id_member, id_group, additional_groups
1386
		FROM {db_prefix}members
1387
		WHERE id_member IN ({array_int:user_list})',
1388
		array(
1389
			'user_list' => $users,
1390
		)
1391
	);
1392
	while ($row = $smcFunc['db_fetch_assoc']($request))
1393
	{
1394
		$groups[$row['id_member']] = array(
1395
			'primary' => $row['id_group'],
1396
			'additional' => explode(',', $row['additional_groups']),
1397
		);
1398
	}
1399
	$smcFunc['db_free_result']($request);
1400
1401
	$request = $smcFunc['db_query']('', '
1402
		SELECT ls.id_member, ls.old_id_group, s.id_group, s.add_groups
1403
		FROM {db_prefix}log_subscribed AS ls
1404
			INNER JOIN {db_prefix}subscriptions AS s ON (s.id_subscribe = ls.id_subscribe)
1405
		WHERE ls.id_member IN ({array_int:user_list})
1406
			AND ls.end_time > {int:current_time}',
1407
		array(
1408
			'user_list' => $users,
1409
			'current_time' => time(),
1410
		)
1411
	);
1412
	while ($row = $smcFunc['db_fetch_assoc']($request))
1413
	{
1414
		// Specific primary group?
1415
		if ($row['id_group'] != 0)
1416
		{
1417
			// If this is changing - add the old one to the additional groups so it's not lost.
1418
			if ($row['id_group'] != $groups[$row['id_member']]['primary'])
1419
				$groups[$row['id_member']]['additional'][] = $groups[$row['id_member']]['primary'];
1420
			$groups[$row['id_member']]['primary'] = $row['id_group'];
1421
		}
1422
1423
		// Additional groups.
1424
		if (!empty($row['add_groups']))
1425
			$groups[$row['id_member']]['additional'] = array_merge($groups[$row['id_member']]['additional'], explode(',', $row['add_groups']));
1426
	}
1427
	$smcFunc['db_free_result']($request);
1428
1429
	// Update all the members.
1430
	foreach ($groups as $id => $group)
1431
	{
1432
		$group['additional'] = array_unique($group['additional']);
1433
		foreach ($group['additional'] as $key => $value)
1434
			if (empty($value))
1435
				unset($group['additional'][$key]);
1436
		$addgroups = implode(',', $group['additional']);
1437
1438
		$smcFunc['db_query']('', '
1439
			UPDATE {db_prefix}members
1440
			SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
1441
			WHERE id_member = {int:current_member}
1442
			LIMIT 1',
1443
			array(
1444
				'primary_group' => $group['primary'],
1445
				'current_member' => $id,
1446
				'additional_groups' => $addgroups,
1447
			)
1448
		);
1449
	}
1450
}
1451
1452
/**
1453
 * Add or extend a subscription of a user.
1454
 *
1455
 * @param int $id_subscribe The subscription ID
1456
 * @param int $id_member The ID of the member
1457
 * @param int|string $renewal 0 if we're forcing start/end time, otherwise a string indicating how long to renew the subscription for ('D', 'W', 'M' or 'Y')
1458
 * @param int $forceStartTime If set, forces the subscription to start at the specified time
1459
 * @param int $forceEndTime If set, forces the subscription to end at the specified time
1460
 */
1461
function addSubscription($id_subscribe, $id_member, $renewal = 0, $forceStartTime = 0, $forceEndTime = 0)
1462
{
1463
	global $context, $smcFunc;
1464
1465
	// Take the easy way out...
1466
	loadSubscriptions();
1467
1468
	// Exists, yes?
1469
	if (!isset($context['subscriptions'][$id_subscribe]))
1470
		return;
1471
1472
	$curSub = $context['subscriptions'][$id_subscribe];
1473
1474
	// Grab the duration.
1475
	$duration = $curSub['num_length'];
1476
1477
	// If this is a renewal change the duration to be correct.
1478
	if (!empty($renewal))
1479
	{
1480
		switch ($renewal)
1481
		{
1482
			case 'D':
1483
				$duration = 86400;
1484
				break;
1485
			case 'W':
1486
				$duration = 604800;
1487
				break;
1488
			case 'M':
1489
				$duration = 2629743;
1490
				break;
1491
			case 'Y':
1492
				$duration = 31556926;
1493
				break;
1494
			default:
1495
				break;
1496
		}
1497
	}
1498
1499
	// Firstly, see whether it exists, and is active. If so then this is meerly an extension.
1500
	$request = $smcFunc['db_query']('', '
1501
		SELECT id_sublog, end_time, start_time
1502
		FROM {db_prefix}log_subscribed
1503
		WHERE id_subscribe = {int:current_subscription}
1504
			AND id_member = {int:current_member}
1505
			AND status = {int:is_active}',
1506
		array(
1507
			'current_subscription' => $id_subscribe,
1508
			'current_member' => $id_member,
1509
			'is_active' => 1,
1510
		)
1511
	);
1512
1513
	if ($smcFunc['db_num_rows']($request) != 0)
1514
	{
1515
		list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
1516
1517
		// If this has already expired but is active, extension means the period from now.
1518
		if ($endtime < time())
1519
			$endtime = time();
1520
		if ($starttime == 0)
1521
			$starttime = time();
1522
1523
		// Work out the new expiry date.
1524
		$endtime += $duration;
1525
1526
		if ($forceEndTime != 0)
1527
			$endtime = $forceEndTime;
1528
1529
		// As everything else should be good, just update!
1530
		$smcFunc['db_query']('', '
1531
			UPDATE {db_prefix}log_subscribed
1532
			SET end_time = {int:end_time}, start_time = {int:start_time}, reminder_sent = {int:no_reminder_sent}
1533
			WHERE id_sublog = {int:current_subscription_item}',
1534
			array(
1535
				'end_time' => $endtime,
1536
				'start_time' => $starttime,
1537
				'current_subscription_item' => $id_sublog,
1538
				'no_reminder_sent' => 0,
1539
			)
1540
		);
1541
1542
		return;
1543
	}
1544
	$smcFunc['db_free_result']($request);
1545
1546
	// If we're here, that means we don't have an active subscription - that means we need to do some work!
1547
	$request = $smcFunc['db_query']('', '
1548
		SELECT m.id_group, m.additional_groups
1549
		FROM {db_prefix}members AS m
1550
		WHERE m.id_member = {int:current_member}',
1551
		array(
1552
			'current_member' => $id_member,
1553
		)
1554
	);
1555
1556
	// Just in case the member doesn't exist.
1557
	if ($smcFunc['db_num_rows']($request) == 0)
1558
		return;
1559
1560
	list ($old_id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
1561
	$smcFunc['db_free_result']($request);
1562
1563
	// Prepare additional groups.
1564
	$newAddGroups = explode(',', $curSub['add_groups']);
1565
	$curAddGroups = explode(',', $additional_groups);
1566
1567
	$newAddGroups = array_merge($newAddGroups, $curAddGroups);
1568
1569
	// Simple, simple, simple - hopefully... id_group first.
1570
	if ($curSub['prim_group'] != 0)
1571
	{
1572
		$id_group = $curSub['prim_group'];
1573
1574
		// Ensure their old privileges are maintained.
1575
		if ($old_id_group != 0)
1576
			$newAddGroups[] = $old_id_group;
1577
	}
1578
	else
1579
		$id_group = $old_id_group;
1580
1581
	// Yep, make sure it's unique, and no empties.
1582
	foreach ($newAddGroups as $k => $v)
1583
		if (empty($v))
1584
			unset($newAddGroups[$k]);
1585
	$newAddGroups = array_unique($newAddGroups);
1586
	$newAddGroups = implode(',', $newAddGroups);
1587
1588
	// Store the new settings.
1589
	$smcFunc['db_query']('', '
1590
		UPDATE {db_prefix}members
1591
		SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
1592
		WHERE id_member = {int:current_member}',
1593
		array(
1594
			'primary_group' => $id_group,
1595
			'current_member' => $id_member,
1596
			'additional_groups' => $newAddGroups,
1597
		)
1598
	);
1599
1600
	// Now log the subscription - maybe we have a dorment subscription we can restore?
1601
	$request = $smcFunc['db_query']('', '
1602
		SELECT id_sublog, end_time, start_time
1603
		FROM {db_prefix}log_subscribed
1604
		WHERE id_subscribe = {int:current_subscription}
1605
			AND id_member = {int:current_member}',
1606
		array(
1607
			'current_subscription' => $id_subscribe,
1608
			'current_member' => $id_member,
1609
		)
1610
	);
1611
1612
	/**
1613
	 * @todo Don't really need to do this twice...
1614
	 */
1615
	if ($smcFunc['db_num_rows']($request) != 0)
1616
	{
1617
		list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
1618
1619
		// If this has already expired but is active, extension means the period from now.
1620
		if ($endtime < time())
1621
			$endtime = time();
1622
		if ($starttime == 0)
1623
			$starttime = time();
1624
1625
		// Work out the new expiry date.
1626
		$endtime += $duration;
1627
1628
		if ($forceEndTime != 0)
1629
			$endtime = $forceEndTime;
1630
1631
		// As everything else should be good, just update!
1632
		$smcFunc['db_query']('', '
1633
			UPDATE {db_prefix}log_subscribed
1634
			SET start_time = {int:start_time}, end_time = {int:end_time}, old_id_group = {int:old_id_group}, status = {int:is_active}, reminder_sent = {int:no_reminder_sent}
1635
			WHERE id_sublog = {int:current_subscription_item}',
1636
			array(
1637
				'start_time' => $starttime,
1638
				'end_time' => $endtime,
1639
				'old_id_group' => $old_id_group,
1640
				'is_active' => 1,
1641
				'no_reminder_sent' => 0,
1642
				'current_subscription_item' => $id_sublog,
1643
			)
1644
		);
1645
1646
		return;
1647
	}
1648
	$smcFunc['db_free_result']($request);
1649
1650
	// Otherwise a very simple insert.
1651
	$endtime = time() + $duration;
1652
	if ($forceEndTime != 0)
1653
		$endtime = $forceEndTime;
1654
1655
	if ($forceStartTime == 0)
1656
		$starttime = time();
1657
	else
1658
		$starttime = $forceStartTime;
1659
1660
	$smcFunc['db_insert']('',
1661
		'{db_prefix}log_subscribed',
1662
		array(
1663
			'id_subscribe' => 'int', 'id_member' => 'int', 'old_id_group' => 'int', 'start_time' => 'int',
1664
			'end_time' => 'int', 'status' => 'int', 'pending_details' => 'string',
1665
		),
1666
		array(
1667
			$id_subscribe, $id_member, $old_id_group, $starttime,
1668
			$endtime, 1, '',
1669
		),
1670
		array('id_sublog')
1671
	);
1672
}
1673
1674
/**
1675
 * Removes a subscription from a user, as in removes the groups.
1676
 *
1677
 * @param int $id_subscribe The ID of the subscription
1678
 * @param int $id_member The ID of the member
1679
 * @param bool $delete Whether to delete the subscription or just disable it
1680
 */
1681
function removeSubscription($id_subscribe, $id_member, $delete = false)
1682
{
1683
	global $context, $smcFunc;
1684
1685
	loadSubscriptions();
1686
1687
	// Load the user core bits.
1688
	$request = $smcFunc['db_query']('', '
1689
		SELECT m.id_group, m.additional_groups
1690
		FROM {db_prefix}members AS m
1691
		WHERE m.id_member = {int:current_member}',
1692
		array(
1693
			'current_member' => $id_member,
1694
		)
1695
	);
1696
1697
	// Just in case of errors.
1698
	if ($smcFunc['db_num_rows']($request) == 0)
1699
	{
1700
		$smcFunc['db_query']('', '
1701
			DELETE FROM {db_prefix}log_subscribed
1702
			WHERE id_member = {int:current_member}',
1703
			array(
1704
				'current_member' => $id_member,
1705
			)
1706
		);
1707
		return;
1708
	}
1709
	list ($id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
1710
	$smcFunc['db_free_result']($request);
1711
1712
	// Get all of the subscriptions for this user that are active - it will be necessary!
1713
	$request = $smcFunc['db_query']('', '
1714
		SELECT id_subscribe, old_id_group
1715
		FROM {db_prefix}log_subscribed
1716
		WHERE id_member = {int:current_member}
1717
			AND status = {int:is_active}',
1718
		array(
1719
			'current_member' => $id_member,
1720
			'is_active' => 1,
1721
		)
1722
	);
1723
1724
	// These variables will be handy, honest ;)
1725
	$removals = array();
1726
	$allowed = array();
1727
	$old_id_group = 0;
1728
	$new_id_group = -1;
1729
	while ($row = $smcFunc['db_fetch_assoc']($request))
1730
	{
1731
		if (!isset($context['subscriptions'][$row['id_subscribe']]))
1732
			continue;
1733
1734
		// The one we're removing?
1735
		if ($row['id_subscribe'] == $id_subscribe)
1736
		{
1737
			$removals = explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']);
1738
			if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
1739
				$removals[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
1740
			$old_id_group = $row['old_id_group'];
1741
		}
1742
		// Otherwise things we allow.
1743
		else
1744
		{
1745
			$allowed = array_merge($allowed, explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']));
1746
			if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
1747
			{
1748
				$allowed[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
1749
				$new_id_group = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
1750
			}
1751
		}
1752
	}
1753
	$smcFunc['db_free_result']($request);
1754
1755
	// Now, for everything we are removing check they definitely are not allowed it.
1756
	$existingGroups = explode(',', $additional_groups);
1757
	foreach ($existingGroups as $key => $group)
1758
		if (empty($group) || (in_array($group, $removals) && !in_array($group, $allowed)))
1759
			unset($existingGroups[$key]);
1760
1761
	// Finally, do something with the current primary group.
1762
	if (in_array($id_group, $removals))
1763
	{
1764
		// If this primary group is actually allowed keep it.
1765
		if (in_array($id_group, $allowed))
1766
			$existingGroups[] = $id_group;
1767
1768
		// Either way, change the id_group back.
1769
		if ($new_id_group < 1)
1770
		{
1771
			// If we revert to the old id-group we need to ensure it wasn't from a subscription.
1772
			foreach ($context['subscriptions'] as $id => $group)
1773
				// It was? Make them a regular member then!
1774
				if ($group['prim_group'] == $old_id_group)
1775
					$old_id_group = 0;
1776
1777
			$id_group = $old_id_group;
1778
		}
1779
		else
1780
			$id_group = $new_id_group;
1781
	}
1782
1783
	// Crazy stuff, we seem to have our groups fixed, just make them unique
1784
	$existingGroups = array_unique($existingGroups);
1785
	$existingGroups = implode(',', $existingGroups);
1786
1787
	// Update the member
1788
	$smcFunc['db_query']('', '
1789
		UPDATE {db_prefix}members
1790
		SET id_group = {int:primary_group}, additional_groups = {string:existing_groups}
1791
		WHERE id_member = {int:current_member}',
1792
		array(
1793
			'primary_group' => $id_group,
1794
			'current_member' => $id_member,
1795
			'existing_groups' => $existingGroups,
1796
		)
1797
	);
1798
1799
	// Disable the subscription.
1800
	if (!$delete)
1801
		$smcFunc['db_query']('', '
1802
			UPDATE {db_prefix}log_subscribed
1803
			SET status = {int:not_active}
1804
			WHERE id_member = {int:current_member}
1805
				AND id_subscribe = {int:current_subscription}',
1806
			array(
1807
				'not_active' => 0,
1808
				'current_member' => $id_member,
1809
				'current_subscription' => $id_subscribe,
1810
			)
1811
		);
1812
	// Otherwise delete it!
1813
	else
1814
		$smcFunc['db_query']('', '
1815
			DELETE FROM {db_prefix}log_subscribed
1816
			WHERE id_member = {int:current_member}
1817
				AND id_subscribe = {int:current_subscription}',
1818
			array(
1819
				'current_member' => $id_member,
1820
				'current_subscription' => $id_subscribe,
1821
			)
1822
		);
1823
}
1824
1825
/**
1826
 * This just kind of caches all the subscription data.
1827
 */
1828
function loadSubscriptions()
1829
{
1830
	global $context, $txt, $modSettings, $smcFunc;
1831
1832
	if (!empty($context['subscriptions']))
1833
		return;
1834
1835
	// Make sure this is loaded, just in case.
1836
	loadLanguage('ManagePaid');
1837
1838
	$request = $smcFunc['db_query']('', '
1839
		SELECT id_subscribe, name, description, cost, length, id_group, add_groups, active, repeatable
1840
		FROM {db_prefix}subscriptions',
1841
		array(
1842
		)
1843
	);
1844
	$context['subscriptions'] = array();
1845
	while ($row = $smcFunc['db_fetch_assoc']($request))
1846
	{
1847
		// Pick a cost.
1848
		$costs = $smcFunc['json_decode']($row['cost'], true);
1849
1850
		if ($row['length'] != 'F' && !empty($modSettings['paid_currency_symbol']) && !empty($costs['fixed']))
1851
			$cost = sprintf($modSettings['paid_currency_symbol'], $costs['fixed']);
1852
		else
1853
			$cost = '???';
1854
1855
		// Do the span.
1856
		preg_match('~(\d*)(\w)~', $row['length'], $match);
1857
		if (isset($match[2]))
1858
		{
1859
			$num_length = $match[1];
1860
			$length = $match[1] . ' ';
1861
			switch ($match[2])
1862
			{
1863
				case 'D':
1864
					$length .= $txt['paid_mod_span_days'];
1865
					$num_length *= 86400;
1866
					break;
1867
				case 'W':
1868
					$length .= $txt['paid_mod_span_weeks'];
1869
					$num_length *= 604800;
1870
					break;
1871
				case 'M':
1872
					$length .= $txt['paid_mod_span_months'];
1873
					$num_length *= 2629743;
1874
					break;
1875
				case 'Y':
1876
					$length .= $txt['paid_mod_span_years'];
1877
					$num_length *= 31556926;
1878
					break;
1879
			}
1880
		}
1881
		else
1882
			$length = '??';
1883
1884
		$context['subscriptions'][$row['id_subscribe']] = array(
1885
			'id' => $row['id_subscribe'],
1886
			'name' => $row['name'],
1887
			'desc' => $row['description'],
1888
			'cost' => $cost,
1889
			'real_cost' => $row['cost'],
1890
			'length' => $length,
1891
			'num_length' => $num_length,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $num_length does not seem to be defined for all execution paths leading up to this point.
Loading history...
1892
			'real_length' => $row['length'],
1893
			'pending' => 0,
1894
			'finished' => 0,
1895
			'total' => 0,
1896
			'active' => $row['active'],
1897
			'prim_group' => $row['id_group'],
1898
			'add_groups' => $row['add_groups'],
1899
			'flexible' => $row['length'] == 'F' ? true : false,
1900
			'repeatable' => $row['repeatable'],
1901
		);
1902
	}
1903
	$smcFunc['db_free_result']($request);
1904
1905
	// Do the counts.
1906
	$request = $smcFunc['db_query']('', '
1907
		SELECT COUNT(id_sublog) AS member_count, id_subscribe, status
1908
		FROM {db_prefix}log_subscribed
1909
		GROUP BY id_subscribe, status',
1910
		array(
1911
		)
1912
	);
1913
	while ($row = $smcFunc['db_fetch_assoc']($request))
1914
	{
1915
		$ind = $row['status'] == 0 ? 'finished' : 'total';
1916
1917
		if (isset($context['subscriptions'][$row['id_subscribe']]))
1918
			$context['subscriptions'][$row['id_subscribe']][$ind] = $row['member_count'];
1919
	}
1920
	$smcFunc['db_free_result']($request);
1921
1922
	// How many payments are we waiting on?
1923
	$request = $smcFunc['db_query']('', '
1924
		SELECT SUM(payments_pending) AS total_pending, id_subscribe
1925
		FROM {db_prefix}log_subscribed
1926
		GROUP BY id_subscribe',
1927
		array(
1928
		)
1929
	);
1930
	while ($row = $smcFunc['db_fetch_assoc']($request))
1931
	{
1932
		if (isset($context['subscriptions'][$row['id_subscribe']]))
1933
			$context['subscriptions'][$row['id_subscribe']]['pending'] = $row['total_pending'];
1934
	}
1935
	$smcFunc['db_free_result']($request);
1936
}
1937
1938
/**
1939
 * Load all the payment gateways.
1940
 * Checks the Sources directory for any files fitting the format of a payment gateway,
1941
 * loads each file to check it's valid, includes each file and returns the
1942
 * function name and whether it should work with this version of SMF.
1943
 *
1944
 * @return array An array of information about available payment gateways
1945
 */
1946
function loadPaymentGateways()
1947
{
1948
	global $sourcedir;
1949
1950
	$gateways = array();
1951
	if ($dh = opendir($sourcedir))
1952
	{
1953
		while (($file = readdir($dh)) !== false)
1954
		{
1955
			if (is_file($sourcedir . '/' . $file) && preg_match('~^Subscriptions-([A-Za-z\d]+)\.php$~', $file, $matches))
1956
			{
1957
				// Check this is definitely a valid gateway!
1958
				$fp = fopen($sourcedir . '/' . $file, 'rb');
1959
				$header = fread($fp, 4096);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fread() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1959
				$header = fread(/** @scrutinizer ignore-type */ $fp, 4096);
Loading history...
1960
				fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1960
				fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
1961
1962
				if (strpos($header, '// SMF Payment Gateway: ' . strtolower($matches[1])) !== false)
1963
				{
1964
					require_once($sourcedir . '/' . $file);
1965
1966
					$gateways[] = array(
1967
						'filename' => $file,
1968
						'code' => strtolower($matches[1]),
1969
						// Don't need anything snazzier than this yet.
1970
						'valid_version' => class_exists(strtolower($matches[1]) . '_payment') && class_exists(strtolower($matches[1]) . '_display'),
1971
						'payment_class' => strtolower($matches[1]) . '_payment',
1972
						'display_class' => strtolower($matches[1]) . '_display',
1973
					);
1974
				}
1975
			}
1976
		}
1977
	}
1978
	closedir($dh);
0 ignored issues
show
Bug introduced by
It seems like $dh can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1978
	closedir(/** @scrutinizer ignore-type */ $dh);
Loading history...
1979
1980
	return $gateways;
1981
}
1982
1983
?>