ManagePaid.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  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. // 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. }
  1228. /**
  1229. * Reapplies all subscription rules for each of the users.
  1230. *
  1231. * @param array $users
  1232. */
  1233. function reapplySubscriptions($users)
  1234. {
  1235. global $smcFunc;
  1236. // Make it an array.
  1237. if (!is_array($users))
  1238. $users = array($users);
  1239. // Get all the members current groups.
  1240. $groups = array();
  1241. $request = $smcFunc['db_query']('', '
  1242. SELECT id_member, id_group, additional_groups
  1243. FROM {db_prefix}members
  1244. WHERE id_member IN ({array_int:user_list})',
  1245. array(
  1246. 'user_list' => $users,
  1247. )
  1248. );
  1249. while ($row = $smcFunc['db_fetch_assoc']($request))
  1250. {
  1251. $groups[$row['id_member']] = array(
  1252. 'primary' => $row['id_group'],
  1253. 'additional' => explode(',', $row['additional_groups']),
  1254. );
  1255. }
  1256. $smcFunc['db_free_result']($request);
  1257. $request = $smcFunc['db_query']('', '
  1258. SELECT ls.id_member, ls.old_id_group, s.id_group, s.add_groups
  1259. FROM {db_prefix}log_subscribed AS ls
  1260. INNER JOIN {db_prefix}subscriptions AS s ON (s.id_subscribe = ls.id_subscribe)
  1261. WHERE ls.id_member IN ({array_int:user_list})
  1262. AND ls.end_time > {int:current_time}',
  1263. array(
  1264. 'user_list' => $users,
  1265. 'current_time' => time(),
  1266. )
  1267. );
  1268. while ($row = $smcFunc['db_fetch_assoc']($request))
  1269. {
  1270. // Specific primary group?
  1271. if ($row['id_group'] != 0)
  1272. {
  1273. // If this is changing - add the old one to the additional groups so it's not lost.
  1274. if ($row['id_group'] != $groups[$row['id_member']]['primary'])
  1275. $groups[$row['id_member']]['additional'][] = $groups[$row['id_member']]['primary'];
  1276. $groups[$row['id_member']]['primary'] = $row['id_group'];
  1277. }
  1278. // Additional groups.
  1279. if (!empty($row['add_groups']))
  1280. $groups[$row['id_member']]['additional'] = array_merge($groups[$row['id_member']]['additional'], explode(',', $row['add_groups']));
  1281. }
  1282. $smcFunc['db_free_result']($request);
  1283. // Update all the members.
  1284. foreach ($groups as $id => $group)
  1285. {
  1286. $group['additional'] = array_unique($group['additional']);
  1287. foreach ($group['additional'] as $key => $value)
  1288. if (empty($value))
  1289. unset($group['additional'][$key]);
  1290. $addgroups = implode(',', $group['additional']);
  1291. $smcFunc['db_query']('', '
  1292. UPDATE {db_prefix}members
  1293. SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
  1294. WHERE id_member = {int:current_member}
  1295. LIMIT 1',
  1296. array(
  1297. 'primary_group' => $group['primary'],
  1298. 'current_member' => $id,
  1299. 'additional_groups' => $addgroups,
  1300. )
  1301. );
  1302. }
  1303. }
  1304. /**
  1305. * Add or extend a subscription of a user.
  1306. *
  1307. * @param int $id_subscribe
  1308. * @param int $id_member
  1309. * @param string $renewal = 0, options 'D', 'W', 'M', 'Y'
  1310. * @param int $forceStartTime = 0
  1311. * @param int $forceEndTime = 0
  1312. */
  1313. function addSubscription($id_subscribe, $id_member, $renewal = 0, $forceStartTime = 0, $forceEndTime = 0)
  1314. {
  1315. global $context, $smcFunc;
  1316. // Take the easy way out...
  1317. loadSubscriptions();
  1318. // Exists, yes?
  1319. if (!isset($context['subscriptions'][$id_subscribe]))
  1320. return;
  1321. $curSub = $context['subscriptions'][$id_subscribe];
  1322. // Grab the duration.
  1323. $duration = $curSub['num_length'];
  1324. // If this is a renewal change the duration to be correct.
  1325. if (!empty($renewal))
  1326. {
  1327. switch ($renewal)
  1328. {
  1329. case 'D':
  1330. $duration = 86400;
  1331. break;
  1332. case 'W':
  1333. $duration = 604800;
  1334. break;
  1335. case 'M':
  1336. $duration = 2629743;
  1337. break;
  1338. case 'Y':
  1339. $duration = 31556926;
  1340. break;
  1341. default:
  1342. break;
  1343. }
  1344. }
  1345. // Firstly, see whether it exists, and is active. If so then this is meerly an extension.
  1346. $request = $smcFunc['db_query']('', '
  1347. SELECT id_sublog, end_time, start_time
  1348. FROM {db_prefix}log_subscribed
  1349. WHERE id_subscribe = {int:current_subscription}
  1350. AND id_member = {int:current_member}
  1351. AND status = {int:is_active}',
  1352. array(
  1353. 'current_subscription' => $id_subscribe,
  1354. 'current_member' => $id_member,
  1355. 'is_active' => 1,
  1356. )
  1357. );
  1358. if ($smcFunc['db_num_rows']($request) != 0)
  1359. {
  1360. list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
  1361. // If this has already expired but is active, extension means the period from now.
  1362. if ($endtime < time())
  1363. $endtime = time();
  1364. if ($starttime == 0)
  1365. $starttime = time();
  1366. // Work out the new expiry date.
  1367. $endtime += $duration;
  1368. if ($forceEndTime != 0)
  1369. $endtime = $forceEndTime;
  1370. // As everything else should be good, just update!
  1371. $smcFunc['db_query']('', '
  1372. UPDATE {db_prefix}log_subscribed
  1373. SET end_time = {int:end_time}, start_time = {int:start_time}, reminder_sent = {int:no_reminder_sent}
  1374. WHERE id_sublog = {int:current_subscription_item}',
  1375. array(
  1376. 'end_time' => $endtime,
  1377. 'start_time' => $starttime,
  1378. 'current_subscription_item' => $id_sublog,
  1379. 'no_reminder_sent' => 0,
  1380. )
  1381. );
  1382. return;
  1383. }
  1384. $smcFunc['db_free_result']($request);
  1385. // If we're here, that means we don't have an active subscription - that means we need to do some work!
  1386. $request = $smcFunc['db_query']('', '
  1387. SELECT m.id_group, m.additional_groups
  1388. FROM {db_prefix}members AS m
  1389. WHERE m.id_member = {int:current_member}',
  1390. array(
  1391. 'current_member' => $id_member,
  1392. )
  1393. );
  1394. // Just in case the member doesn't exist.
  1395. if ($smcFunc['db_num_rows']($request) == 0)
  1396. return;
  1397. list ($old_id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
  1398. $smcFunc['db_free_result']($request);
  1399. // Prepare additional groups.
  1400. $newAddGroups = explode(',', $curSub['add_groups']);
  1401. $curAddGroups = explode(',', $additional_groups);
  1402. $newAddGroups = array_merge($newAddGroups, $curAddGroups);
  1403. // Simple, simple, simple - hopefully... id_group first.
  1404. if ($curSub['prim_group'] != 0)
  1405. {
  1406. $id_group = $curSub['prim_group'];
  1407. // Ensure their old privileges are maintained.
  1408. if ($old_id_group != 0)
  1409. $newAddGroups[] = $old_id_group;
  1410. }
  1411. else
  1412. $id_group = $old_id_group;
  1413. // Yep, make sure it's unique, and no empties.
  1414. foreach ($newAddGroups as $k => $v)
  1415. if (empty($v))
  1416. unset($newAddGroups[$k]);
  1417. $newAddGroups = array_unique($newAddGroups);
  1418. $newAddGroups = implode(',', $newAddGroups);
  1419. // Store the new settings.
  1420. $smcFunc['db_query']('', '
  1421. UPDATE {db_prefix}members
  1422. SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
  1423. WHERE id_member = {int:current_member}',
  1424. array(
  1425. 'primary_group' => $id_group,
  1426. 'current_member' => $id_member,
  1427. 'additional_groups' => $newAddGroups,
  1428. )
  1429. );
  1430. // Now log the subscription - maybe we have a dorment subscription we can restore?
  1431. $request = $smcFunc['db_query']('', '
  1432. SELECT id_sublog, end_time, start_time
  1433. FROM {db_prefix}log_subscribed
  1434. WHERE id_subscribe = {int:current_subscription}
  1435. AND id_member = {int:current_member}',
  1436. array(
  1437. 'current_subscription' => $id_subscribe,
  1438. 'current_member' => $id_member,
  1439. )
  1440. );
  1441. /**
  1442. * @todo Don't really need to do this twice...
  1443. */
  1444. if ($smcFunc['db_num_rows']($request) != 0)
  1445. {
  1446. list ($id_sublog, $endtime, $starttime) = $smcFunc['db_fetch_row']($request);
  1447. // If this has already expired but is active, extension means the period from now.
  1448. if ($endtime < time())
  1449. $endtime = time();
  1450. if ($starttime == 0)
  1451. $starttime = time();
  1452. // Work out the new expiry date.
  1453. $endtime += $duration;
  1454. if ($forceEndTime != 0)
  1455. $endtime = $forceEndTime;
  1456. // As everything else should be good, just update!
  1457. $smcFunc['db_query']('', '
  1458. UPDATE {db_prefix}log_subscribed
  1459. 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}
  1460. WHERE id_sublog = {int:current_subscription_item}',
  1461. array(
  1462. 'start_time' => $starttime,
  1463. 'end_time' => $endtime,
  1464. 'old_id_group' => $old_id_group,
  1465. 'is_active' => 1,
  1466. 'no_reminder_sent' => 0,
  1467. 'current_subscription_item' => $id_sublog,
  1468. )
  1469. );
  1470. return;
  1471. }
  1472. $smcFunc['db_free_result']($request);
  1473. // Otherwise a very simple insert.
  1474. $endtime = time() + $duration;
  1475. if ($forceEndTime != 0)
  1476. $endtime = $forceEndTime;
  1477. if ($forceStartTime == 0)
  1478. $starttime = time();
  1479. else
  1480. $starttime = $forceStartTime;
  1481. $smcFunc['db_insert']('',
  1482. '{db_prefix}log_subscribed',
  1483. array(
  1484. 'id_subscribe' => 'int', 'id_member' => 'int', 'old_id_group' => 'int', 'start_time' => 'int',
  1485. 'end_time' => 'int', 'status' => 'int', 'pending_details' => 'string',
  1486. ),
  1487. array(
  1488. $id_subscribe, $id_member, $old_id_group, $starttime,
  1489. $endtime, 1, '',
  1490. ),
  1491. array('id_sublog')
  1492. );
  1493. }
  1494. /**
  1495. * Removes a subscription from a user, as in removes the groups.
  1496. *
  1497. * @param $id_subscribe
  1498. * @param $id_member
  1499. * @param $delete
  1500. */
  1501. function removeSubscription($id_subscribe, $id_member, $delete = false)
  1502. {
  1503. global $context, $smcFunc;
  1504. loadSubscriptions();
  1505. // Load the user core bits.
  1506. $request = $smcFunc['db_query']('', '
  1507. SELECT m.id_group, m.additional_groups
  1508. FROM {db_prefix}members AS m
  1509. WHERE m.id_member = {int:current_member}',
  1510. array(
  1511. 'current_member' => $id_member,
  1512. )
  1513. );
  1514. // Just in case of errors.
  1515. if ($smcFunc['db_num_rows']($request) == 0)
  1516. {
  1517. $smcFunc['db_query']('', '
  1518. DELETE FROM {db_prefix}log_subscribed
  1519. WHERE id_member = {int:current_member}',
  1520. array(
  1521. 'current_member' => $id_member,
  1522. )
  1523. );
  1524. return;
  1525. }
  1526. list ($id_group, $additional_groups) = $smcFunc['db_fetch_row']($request);
  1527. $smcFunc['db_free_result']($request);
  1528. // Get all of the subscriptions for this user that are active - it will be necessary!
  1529. $request = $smcFunc['db_query']('', '
  1530. SELECT id_subscribe, old_id_group
  1531. FROM {db_prefix}log_subscribed
  1532. WHERE id_member = {int:current_member}
  1533. AND status = {int:is_active}',
  1534. array(
  1535. 'current_member' => $id_member,
  1536. 'is_active' => 1,
  1537. )
  1538. );
  1539. // These variables will be handy, honest ;)
  1540. $removals = array();
  1541. $allowed = array();
  1542. $old_id_group = 0;
  1543. $new_id_group = -1;
  1544. while ($row = $smcFunc['db_fetch_assoc']($request))
  1545. {
  1546. if (!isset($context['subscriptions'][$row['id_subscribe']]))
  1547. continue;
  1548. // The one we're removing?
  1549. if ($row['id_subscribe'] == $id_subscribe)
  1550. {
  1551. $removals = explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']);
  1552. if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
  1553. $removals[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1554. $old_id_group = $row['old_id_group'];
  1555. }
  1556. // Otherwise things we allow.
  1557. else
  1558. {
  1559. $allowed = array_merge($allowed, explode(',', $context['subscriptions'][$row['id_subscribe']]['add_groups']));
  1560. if ($context['subscriptions'][$row['id_subscribe']]['prim_group'] != 0)
  1561. {
  1562. $allowed[] = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1563. $new_id_group = $context['subscriptions'][$row['id_subscribe']]['prim_group'];
  1564. }
  1565. }
  1566. }
  1567. $smcFunc['db_free_result']($request);
  1568. // Now, for everything we are removing check they defintely are not allowed it.
  1569. $existingGroups = explode(',', $additional_groups);
  1570. foreach ($existingGroups as $key => $group)
  1571. if (empty($group) || (in_array($group, $removals) && !in_array($group, $allowed)))
  1572. unset($existingGroups[$key]);
  1573. // Finally, do something with the current primary group.
  1574. if (in_array($id_group, $removals))
  1575. {
  1576. // If this primary group is actually allowed keep it.
  1577. if (in_array($id_group, $allowed))
  1578. $existingGroups[] = $id_group;
  1579. // Either way, change the id_group back.
  1580. if ($new_id_group < 1)
  1581. {
  1582. // If we revert to the old id-group we need to ensure it wasn't from a subscription.
  1583. foreach ($context['subscriptions'] as $id => $group)
  1584. // It was? Make them a regular member then!
  1585. if ($group['prim_group'] == $old_id_group)
  1586. $old_id_group = 0;
  1587. $id_group = $old_id_group;
  1588. }
  1589. else
  1590. $id_group = $new_id_group;
  1591. }
  1592. // Crazy stuff, we seem to have our groups fixed, just make them unique
  1593. $existingGroups = array_unique($existingGroups);
  1594. $existingGroups = implode(',', $existingGroups);
  1595. // Update the member
  1596. $smcFunc['db_query']('', '
  1597. UPDATE {db_prefix}members
  1598. SET id_group = {int:primary_group}, additional_groups = {string:existing_groups}
  1599. WHERE id_member = {int:current_member}',
  1600. array(
  1601. 'primary_group' => $id_group,
  1602. 'current_member' => $id_member,
  1603. 'existing_groups' => $existingGroups,
  1604. )
  1605. );
  1606. // Disable the subscription.
  1607. if (!$delete)
  1608. $smcFunc['db_query']('', '
  1609. UPDATE {db_prefix}log_subscribed
  1610. SET status = {int:not_active}
  1611. WHERE id_member = {int:current_member}
  1612. AND id_subscribe = {int:current_subscription}',
  1613. array(
  1614. 'not_active' => 0,
  1615. 'current_member' => $id_member,
  1616. 'current_subscription' => $id_subscribe,
  1617. )
  1618. );
  1619. // Otherwise delete it!
  1620. else
  1621. $smcFunc['db_query']('', '
  1622. DELETE FROM {db_prefix}log_subscribed
  1623. WHERE id_member = {int:current_member}
  1624. AND id_subscribe = {int:current_subscription}',
  1625. array(
  1626. 'current_member' => $id_member,
  1627. 'current_subscription' => $id_subscribe,
  1628. )
  1629. );
  1630. }
  1631. /**
  1632. * This just kind of caches all the subscription data.
  1633. */
  1634. function loadSubscriptions()
  1635. {
  1636. global $context, $txt, $modSettings, $smcFunc;
  1637. if (!empty($context['subscriptions']))
  1638. return;
  1639. // Make sure this is loaded, just in case.
  1640. loadLanguage('ManagePaid');
  1641. $request = $smcFunc['db_query']('', '
  1642. SELECT id_subscribe, name, description, cost, length, id_group, add_groups, active, repeatable
  1643. FROM {db_prefix}subscriptions',
  1644. array(
  1645. )
  1646. );
  1647. $context['subscriptions'] = array();
  1648. while ($row = $smcFunc['db_fetch_assoc']($request))
  1649. {
  1650. // Pick a cost.
  1651. $costs = @unserialize($row['cost']);
  1652. if ($row['length'] != 'F' && !empty($modSettings['paid_currency_symbol']) && !empty($costs['fixed']))
  1653. $cost = sprintf($modSettings['paid_currency_symbol'], $costs['fixed']);
  1654. else
  1655. $cost = '???';
  1656. // Do the span.
  1657. preg_match('~(\d*)(\w)~', $row['length'], $match);
  1658. if (isset($match[2]))
  1659. {
  1660. $num_length = $match[1];
  1661. $length = $match[1] . ' ';
  1662. switch ($match[2])
  1663. {
  1664. case 'D':
  1665. $length .= $txt['paid_mod_span_days'];
  1666. $num_length *= 86400;
  1667. break;
  1668. case 'W':
  1669. $length .= $txt['paid_mod_span_weeks'];
  1670. $num_length *= 604800;
  1671. break;
  1672. case 'M':
  1673. $length .= $txt['paid_mod_span_months'];
  1674. $num_length *= 2629743;
  1675. break;
  1676. case 'Y':
  1677. $length .= $txt['paid_mod_span_years'];
  1678. $num_length *= 31556926;
  1679. break;
  1680. }
  1681. }
  1682. else
  1683. $length = '??';
  1684. $context['subscriptions'][$row['id_subscribe']] = array(
  1685. 'id' => $row['id_subscribe'],
  1686. 'name' => $row['name'],
  1687. 'desc' => $row['description'],
  1688. 'cost' => $cost,
  1689. 'real_cost' => $row['cost'],
  1690. 'length' => $length,
  1691. 'num_length' => $num_length,
  1692. 'real_length' => $row['length'],
  1693. 'pending' => 0,
  1694. 'finished' => 0,
  1695. 'total' => 0,
  1696. 'active' => $row['active'],
  1697. 'prim_group' => $row['id_group'],
  1698. 'add_groups' => $row['add_groups'],
  1699. 'flexible' => $row['length'] == 'F' ? true : false,
  1700. 'repeatable' => $row['repeatable'],
  1701. );
  1702. }
  1703. $smcFunc['db_free_result']($request);
  1704. // Do the counts.
  1705. $request = $smcFunc['db_query']('', '
  1706. SELECT COUNT(id_sublog) AS member_count, id_subscribe, status
  1707. FROM {db_prefix}log_subscribed
  1708. GROUP BY id_subscribe, status',
  1709. array(
  1710. )
  1711. );
  1712. while ($row = $smcFunc['db_fetch_assoc']($request))
  1713. {
  1714. $ind = $row['status'] == 0 ? 'finished' : 'total';
  1715. if (isset($context['subscriptions'][$row['id_subscribe']]))
  1716. $context['subscriptions'][$row['id_subscribe']][$ind] = $row['member_count'];
  1717. }
  1718. $smcFunc['db_free_result']($request);
  1719. // How many payments are we waiting on?
  1720. $request = $smcFunc['db_query']('', '
  1721. SELECT SUM(payments_pending) AS total_pending, id_subscribe
  1722. FROM {db_prefix}log_subscribed
  1723. GROUP BY id_subscribe',
  1724. array(
  1725. )
  1726. );
  1727. while ($row = $smcFunc['db_fetch_assoc']($request))
  1728. {
  1729. if (isset($context['subscriptions'][$row['id_subscribe']]))
  1730. $context['subscriptions'][$row['id_subscribe']]['pending'] = $row['total_pending'];
  1731. }
  1732. $smcFunc['db_free_result']($request);
  1733. }
  1734. /**
  1735. * Load all the payment gateways.
  1736. * Checks the Sources directory for any files fitting the format of a payment gateway,
  1737. * loads each file to check it's valid, includes each file and returns the
  1738. * function name and whether it should work with this version of SMF.
  1739. *
  1740. * @return array
  1741. */
  1742. function loadPaymentGateways()
  1743. {
  1744. global $sourcedir;
  1745. $gateways = array();
  1746. if ($dh = opendir($sourcedir))
  1747. {
  1748. while (($file = readdir($dh)) !== false)
  1749. {
  1750. if (is_file($sourcedir .'/'. $file) && preg_match('~^Subscriptions-([A-Za-z\d]+)\.php$~', $file, $matches))
  1751. {
  1752. // Check this is definitely a valid gateway!
  1753. $fp = fopen($sourcedir . '/' . $file, 'rb');
  1754. $header = fread($fp, 4096);
  1755. fclose($fp);
  1756. if (strpos($header, '// SMF Payment Gateway: ' . strtolower($matches[1])) !== false)
  1757. {
  1758. require_once($sourcedir . '/' . $file);
  1759. $gateways[] = array(
  1760. 'filename' => $file,
  1761. 'code' => strtolower($matches[1]),
  1762. // Don't need anything snazier than this yet.
  1763. 'valid_version' => class_exists(strtolower($matches[1]) . '_payment') && class_exists(strtolower($matches[1]) . '_display'),
  1764. 'payment_class' => strtolower($matches[1]) . '_payment',
  1765. 'display_class' => strtolower($matches[1]) . '_display',
  1766. );
  1767. }
  1768. }
  1769. }
  1770. }
  1771. closedir($dh);
  1772. return $gateways;
  1773. }
  1774. ?>