ManagePaid.php 57 KB

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