2
0

ManagePaid.php 60 KB

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