PageRenderTime 76ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/admin/ManagePaid.php

https://github.com/Arantor/Elkarte
PHP | 1806 lines | 1423 code | 160 blank | 223 comment | 175 complexity | 1a1032bd69e22b684adb8192fcaf33ec MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file