ManagePaid.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  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('text', '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. validateToken('admin-pms');
  448. // Some cleaning...
  449. $isActive = isset($_POST['active']) ? 1 : 0;
  450. $isRepeatable = isset($_POST['repeatable']) ? 1 : 0;
  451. $allowpartial = isset($_POST['allow_partial']) ? 1 : 0;
  452. $reminder = isset($_POST['reminder']) ? (int) $_POST['reminder'] : 0;
  453. $emailComplete = strlen($_POST['emailcomplete']) > 10 ? trim($_POST['emailcomplete']) : '';
  454. // Is this a fixed one?
  455. if ($_POST['duration_type'] == 'fixed')
  456. {
  457. // Clean the span.
  458. $span = $_POST['span_value'] . $_POST['span_unit'];
  459. // Sort out the cost.
  460. $cost = array('fixed' => sprintf('%01.2f', strtr($_POST['cost'], ',', '.')));
  461. // There needs to be something.
  462. if (empty($_POST['span_value']) || empty($_POST['cost']))
  463. fatal_lang_error('paid_no_cost_value');
  464. }
  465. // Flexible is harder but more fun ;)
  466. else
  467. {
  468. $span = 'F';
  469. $cost = array(
  470. 'day' => sprintf('%01.2f', strtr($_POST['cost_day'], ',', '.')),
  471. 'week' => sprintf('%01.2f', strtr($_POST['cost_week'], ',', '.')),
  472. 'month' => sprintf('%01.2f', strtr($_POST['cost_month'], ',', '.')),
  473. 'year' => sprintf('%01.2f', strtr($_POST['cost_year'], ',', '.')),
  474. );
  475. if (empty($_POST['cost_day']) && empty($_POST['cost_week']) && empty($_POST['cost_month']) && empty($_POST['cost_year']))
  476. fatal_lang_error('paid_all_freq_blank');
  477. }
  478. $cost = serialize($cost);
  479. // Yep, time to do additional groups.
  480. $addgroups = array();
  481. if (!empty($_POST['addgroup']))
  482. foreach ($_POST['addgroup'] as $id => $dummy)
  483. $addgroups[] = (int) $id;
  484. $addgroups = implode(',', $addgroups);
  485. // Is it new?!
  486. if ($context['action_type'] == 'add')
  487. {
  488. $smcFunc['db_insert']('',
  489. '{db_prefix}subscriptions',
  490. array(
  491. 'name' => 'string-60', 'description' => 'string-255', 'active' => 'int', 'length' => 'string-4', 'cost' => 'string',
  492. 'id_group' => 'int', 'add_groups' => 'string-40', 'repeatable' => 'int', 'allow_partial' => 'int', 'email_complete' => 'string',
  493. 'reminder' => 'int',
  494. ),
  495. array(
  496. $_POST['name'], $_POST['desc'], $isActive, $span, $cost,
  497. $_POST['prim_group'], $addgroups, $isRepeatable, $allowpartial, $emailComplete,
  498. $reminder,
  499. ),
  500. array('id_subscribe')
  501. );
  502. }
  503. // Otherwise must be editing.
  504. else
  505. {
  506. // Don't do groups if there are active members
  507. $request = $smcFunc['db_query']('', '
  508. SELECT COUNT(*)
  509. FROM {db_prefix}log_subscribed
  510. WHERE id_subscribe = {int:current_subscription}
  511. AND status = {int:is_active}',
  512. array(
  513. 'current_subscription' => $context['sub_id'],
  514. 'is_active' => 1,
  515. )
  516. );
  517. list ($disableGroups) = $smcFunc['db_fetch_row']($request);
  518. $smcFunc['db_free_result']($request);
  519. $smcFunc['db_query']('substring', '
  520. UPDATE {db_prefix}subscriptions
  521. SET name = SUBSTRING({string:name}, 1, 60), description = SUBSTRING({string:description}, 1, 255), active = {int:is_active},
  522. length = SUBSTRING({string:length}, 1, 4), cost = {string:cost}' . ($disableGroups ? '' : ', id_group = {int:id_group},
  523. add_groups = {string:additional_groups}') . ', repeatable = {int:repeatable}, allow_partial = {int:allow_partial},
  524. email_complete = {string:email_complete}, reminder = {int:reminder}
  525. WHERE id_subscribe = {int:current_subscription}',
  526. array(
  527. 'is_active' => $isActive,
  528. 'id_group' => !empty($_POST['prim_group']) ? $_POST['prim_group'] : 0,
  529. 'repeatable' => $isRepeatable,
  530. 'allow_partial' => $allowpartial,
  531. 'reminder' => $reminder,
  532. 'current_subscription' => $context['sub_id'],
  533. 'name' => $_POST['name'],
  534. 'description' => $_POST['desc'],
  535. 'length' => $span,
  536. 'cost' => $cost,
  537. 'additional_groups' => !empty($addgroups) ? $addgroups : '',
  538. 'email_complete' => $emailComplete,
  539. )
  540. );
  541. }
  542. 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));
  543. redirectexit('action=admin;area=paidsubscribe;view');
  544. }
  545. // Defaults.
  546. if ($context['action_type'] == 'add')
  547. {
  548. $context['sub'] = array(
  549. 'name' => '',
  550. 'desc' => '',
  551. 'cost' => array(
  552. 'fixed' => 0,
  553. ),
  554. 'span' => array(
  555. 'value' => '',
  556. 'unit' => 'D',
  557. ),
  558. 'prim_group' => 0,
  559. 'add_groups' => array(),
  560. 'active' => 1,
  561. 'repeatable' => 1,
  562. 'allow_partial' => 0,
  563. 'duration' => 'fixed',
  564. 'email_complete' => '',
  565. 'reminder' => 0,
  566. );
  567. }
  568. // Otherwise load up all the details.
  569. else
  570. {
  571. $request = $smcFunc['db_query']('', '
  572. SELECT name, description, cost, length, id_group, add_groups, active, repeatable, allow_partial, email_complete, reminder
  573. FROM {db_prefix}subscriptions
  574. WHERE id_subscribe = {int:current_subscription}
  575. LIMIT 1',
  576. array(
  577. 'current_subscription' => $context['sub_id'],
  578. )
  579. );
  580. while ($row = $smcFunc['db_fetch_assoc']($request))
  581. {
  582. // Sort the date.
  583. preg_match('~(\d*)(\w)~', $row['length'], $match);
  584. if (isset($match[2]))
  585. {
  586. $span_value = $match[1];
  587. $span_unit = $match[2];
  588. }
  589. else
  590. {
  591. $span_value = 0;
  592. $span_unit = 'D';
  593. }
  594. // Is this a flexible one?
  595. if ($row['length'] == 'F')
  596. $isFlexible = true;
  597. else
  598. $isFlexible = false;
  599. $context['sub'] = array(
  600. 'name' => $row['name'],
  601. 'desc' => $row['description'],
  602. 'cost' => @unserialize($row['cost']),
  603. 'span' => array(
  604. 'value' => $span_value,
  605. 'unit' => $span_unit,
  606. ),
  607. 'prim_group' => $row['id_group'],
  608. 'add_groups' => explode(',', $row['add_groups']),
  609. 'active' => $row['active'],
  610. 'repeatable' => $row['repeatable'],
  611. 'allow_partial' => $row['allow_partial'],
  612. 'duration' => $isFlexible ? 'flexible' : 'fixed',
  613. 'email_complete' => $smcFunc['htmlspecialchars']($row['email_complete']),
  614. 'reminder' => $row['reminder'],
  615. );
  616. }
  617. $smcFunc['db_free_result']($request);
  618. // Does this have members who are active?
  619. $request = $smcFunc['db_query']('', '
  620. SELECT COUNT(*)
  621. FROM {db_prefix}log_subscribed
  622. WHERE id_subscribe = {int:current_subscription}
  623. AND status = {int:is_active}',
  624. array(
  625. 'current_subscription' => $context['sub_id'],
  626. 'is_active' => 1,
  627. )
  628. );
  629. list ($context['disable_groups']) = $smcFunc['db_fetch_row']($request);
  630. $smcFunc['db_free_result']($request);
  631. }
  632. // Load up all the groups.
  633. $request = $smcFunc['db_query']('', '
  634. SELECT id_group, group_name
  635. FROM {db_prefix}membergroups
  636. WHERE id_group != {int:moderator_group}
  637. AND min_posts = {int:min_posts}',
  638. array(
  639. 'moderator_group' => 3,
  640. 'min_posts' => -1,
  641. )
  642. );
  643. $context['groups'] = array();
  644. while ($row = $smcFunc['db_fetch_assoc']($request))
  645. $context['groups'][$row['id_group']] = $row['group_name'];
  646. $smcFunc['db_free_result']($request);
  647. // This always happens.
  648. createToken($context['action_type'] == 'delete' ? 'admin-pmsd' : 'admin-pms');
  649. }
  650. /**
  651. * View all the users subscribed to a particular subscription.
  652. * Requires the admin_forum permission.
  653. * Accessed from ?action=admin;area=paidsubscribe;sa=viewsub.
  654. *
  655. * Subscription ID is required, in the form of $_GET['sid'].
  656. */
  657. function ViewSubscribedUsers()
  658. {
  659. global $context, $txt, $scripturl, $smcFunc, $sourcedir;
  660. // Setup the template.
  661. $context['page_title'] = $txt['viewing_users_subscribed'];
  662. // ID of the subscription.
  663. $context['sub_id'] = (int) $_REQUEST['sid'];
  664. // Load the subscription information.
  665. $request = $smcFunc['db_query']('', '
  666. SELECT id_subscribe, name, description, cost, length, id_group, add_groups, active
  667. FROM {db_prefix}subscriptions
  668. WHERE id_subscribe = {int:current_subscription}',
  669. array(
  670. 'current_subscription' => $context['sub_id'],
  671. )
  672. );
  673. // Something wrong?
  674. if ($smcFunc['db_num_rows']($request) == 0)
  675. fatal_lang_error('no_access', false);
  676. // Do the subscription context.
  677. $row = $smcFunc['db_fetch_assoc']($request);
  678. $context['subscription'] = array(
  679. 'id' => $row['id_subscribe'],
  680. 'name' => $row['name'],
  681. 'desc' => $row['description'],
  682. 'active' => $row['active'],
  683. );
  684. $smcFunc['db_free_result']($request);
  685. // Are we searching for people?
  686. $search_string = isset($_POST['ssearch']) && !empty($_POST['sub_search']) ? ' AND IFNULL(mem.real_name, {string:guest}) LIKE {string:search}' : '';
  687. $search_vars = empty($_POST['sub_search']) ? array() : array('search' => '%' . $_POST['sub_search'] . '%', 'guest' => $txt['guest']);
  688. $listOptions = array(
  689. 'id' => 'subscribed_users_list',
  690. 'title' => sprintf($txt['view_users_subscribed'], $row['name']),
  691. 'items_per_page' => 20,
  692. 'base_href' => $scripturl . '?action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id'],
  693. 'default_sort_col' => 'name',
  694. 'get_items' => array(
  695. 'function' => 'list_getSubscribedUsers',
  696. 'params' => array(
  697. $context['sub_id'],
  698. $search_string,
  699. $search_vars,
  700. ),
  701. ),
  702. 'get_count' => array(
  703. 'function' => 'list_getSubscribedUserCount',
  704. 'params' => array(
  705. $context['sub_id'],
  706. $search_string,
  707. $search_vars,
  708. ),
  709. ),
  710. 'no_items_label' => $txt['no_subscribers'],
  711. 'columns' => array(
  712. 'name' => array(
  713. 'header' => array(
  714. 'value' => $txt['who_member'],
  715. 'style' => 'width: 20%;',
  716. ),
  717. 'data' => array(
  718. 'function' => create_function('$rowData', '
  719. global $context, $txt, $scripturl;
  720. return $rowData[\'id_member\'] == 0 ? $txt[\'guest\'] : \'<a href="\' . $scripturl . \'?action=profile;u=\' . $rowData[\'id_member\'] . \'">\' . $rowData[\'name\'] . \'</a>\';
  721. '),
  722. ),
  723. 'sort' => array(
  724. 'default' => 'name',
  725. 'reverse' => 'name DESC',
  726. ),
  727. ),
  728. 'status' => array(
  729. 'header' => array(
  730. 'value' => $txt['paid_status'],
  731. 'style' => 'width: 10%;',
  732. ),
  733. 'data' => array(
  734. 'db_htmlsafe' => 'status_text',
  735. ),
  736. 'sort' => array(
  737. 'default' => 'status',
  738. 'reverse' => 'status DESC',
  739. ),
  740. ),
  741. 'payments_pending' => array(
  742. 'header' => array(
  743. 'value' => $txt['paid_payments_pending'],
  744. 'style' => 'width: 15%;',
  745. ),
  746. 'data' => array(
  747. 'db_htmlsafe' => 'pending',
  748. ),
  749. 'sort' => array(
  750. 'default' => 'payments_pending',
  751. 'reverse' => 'payments_pending DESC',
  752. ),
  753. ),
  754. 'start_time' => array(
  755. 'header' => array(
  756. 'value' => $txt['start_date'],
  757. 'style' => 'width: 20%;',
  758. ),
  759. 'data' => array(
  760. 'db_htmlsafe' => 'start_date',
  761. 'class' => 'smalltext',
  762. ),
  763. 'sort' => array(
  764. 'default' => 'start_time',
  765. 'reverse' => 'start_time DESC',
  766. ),
  767. ),
  768. 'end_time' => array(
  769. 'header' => array(
  770. 'value' => $txt['end_date'],
  771. 'style' => 'width: 20%;',
  772. ),
  773. 'data' => array(
  774. 'db_htmlsafe' => 'end_date',
  775. 'class' => 'smalltext',
  776. ),
  777. 'sort' => array(
  778. 'default' => 'end_time',
  779. 'reverse' => 'end_time DESC',
  780. ),
  781. ),
  782. 'modify' => array(
  783. 'header' => array(
  784. 'style' => 'width: 10%;',
  785. 'class' => 'centercol',
  786. ),
  787. 'data' => array(
  788. 'function' => create_function('$rowData', '
  789. global $context, $txt, $scripturl;
  790. return \'<a href="\' . $scripturl . \'?action=admin;area=paidsubscribe;sa=modifyuser;lid=\' . $rowData[\'id\'] . \'">\' . $txt[\'modify\'] . \'</a>\';
  791. '),
  792. 'class' => 'centercol',
  793. ),
  794. ),
  795. 'delete' => array(
  796. 'header' => array(
  797. 'style' => 'width: 4%;',
  798. 'class' => 'centercol',
  799. ),
  800. 'data' => array(
  801. 'function' => create_function('$rowData', '
  802. global $context, $txt, $scripturl;
  803. return \'<input type="checkbox" name="delsub[\' . $rowData[\'id\'] . \']" class="input_check">\';
  804. '),
  805. 'class' => 'centercol',
  806. ),
  807. ),
  808. ),
  809. 'form' => array(
  810. 'href' => $scripturl . '?action=admin;area=paidsubscribe;sa=modifyuser;sid=' . $context['sub_id'],
  811. ),
  812. 'additional_rows' => array(
  813. array(
  814. 'position' => 'below_table_data',
  815. 'value' => '
  816. <input type="submit" name="add" value="' . $txt['add_subscriber'] . '" class="button_submit">
  817. <input type="submit" name="finished" value="' . $txt['complete_selected'] . '" onclick="return confirm(\'' . $txt['complete_are_sure'] . '\');" class="button_submit">
  818. <input type="submit" name="delete" value="' . $txt['delete_selected'] . '" onclick="return confirm(\'' . $txt['delete_are_sure'] . '\');" class="button_submit">
  819. ',
  820. ),
  821. array(
  822. 'position' => 'top_of_list',
  823. 'value' => '
  824. <div class="flow_auto">
  825. <input type="submit" name="ssearch" value="' . $txt['search_sub'] . '" class="button_submit" style="margin-top: 3px;">
  826. <input type="text" name="sub_search" value="" class="input_text floatright">
  827. </div>
  828. ',
  829. ),
  830. ),
  831. );
  832. require_once($sourcedir . '/Subs-List.php');
  833. createList($listOptions);
  834. $context['sub_template'] = 'show_list';
  835. $context['default_list'] = 'subscribed_users_list';
  836. }
  837. /**
  838. * Returns how many people are subscribed to a paid subscription.
  839. * @todo refactor away
  840. *
  841. * @param int $id_sub
  842. * @param string $search_string
  843. * @param array $search_vars = array()
  844. */
  845. function list_getSubscribedUserCount($id_sub, $search_string, $search_vars = array())
  846. {
  847. global $smcFunc;
  848. // Get the total amount of users.
  849. $request = $smcFunc['db_query']('', '
  850. SELECT COUNT(*) AS total_subs
  851. FROM {db_prefix}log_subscribed AS ls
  852. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
  853. WHERE ls.id_subscribe = {int:current_subscription} ' . $search_string . '
  854. AND (ls.end_time != {int:no_end_time} OR ls.payments_pending != {int:no_pending_payments})',
  855. array_merge($search_vars, array(
  856. 'current_subscription' => $id_sub,
  857. 'no_end_time' => 0,
  858. 'no_pending_payments' => 0,
  859. ))
  860. );
  861. list ($memberCount) = $smcFunc['db_fetch_row']($request);
  862. $smcFunc['db_free_result']($request);
  863. return $memberCount;
  864. }
  865. /**
  866. * Return the subscribed users list, for the given parameters.
  867. * @todo refactor outta here
  868. *
  869. * @param int $start
  870. * @param int $items_per_page
  871. * @param string $sort
  872. * @param int $id_sub
  873. * @param string $search_string
  874. * @param string $search_vars
  875. */
  876. function list_getSubscribedUsers($start, $items_per_page, $sort, $id_sub, $search_string, $search_vars = array())
  877. {
  878. global $smcFunc, $txt;
  879. $request = $smcFunc['db_query']('', '
  880. 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,
  881. ls.status, ls.payments_pending
  882. FROM {db_prefix}log_subscribed AS ls
  883. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
  884. WHERE ls.id_subscribe = {int:current_subscription} ' . $search_string . '
  885. AND (ls.end_time != {int:no_end_time} OR ls.payments_pending != {int:no_payments_pending})
  886. ORDER BY ' . $sort . '
  887. LIMIT ' . $start . ', ' . $items_per_page,
  888. array_merge($search_vars, array(
  889. 'current_subscription' => $id_sub,
  890. 'no_end_time' => 0,
  891. 'no_payments_pending' => 0,
  892. 'guest' => $txt['guest'],
  893. ))
  894. );
  895. $subscribers = array();
  896. while ($row = $smcFunc['db_fetch_assoc']($request))
  897. $subscribers[] = array(
  898. 'id' => $row['id_sublog'],
  899. 'id_member' => $row['id_member'],
  900. 'name' => $row['name'],
  901. 'start_date' => timeformat($row['start_time'], false),
  902. 'end_date' => $row['end_time'] == 0 ? 'N/A' : timeformat($row['end_time'], false),
  903. 'pending' => $row['payments_pending'],
  904. 'status' => $row['status'],
  905. 'status_text' => $row['status'] == 0 ? ($row['payments_pending'] == 0 ? $txt['paid_finished'] : $txt['paid_pending']) : $txt['paid_active'],
  906. );
  907. $smcFunc['db_free_result']($request);
  908. return $subscribers;
  909. }
  910. /**
  911. * Edit or add a user subscription.
  912. * Accessed from ?action=admin;area=paidsubscribe;sa=modifyuser.
  913. */
  914. function ModifyUserSubscription()
  915. {
  916. global $context, $txt, $modSettings, $smcFunc;
  917. loadSubscriptions();
  918. $context['log_id'] = isset($_REQUEST['lid']) ? (int) $_REQUEST['lid'] : 0;
  919. $context['sub_id'] = isset($_REQUEST['sid']) ? (int) $_REQUEST['sid'] : 0;
  920. $context['action_type'] = $context['log_id'] ? 'edit' : 'add';
  921. // Setup the template.
  922. $context['sub_template'] = 'modify_user_subscription';
  923. $context['page_title'] = $txt[$context['action_type'] . '_subscriber'];
  924. // If we haven't been passed the subscription ID get it.
  925. if ($context['log_id'] && !$context['sub_id'])
  926. {
  927. $request = $smcFunc['db_query']('', '
  928. SELECT id_subscribe
  929. FROM {db_prefix}log_subscribed
  930. WHERE id_sublog = {int:current_log_item}',
  931. array(
  932. 'current_log_item' => $context['log_id'],
  933. )
  934. );
  935. if ($smcFunc['db_num_rows']($request) == 0)
  936. fatal_lang_error('no_access', false);
  937. list ($context['sub_id']) = $smcFunc['db_fetch_row']($request);
  938. $smcFunc['db_free_result']($request);
  939. }
  940. if (!isset($context['subscriptions'][$context['sub_id']]))
  941. fatal_lang_error('no_access', false);
  942. $context['current_subscription'] = $context['subscriptions'][$context['sub_id']];
  943. // Searching?
  944. if (isset($_POST['ssearch']))
  945. {
  946. return ViewSubscribedUsers();
  947. }
  948. // Saving?
  949. elseif (isset($_REQUEST['save_sub']))
  950. {
  951. checkSession();
  952. // Work out the dates...
  953. $starttime = mktime($_POST['hour'], $_POST['minute'], 0, $_POST['month'], $_POST['day'], $_POST['year']);
  954. $endtime = mktime($_POST['hourend'], $_POST['minuteend'], 0, $_POST['monthend'], $_POST['dayend'], $_POST['yearend']);
  955. // Status.
  956. $status = $_POST['status'];
  957. // New one?
  958. if (empty($context['log_id']))
  959. {
  960. // Find the user...
  961. $request = $smcFunc['db_query']('', '
  962. SELECT id_member, id_group
  963. FROM {db_prefix}members
  964. WHERE real_name = {string:name}
  965. LIMIT 1',
  966. array(
  967. 'name' => $_POST['name'],
  968. )
  969. );
  970. if ($smcFunc['db_num_rows']($request) == 0)
  971. fatal_lang_error('error_member_not_found');
  972. list ($id_member, $id_group) = $smcFunc['db_fetch_row']($request);
  973. $smcFunc['db_free_result']($request);
  974. // Ensure the member doesn't already have a subscription!
  975. $request = $smcFunc['db_query']('', '
  976. SELECT id_subscribe
  977. FROM {db_prefix}log_subscribed
  978. WHERE id_subscribe = {int:current_subscription}
  979. AND id_member = {int:current_member}',
  980. array(
  981. 'current_subscription' => $context['sub_id'],
  982. 'current_member' => $id_member,
  983. )
  984. );
  985. if ($smcFunc['db_num_rows']($request) != 0)
  986. fatal_lang_error('member_already_subscribed');
  987. $smcFunc['db_free_result']($request);
  988. // Actually put the subscription in place.
  989. if ($status == 1)
  990. addSubscription($context['sub_id'], $id_member, 0, $starttime, $endtime);
  991. else
  992. {
  993. $smcFunc['db_insert']('',
  994. '{db_prefix}log_subscribed',
  995. array(
  996. 'id_subscribe' => 'int', 'id_member' => 'int', 'old_id_group' => 'int', 'start_time' => 'int',
  997. 'end_time' => 'int', 'status' => 'int',
  998. ),
  999. array(
  1000. $context['sub_id'], $id_member, $id_group, $starttime,
  1001. $endtime, $status,
  1002. ),
  1003. array('id_sublog')
  1004. );
  1005. }
  1006. }
  1007. // Updating.
  1008. else
  1009. {
  1010. $request = $smcFunc['db_query']('', '
  1011. SELECT id_member, status
  1012. FROM {db_prefix}log_subscribed
  1013. WHERE id_sublog = {int:current_log_item}',
  1014. array(
  1015. 'current_log_item' => $context['log_id'],
  1016. )
  1017. );
  1018. if ($smcFunc['db_num_rows']($request) == 0)
  1019. fatal_lang_error('no_access', false);
  1020. list ($id_member, $old_status) = $smcFunc['db_fetch_row']($request);
  1021. $smcFunc['db_free_result']($request);
  1022. // Pick the right permission stuff depending on what the status is changing from/to.
  1023. if ($old_status == 1 && $status != 1)
  1024. removeSubscription($context['sub_id'], $id_member);
  1025. elseif ($status == 1 && $old_status != 1)
  1026. {
  1027. addSubscription($context['sub_id'], $id_member, 0, $starttime, $endtime);
  1028. }
  1029. else
  1030. {
  1031. $smcFunc['db_query']('', '
  1032. UPDATE {db_prefix}log_subscribed
  1033. SET start_time = {int:start_time}, end_time = {int:end_time}, status = {int:status}
  1034. WHERE id_sublog = {int:current_log_item}',
  1035. array(
  1036. 'start_time' => $starttime,
  1037. 'end_time' => $endtime,
  1038. 'status' => $status,
  1039. 'current_log_item' => $context['log_id'],
  1040. )
  1041. );
  1042. }
  1043. }
  1044. // Done - redirect...
  1045. redirectexit('action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id']);
  1046. }
  1047. // Deleting?
  1048. elseif (isset($_REQUEST['delete']) || isset($_REQUEST['finished']))
  1049. {
  1050. checkSession();
  1051. // Do the actual deletes!
  1052. if (!empty($_REQUEST['delsub']))
  1053. {
  1054. $toDelete = array();
  1055. foreach ($_REQUEST['delsub'] as $id => $dummy)
  1056. $toDelete[] = (int) $id;
  1057. $request = $smcFunc['db_query']('', '
  1058. SELECT id_subscribe, id_member
  1059. FROM {db_prefix}log_subscribed
  1060. WHERE id_sublog IN ({array_int:subscription_list})',
  1061. array(
  1062. 'subscription_list' => $toDelete,
  1063. )
  1064. );
  1065. while ($row = $smcFunc['db_fetch_assoc']($request))
  1066. removeSubscription($row['id_subscribe'], $row['id_member'], isset($_REQUEST['delete']));
  1067. $smcFunc['db_free_result']($request);
  1068. }
  1069. redirectexit('action=admin;area=paidsubscribe;sa=viewsub;sid=' . $context['sub_id']);
  1070. }
  1071. // Default attributes.
  1072. if ($context['action_type'] == 'add')
  1073. {
  1074. $context['sub'] = array(
  1075. 'id' => 0,
  1076. 'start' => array(
  1077. 'year' => (int) strftime('%Y', time()),
  1078. 'month' => (int) strftime('%m', time()),
  1079. 'day' => (int) strftime('%d', time()),
  1080. 'hour' => (int) strftime('%H', time()),
  1081. 'min' => (int) strftime('%M', time()) < 10 ? '0' . (int) strftime('%M', time()) : (int) strftime('%M', time()),
  1082. 'last_day' => 0,
  1083. ),
  1084. 'end' => array(
  1085. 'year' => (int) strftime('%Y', time()),
  1086. 'month' => (int) strftime('%m', time()),
  1087. 'day' => (int) strftime('%d', time()),
  1088. 'hour' => (int) strftime('%H', time()),
  1089. 'min' => (int) strftime('%M', time()) < 10 ? '0' . (int) strftime('%M', time()) : (int) strftime('%M', time()),
  1090. 'last_day' => 0,
  1091. ),
  1092. 'status' => 1,
  1093. );
  1094. $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']));
  1095. $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']));
  1096. if (isset($_GET['uid']))
  1097. {
  1098. $request = $smcFunc['db_query']('', '
  1099. SELECT real_name
  1100. FROM {db_prefix}members
  1101. WHERE id_member = {int:current_member}',
  1102. array(
  1103. 'current_member' => (int) $_GET['uid'],
  1104. )
  1105. );
  1106. list ($context['sub']['username']) = $smcFunc['db_fetch_row']($request);
  1107. $smcFunc['db_free_result']($request);
  1108. }
  1109. else
  1110. $context['sub']['username'] = '';
  1111. }
  1112. // Otherwise load the existing info.
  1113. else
  1114. {
  1115. $request = $smcFunc['db_query']('', '
  1116. SELECT ls.id_sublog, ls.id_subscribe, ls.id_member, start_time, end_time, status, payments_pending, pending_details,
  1117. IFNULL(mem.real_name, {string:blank_string}) AS username
  1118. FROM {db_prefix}log_subscribed AS ls
  1119. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
  1120. WHERE ls.id_sublog = {int:current_subscription_item}
  1121. LIMIT 1',
  1122. array(
  1123. 'current_subscription_item' => $context['log_id'],
  1124. 'blank_string' => '',
  1125. )
  1126. );
  1127. if ($smcFunc['db_num_rows']($request) == 0)
  1128. fatal_lang_error('no_access', false);
  1129. $row = $smcFunc['db_fetch_assoc']($request);
  1130. $smcFunc['db_free_result']($request);
  1131. // Any pending payments?
  1132. $context['pending_payments'] = array();
  1133. if (!empty($row['pending_details']))
  1134. {
  1135. $pending_details = @unserialize($row['pending_details']);
  1136. foreach ($pending_details as $id => $pending)
  1137. {
  1138. // Only this type need be displayed.
  1139. if ($pending[3] == 'payback')
  1140. {
  1141. // Work out what the options were.
  1142. $costs = @unserialize($context['current_subscription']['real_cost']);
  1143. if ($context['current_subscription']['real_length'] == 'F')
  1144. {
  1145. foreach ($costs as $duration => $cost)
  1146. {
  1147. if ($cost != 0 && $cost == $pending[1] && $duration == $pending[2])
  1148. $context['pending_payments'][$id] = array(
  1149. 'desc' => sprintf($modSettings['paid_currency_symbol'], $cost . '/' . $txt[$duration]),
  1150. );
  1151. }
  1152. }
  1153. elseif ($costs['fixed'] == $pending[1])
  1154. {
  1155. $context['pending_payments'][$id] = array(
  1156. 'desc' => sprintf($modSettings['paid_currency_symbol'], $costs['fixed']),
  1157. );
  1158. }
  1159. }
  1160. }
  1161. // Check if we are adding/removing any.
  1162. if (isset($_GET['pending']))
  1163. {
  1164. foreach ($pending_details as $id => $pending)
  1165. {
  1166. // Found the one to action?
  1167. if ($_GET['pending'] == $id && $pending[3] == 'payback' && isset($context['pending_payments'][$id]))
  1168. {
  1169. // Flexible?
  1170. if (isset($_GET['accept']))
  1171. addSubscription($context['current_subscription']['id'], $row['id_member'], $context['current_subscription']['real_length'] == 'F' ? strtoupper(substr($pending[2], 0, 1)) : 0);
  1172. unset($pending_details[$id]);
  1173. $new_details = serialize($pending_details);
  1174. // Update the entry.
  1175. $smcFunc['db_query']('', '
  1176. UPDATE {db_prefix}log_subscribed
  1177. SET payments_pending = payments_pending - 1, pending_details = {string:pending_details}
  1178. WHERE id_sublog = {int:current_subscription_item}',
  1179. array(
  1180. 'current_subscription_item' => $context['log_id'],
  1181. 'pending_details' => $new_details,
  1182. )
  1183. );
  1184. // Reload
  1185. redirectexit('action=admin;area=paidsubscribe;sa=modifyuser;lid=' . $context['log_id']);
  1186. }
  1187. }
  1188. }
  1189. }
  1190. $context['sub_id'] = $row['id_subscribe'];
  1191. $context['sub'] = array(
  1192. 'id' => 0,
  1193. 'start' => array(
  1194. 'year' => (int) strftime('%Y', $row['start_time']),
  1195. 'month' => (int) strftime('%m', $row['start_time']),
  1196. 'day' => (int) strftime('%d', $row['start_time']),
  1197. 'hour' => (int) strftime('%H', $row['start_time']),
  1198. 'min' => (int) strftime('%M', $row['start_time']) < 10 ? '0' . (int) strftime('%M', $row['start_time']) : (int) strftime('%M', $row['start_time']),
  1199. 'last_day' => 0,
  1200. ),
  1201. 'end' => array(
  1202. 'year' => (int) strftime('%Y', $row['end_time']),
  1203. 'month' => (int) strftime('%m', $row['end_time']),
  1204. 'day' => (int) strftime('%d', $row['end_time']),
  1205. 'hour' => (int) strftime('%H', $row['end_time']),
  1206. 'min' => (int) strftime('%M', $row['end_time']) < 10 ? '0' . (int) strftime('%M', $row['end_time']) : (int) strftime('%M', $row['end_time']),
  1207. 'last_day' => 0,
  1208. ),
  1209. 'status' => $row['status'],
  1210. 'username' => $row['username'],
  1211. );
  1212. $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']));
  1213. $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']));
  1214. }
  1215. }
  1216. /**
  1217. * Reapplies all subscription rules for each of the users.
  1218. *
  1219. * @param array $users
  1220. */
  1221. function reapplySubscriptions($users)
  1222. {
  1223. global $smcFunc;
  1224. // Make it an array.
  1225. if (!is_array($users))
  1226. $users = array($users);
  1227. // Get all the members current groups.
  1228. $groups = array();
  1229. $request = $smcFunc['db_query']('', '
  1230. SELECT id_member, id_group, additional_groups
  1231. FROM {db_prefix}members
  1232. WHERE id_member IN ({array_int:user_list})',
  1233. array(
  1234. 'user_list' => $users,
  1235. )
  1236. );
  1237. while ($row = $smcFunc['db_fetch_assoc']($request))
  1238. {
  1239. $groups[$row['id_member']] = array(
  1240. 'primary' => $row['id_group'],
  1241. 'additional' => explode(',', $row['additional_groups']),
  1242. );
  1243. }
  1244. $smcFunc['db_free_result']($request);
  1245. $request = $smcFunc['db_query']('', '
  1246. SELECT ls.id_member, ls.old_id_group, s.id_group, s.add_groups
  1247. FROM {db_prefix}log_subscribed AS ls
  1248. INNER JOIN {db_prefix}subscriptions AS s ON (s.id_subscribe = ls.id_subscribe)
  1249. WHERE ls.id_member IN ({array_int:user_list})
  1250. AND ls.end_time > {int:current_time}',
  1251. array(
  1252. 'user_list' => $users,
  1253. 'current_time' => time(),
  1254. )
  1255. );
  1256. while ($row = $smcFunc['db_fetch_assoc']($request))
  1257. {
  1258. // Specific primary group?
  1259. if ($row['id_group'] != 0)
  1260. {
  1261. // If this is changing - add the old one to the additional groups so it's not lost.
  1262. if ($row['id_group'] != $groups[$row['id_member']]['primary'])
  1263. $groups[$row['id_member']]['additional'][] = $groups[$row['id_member']]['primary'];
  1264. $groups[$row['id_member']]['primary'] = $row['id_group'];
  1265. }
  1266. // Additional groups.
  1267. if (!empty($row['add_groups']))
  1268. $groups[$row['id_member']]['additional'] = array_merge($groups[$row['id_member']]['additional'], explode(',', $row['add_groups']));
  1269. }
  1270. $smcFunc['db_free_result']($request);
  1271. // Update all the members.
  1272. foreach ($groups as $id => $group)
  1273. {
  1274. $group['additional'] = array_unique($group['additional']);
  1275. foreach ($group['additional'] as $key => $value)
  1276. if (empty($value))
  1277. unset($group['additional'][$key]);
  1278. $addgroups = implode(',', $group['additional']);
  1279. $smcFunc['db_query']('', '
  1280. UPDATE {db_prefix}members
  1281. SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
  1282. WHERE id_member = {int:current_member}
  1283. LIMIT 1',
  1284. array(
  1285. 'primary_group' => $group['primary'],
  1286. 'current_member' => $id,
  1287. 'additional_groups' => $addgroups,
  1288. )
  1289. );
  1290. }
  1291. }
  1292. /**
  1293. * Add or extend a subscription of a user.
  1294. *
  1295. * @param int $id_subscribe
  1296. * @param int $id_member
  1297. * @param string $renewal = 0, options 'D', 'W', 'M', 'Y'
  1298. * @param int $forceStartTime = 0
  1299. * @param int $forceEndTime = 0
  1300. */
  1301. function addSubscription($id_subscribe, $id_member, $renewal = 0, $forceStartTime = 0, $forceEndTime = 0)
  1302. {
  1303. global $context, $smcFunc;
  1304. // Take the easy way out...
  1305. loadSubscriptions();
  1306. // Exists, yes?
  1307. if (!isset($context['subscriptions'][$id_subscribe]))
  1308. return;
  1309. $curSub = $context['subscriptions'][$id_subscribe];
  1310. // Grab the duration.
  1311. $duration = $curSub['num_length'];
  1312. // If this is a renewal change the duration to be correct.
  1313. if (!empty($renewal))
  1314. {
  1315. switch ($renewal)
  1316. {
  1317. case 'D':
  1318. $duration = 86400;
  1319. break;
  1320. case 'W':
  1321. $duration = 604800;
  1322. break;
  1323. case 'M':
  1324. $duration = 2629743;
  1325. break;
  1326. case 'Y':
  1327. $duration = 31556926;
  1328. break;
  1329. default:
  1330. break;
  1331. }
  1332. }
  1333. // Firstly, see whether it exists, and is active. If so then this is meerly an extension.
  1334. $request = $smcFunc['db_query']('', '
  1335. SELECT id_sublog, end_time, start_time
  1336. FROM {db_prefix}log_subscribed
  1337. WHERE id_subscribe = {int:current_subscription}
  1338. AND id_member = {int:current_member}
  1339. AND status = {int:is_active}',
  1340. array(
  1341. 'current_subscription' => $id_subscribe,
  1342. 'current_member' => $id_member,
  1343. 'is_active' => 1,
  1344. )
  1345. );
  1346. if ($smcFunc['db_num_rows']($request) != 0)
  1347. {
  1348. list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
  1349. // If this has already expired but is active, extension means the period from now.
  1350. if ($endtime < time())
  1351. $endtime = time();
  1352. if ($starttime == 0)
  1353. $starttime = time();
  1354. // Work out the new expiry date.
  1355. $endtime += $duration;
  1356. if ($forceEndTime != 0)
  1357. $endtime = $forceEndTime;
  1358. // As everything else should be good, just update!
  1359. $smcFunc['db_query']('', '
  1360. UPDATE {db_prefix}log_subscribed
  1361. SET end_time = {int:end_time}, start_time = {int:start_time}, reminder_sent = {int:no_reminder_sent}
  1362. WHERE id_sublog = {int:current_subscription_item}',
  1363. array(
  1364. 'end_time' => $endtime,
  1365. 'start_time' => $starttime,
  1366. 'current_subscription_item' => $id_sublog,
  1367. 'no_reminder_sent' => 0,
  1368. )
  1369. );
  1370. return;
  1371. }
  1372. $smcFunc['db_free_result']($request);
  1373. // If we're here, that means we don't have an active subscription - that means we need to do some work!
  1374. $request = $smcFunc['db_query']('', '
  1375. SELECT m.id_group, m.additional_groups
  1376. FROM {db_prefix}members AS m
  1377. WHERE m.id_member = {int:current_member}',
  1378. array(
  1379. 'current_member' => $id_member,
  1380. )
  1381. );
  1382. // Just in case the member doesn't exist.
  1383. if ($smcFunc['db_num_rows']($request) == 0)
  1384. return;
  1385. list ($old_id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
  1386. $smcFunc['db_free_result']($request);
  1387. // Prepare additional groups.
  1388. $newAddGroups = explode(',', $curSub['add_groups']);
  1389. $curAddGroups = explode(',', $additional_groups);
  1390. $newAddGroups = array_merge($newAddGroups, $curAddGroups);
  1391. // Simple, simple, simple - hopefully... id_group first.
  1392. if ($curSub['prim_group'] != 0)
  1393. {
  1394. $id_group = $curSub['prim_group'];
  1395. // Ensure their old privileges are maintained.
  1396. if ($old_id_group != 0)
  1397. $newAddGroups[] = $old_id_group;
  1398. }
  1399. else
  1400. $id_group = $old_id_group;
  1401. // Yep, make sure it's unique, and no empties.
  1402. foreach ($newAddGroups as $k => $v)
  1403. if (empty($v))
  1404. unset($newAddGroups[$k]);
  1405. $newAddGroups = array_unique($newAddGroups);
  1406. $newAddGroups = implode(',', $newAddGroups);
  1407. // Store the new settings.
  1408. $smcFunc['db_query']('', '
  1409. UPDATE {db_prefix}members
  1410. SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
  1411. WHERE id_member = {int:current_member}',
  1412. array(
  1413. 'primary_group' => $id_group,
  1414. 'current_member' => $id_member,
  1415. 'additional_groups' => $newAddGroups,
  1416. )
  1417. );
  1418. // Now log the subscription - maybe we have a dorment subscription we can restore?
  1419. $request = $smcFunc['db_query']('', '
  1420. SELECT id_sublog, end_time, start_time
  1421. FROM {db_prefix}log_subscribed
  1422. WHERE id_subscribe = {int:current_subscription}
  1423. AND id_member = {int:current_member}',
  1424. array(
  1425. 'current_subscription' => $id_subscribe,
  1426. 'current_member' => $id_member,
  1427. )
  1428. );
  1429. /**
  1430. * @todo Don't really need to do this twice...
  1431. */
  1432. if ($smcFunc['db_num_rows']($request) != 0)
  1433. {
  1434. list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
  1435. // If this has already expired but is active, extension means the period from now.
  1436. if ($endtime < time())
  1437. $endtime = time();
  1438. if ($starttime == 0)
  1439. $starttime = time();
  1440. // Work out the new expiry date.
  1441. $endtime += $duration;
  1442. if ($forceEndTime != 0)
  1443. $endtime = $forceEndTime;
  1444. // As everything else should be good, just update!
  1445. $smcFunc['db_query']('', '
  1446. UPDATE {db_prefix}log_subscribed
  1447. 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}
  1448. WHERE id_sublog = {int:current_subscription_item}',
  1449. array(
  1450. 'start_time' => $starttime,
  1451. 'end_time' => $endtime,
  1452. 'old_id_group' => $old_id_group,
  1453. 'is_active' => 1,
  1454. 'no_reminder_sent' => 0,
  1455. 'current_subscription_item' => $id_sublog,
  1456. )
  1457. );
  1458. return;
  1459. }
  1460. $smcFunc['db_free_result']($request);
  1461. // Otherwise a very simple insert.
  1462. $endtime = time() + $duration;
  1463. if ($forceEndTime != 0)
  1464. $endtime = $forceEndTime;
  1465. if ($forceStartTime == 0)
  1466. $starttime = time();
  1467. else
  1468. $starttime = $forceStartTime;
  1469. $smcFunc['db_insert']('',
  1470. '{db_prefix}log_subscribed',
  1471. array(
  1472. 'id_subscribe' => 'int', 'id_member' => 'int', 'old_id_group' => 'int', 'start_time' => 'int',
  1473. 'end_time' => 'int', 'status' => 'int', 'pending_details' => 'string',
  1474. ),
  1475. array(
  1476. $id_subscribe, $id_member, $old_id_group, $starttime,
  1477. $endtime, 1, '',
  1478. ),
  1479. array('id_sublog')
  1480. );
  1481. }
  1482. /**
  1483. * Removes a subscription from a user, as in removes the groups.
  1484. *
  1485. * @param $id_subscribe
  1486. * @param $id_member
  1487. * @param $delete
  1488. */
  1489. function removeSubscription($id_subscribe, $id_member, $delete = false)
  1490. {
  1491. global $context, $smcFunc;
  1492. loadSubscriptions();
  1493. // Load the user core bits.
  1494. $request = $smcFunc['db_query']('', '
  1495. SELECT m.id_group, m.additional_groups
  1496. FROM {db_prefix}members AS m
  1497. WHERE m.id_member = {int:current_member}',
  1498. array(
  1499. 'current_member' => $id_member,
  1500. )
  1501. );
  1502. // Just in case of errors.
  1503. if ($smcFunc['db_num_rows']($request) == 0)
  1504. {
  1505. $smcFunc['db_query']('', '
  1506. DELETE FROM {db_prefix}log_subscribed
  1507. WHERE id_member = {int:current_member}',
  1508. array(
  1509. 'current_member' => $id_member,
  1510. )
  1511. );
  1512. return;
  1513. }
  1514. list ($id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
  1515. $smcFunc['db_free_result']($request);
  1516. // Get all of the subscriptions for this user that are active - it will be necessary!
  1517. $request = $smcFunc['db_query']('', '
  1518. SELECT id_subscribe, old_id_group
  1519. FROM {db_prefix}log_subscribed
  1520. WHERE id_member = {int:current_member}
  1521. AND status = {int:is_active}',
  1522. array(
  1523. 'current_member' => $id_member,
  1524. 'is_active' => 1,
  1525. )
  1526. );
  1527. // These variables will be handy, honest ;)
  1528. $removals = array();
  1529. $allowed = array();
  1530. $old_id_group = 0;
  1531. $new_id_group = -1;
  1532. while ($row = $smcFunc['db_fetch_assoc']($request))
  1533. {
  1534. if (!isset($context['subscriptions'][$row['id_subscribe']]))
  1535. continue;
  1536. // The one we're removing?
  1537. if ($row['id_subscribe'] == $id_subscribe)
  1538. {
  1539. $removals = explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']);
  1540. if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
  1541. $removals[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1542. $old_id_group = $row['old_id_group'];
  1543. }
  1544. // Otherwise things we allow.
  1545. else
  1546. {
  1547. $allowed = array_merge($allowed, explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']));
  1548. if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
  1549. {
  1550. $allowed[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1551. $new_id_group = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1552. }
  1553. }
  1554. }
  1555. $smcFunc['db_free_result']($request);
  1556. // Now, for everything we are removing check they defintely are not allowed it.
  1557. $existingGroups = explode(',', $additional_groups);
  1558. foreach ($existingGroups as $key => $group)
  1559. if (empty($group) || (in_array($group, $removals) && !in_array($group, $allowed)))
  1560. unset($existingGroups[$key]);
  1561. // Finally, do something with the current primary group.
  1562. if (in_array($id_group, $removals))
  1563. {
  1564. // If this primary group is actually allowed keep it.
  1565. if (in_array($id_group, $allowed))
  1566. $existingGroups[] = $id_group;
  1567. // Either way, change the id_group back.
  1568. if ($new_id_group < 1)
  1569. {
  1570. // If we revert to the old id-group we need to ensure it wasn't from a subscription.
  1571. foreach ($context['subscriptions'] as $id => $group)
  1572. // It was? Make them a regular member then!
  1573. if ($group['prim_group'] == $old_id_group)
  1574. $old_id_group = 0;
  1575. $id_group = $old_id_group;
  1576. }
  1577. else
  1578. $id_group = $new_id_group;
  1579. }
  1580. // Crazy stuff, we seem to have our groups fixed, just make them unique
  1581. $existingGroups = array_unique($existingGroups);
  1582. $existingGroups = implode(',', $existingGroups);
  1583. // Update the member
  1584. $smcFunc['db_query']('', '
  1585. UPDATE {db_prefix}members
  1586. SET id_group = {int:primary_group}, additional_groups = {string:existing_groups}
  1587. WHERE id_member = {int:current_member}',
  1588. array(
  1589. 'primary_group' => $id_group,
  1590. 'current_member' => $id_member,
  1591. 'existing_groups' => $existingGroups,
  1592. )
  1593. );
  1594. // Disable the subscription.
  1595. if (!$delete)
  1596. $smcFunc['db_query']('', '
  1597. UPDATE {db_prefix}log_subscribed
  1598. SET status = {int:not_active}
  1599. WHERE id_member = {int:current_member}
  1600. AND id_subscribe = {int:current_subscription}',
  1601. array(
  1602. 'not_active' => 0,
  1603. 'current_member' => $id_member,
  1604. 'current_subscription' => $id_subscribe,
  1605. )
  1606. );
  1607. // Otherwise delete it!
  1608. else
  1609. $smcFunc['db_query']('', '
  1610. DELETE FROM {db_prefix}log_subscribed
  1611. WHERE id_member = {int:current_member}
  1612. AND id_subscribe = {int:current_subscription}',
  1613. array(
  1614. 'current_member' => $id_member,
  1615. 'current_subscription' => $id_subscribe,
  1616. )
  1617. );
  1618. }
  1619. /**
  1620. * This just kind of caches all the subscription data.
  1621. */
  1622. function loadSubscriptions()
  1623. {
  1624. global $context, $txt, $modSettings, $smcFunc;
  1625. if (!empty($context['subscriptions']))
  1626. return;
  1627. // Make sure this is loaded, just in case.
  1628. loadLanguage('ManagePaid');
  1629. $request = $smcFunc['db_query']('', '
  1630. SELECT id_subscribe, name, description, cost, length, id_group, add_groups, active, repeatable
  1631. FROM {db_prefix}subscriptions',
  1632. array(
  1633. )
  1634. );
  1635. $context['subscriptions'] = array();
  1636. while ($row = $smcFunc['db_fetch_assoc']($request))
  1637. {
  1638. // Pick a cost.
  1639. $costs = @unserialize($row['cost']);
  1640. if ($row['length'] != 'F' && !empty($modSettings['paid_currency_symbol']) && !empty($costs['fixed']))
  1641. $cost = sprintf($modSettings['paid_currency_symbol'], $costs['fixed']);
  1642. else
  1643. $cost = '???';
  1644. // Do the span.
  1645. preg_match('~(\d*)(\w)~', $row['length'], $match);
  1646. if (isset($match[2]))
  1647. {
  1648. $num_length = $match[1];
  1649. $length = $match[1] . ' ';
  1650. switch ($match[2])
  1651. {
  1652. case 'D':
  1653. $length .= $txt['paid_mod_span_days'];
  1654. $num_length *= 86400;
  1655. break;
  1656. case 'W':
  1657. $length .= $txt['paid_mod_span_weeks'];
  1658. $num_length *= 604800;
  1659. break;
  1660. case 'M':
  1661. $length .= $txt['paid_mod_span_months'];
  1662. $num_length *= 2629743;
  1663. break;
  1664. case 'Y':
  1665. $length .= $txt['paid_mod_span_years'];
  1666. $num_length *= 31556926;
  1667. break;
  1668. }
  1669. }
  1670. else
  1671. $length = '??';
  1672. $context['subscriptions'][$row['id_subscribe']] = array(
  1673. 'id' => $row['id_subscribe'],
  1674. 'name' => $row['name'],
  1675. 'desc' => $row['description'],
  1676. 'cost' => $cost,
  1677. 'real_cost' => $row['cost'],
  1678. 'length' => $length,
  1679. 'num_length' => $num_length,
  1680. 'real_length' => $row['length'],
  1681. 'pending' => 0,
  1682. 'finished' => 0,
  1683. 'total' => 0,
  1684. 'active' => $row['active'],
  1685. 'prim_group' => $row['id_group'],
  1686. 'add_groups' => $row['add_groups'],
  1687. 'flexible' => $row['length'] == 'F' ? true : false,
  1688. 'repeatable' => $row['repeatable'],
  1689. );
  1690. }
  1691. $smcFunc['db_free_result']($request);
  1692. // Do the counts.
  1693. $request = $smcFunc['db_query']('', '
  1694. SELECT COUNT(id_sublog) AS member_count, id_subscribe, status
  1695. FROM {db_prefix}log_subscribed
  1696. GROUP BY id_subscribe, status',
  1697. array(
  1698. )
  1699. );
  1700. while ($row = $smcFunc['db_fetch_assoc']($request))
  1701. {
  1702. $ind = $row['status'] == 0 ? 'finished' : 'total';
  1703. if (isset($context['subscriptions'][$row['id_subscribe']]))
  1704. $context['subscriptions'][$row['id_subscribe']][$ind] = $row['member_count'];
  1705. }
  1706. $smcFunc['db_free_result']($request);
  1707. // How many payments are we waiting on?
  1708. $request = $smcFunc['db_query']('', '
  1709. SELECT SUM(payments_pending) AS total_pending, id_subscribe
  1710. FROM {db_prefix}log_subscribed
  1711. GROUP BY id_subscribe',
  1712. array(
  1713. )
  1714. );
  1715. while ($row = $smcFunc['db_fetch_assoc']($request))
  1716. {
  1717. if (isset($context['subscriptions'][$row['id_subscribe']]))
  1718. $context['subscriptions'][$row['id_subscribe']]['pending'] = $row['total_pending'];
  1719. }
  1720. $smcFunc['db_free_result']($request);
  1721. }
  1722. /**
  1723. * Load all the payment gateways.
  1724. * Checks the Sources directory for any files fitting the format of a payment gateway,
  1725. * loads each file to check it's valid, includes each file and returns the
  1726. * function name and whether it should work with this version of SMF.
  1727. *
  1728. * @return array
  1729. */
  1730. function loadPaymentGateways()
  1731. {
  1732. global $sourcedir;
  1733. $gateways = array();
  1734. if ($dh = opendir($sourcedir))
  1735. {
  1736. while (($file = readdir($dh)) !== false)
  1737. {
  1738. if (is_file($sourcedir .'/'. $file) && preg_match('~^Subscriptions-([A-Za-z\d]+)\.php$~', $file, $matches))
  1739. {
  1740. // Check this is definitely a valid gateway!
  1741. $fp = fopen($sourcedir . '/' . $file, 'rb');
  1742. $header = fread($fp, 4096);
  1743. fclose($fp);
  1744. if (strpos($header, '// SMF Payment Gateway: ' . strtolower($matches[1])) !== false)
  1745. {
  1746. require_once($sourcedir . '/' . $file);
  1747. $gateways[] = array(
  1748. 'filename' => $file,
  1749. 'code' => strtolower($matches[1]),
  1750. // Don't need anything snazier than this yet.
  1751. 'valid_version' => class_exists(strtolower($matches[1]) . '_payment') && class_exists(strtolower($matches[1]) . '_display'),
  1752. 'payment_class' => strtolower($matches[1]) . '_payment',
  1753. 'display_class' => strtolower($matches[1]) . '_display',
  1754. );
  1755. }
  1756. }
  1757. }
  1758. }
  1759. closedir($dh);
  1760. return $gateways;
  1761. }
  1762. ?>