Issues (1065)

Sources/ManagePaid.php (1 issue)

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