comparison forum/Sources/ManagePaid.php @ 76:e3e11437ecea website

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