ManageNews.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. <?php
  2. /**
  3. * This file manages... the news. :P
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * The news dispatcher; doesn't do anything, just delegates.
  18. * This is the entrance point for all News and Newsletter screens.
  19. * Called by ?action=admin;area=news.
  20. * It does the permission checks, and calls the appropriate function
  21. * based on the requested sub-action.
  22. */
  23. function ManageNews()
  24. {
  25. global $context, $txt, $scripturl;
  26. // First, let's do a quick permissions check for the best error message possible.
  27. isAllowedTo(array('edit_news', 'send_mail', 'admin_forum'));
  28. loadTemplate('ManageNews');
  29. // Format: 'sub-action' => array('function', 'permission')
  30. $subActions = array(
  31. 'editnews' => array('EditNews', 'edit_news'),
  32. 'mailingmembers' => array('SelectMailingMembers', 'send_mail'),
  33. 'mailingcompose' => array('ComposeMailing', 'send_mail'),
  34. 'mailingsend' => array('SendMailing', 'send_mail'),
  35. 'settings' => array('ModifyNewsSettings', 'admin_forum'),
  36. );
  37. call_integration_hook('integrate_manage_news', array(&$subActions));
  38. // Default to sub action 'main' or 'settings' depending on permissions.
  39. $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : (allowedTo('edit_news') ? 'editnews' : (allowedTo('send_mail') ? 'mailingmembers' : 'settings'));
  40. // Have you got the proper permissions?
  41. isAllowedTo($subActions[$_REQUEST['sa']][1]);
  42. // Create the tabs for the template.
  43. $context[$context['admin_menu_name']]['tab_data'] = array(
  44. 'title' => $txt['news_title'],
  45. 'help' => 'edit_news',
  46. 'description' => $txt['admin_news_desc'],
  47. 'tabs' => array(
  48. 'editnews' => array(
  49. ),
  50. 'mailingmembers' => array(
  51. 'description' => $txt['news_mailing_desc'],
  52. ),
  53. 'settings' => array(
  54. 'description' => $txt['news_settings_desc'],
  55. ),
  56. ),
  57. );
  58. // Force the right area...
  59. if (substr($_REQUEST['sa'], 0, 7) == 'mailing')
  60. $context[$context['admin_menu_name']]['current_subsection'] = 'mailingmembers';
  61. $subActions[$_REQUEST['sa']][0]();
  62. }
  63. /**
  64. * Let the administrator(s) edit the news items for the forum.
  65. * It writes an entry into the moderation log.
  66. * This function uses the edit_news administration area.
  67. * Called by ?action=admin;area=news.
  68. * Requires the edit_news permission.
  69. * Can be accessed with ?action=admin;sa=editnews.
  70. *
  71. * @uses ManageNews template, edit_news sub template.
  72. */
  73. function EditNews()
  74. {
  75. global $txt, $modSettings, $context, $sourcedir, $user_info, $scripturl;
  76. global $smcFunc;
  77. require_once($sourcedir . '/Subs-Post.php');
  78. // The 'remove selected' button was pressed.
  79. if (!empty($_POST['delete_selection']) && !empty($_POST['remove']))
  80. {
  81. checkSession();
  82. // Store the news temporarily in this array.
  83. $temp_news = explode("\n", $modSettings['news']);
  84. // Remove the items that were selected.
  85. foreach ($temp_news as $i => $news)
  86. if (in_array($i, $_POST['remove']))
  87. unset($temp_news[$i]);
  88. // Update the database.
  89. updateSettings(array('news' => implode("\n", $temp_news)));
  90. logAction('news');
  91. }
  92. // The 'Save' button was pressed.
  93. elseif (!empty($_POST['save_items']))
  94. {
  95. checkSession();
  96. foreach ($_POST['news'] as $i => $news)
  97. {
  98. if (trim($news) == '')
  99. unset($_POST['news'][$i]);
  100. else
  101. {
  102. $_POST['news'][$i] = $smcFunc['htmlspecialchars']($_POST['news'][$i], ENT_QUOTES);
  103. preparsecode($_POST['news'][$i]);
  104. }
  105. }
  106. // Send the new news to the database.
  107. updateSettings(array('news' => implode("\n", $_POST['news'])));
  108. // Log this into the moderation log.
  109. logAction('news');
  110. }
  111. // We're going to want this for making our list.
  112. require_once($sourcedir . '/Subs-List.php');
  113. $context['page_title'] = $txt['admin_edit_news'];
  114. // Use the standard templates for showing this.
  115. $listOptions = array(
  116. 'id' => 'news_lists',
  117. // 'title' => $txt['admin_edit_news'],
  118. 'get_items' => array(
  119. 'function' => 'list_getNews',
  120. ),
  121. 'columns' => array(
  122. 'news' => array(
  123. 'header' => array(
  124. 'value' => $txt['admin_edit_news'],
  125. ),
  126. 'data' => array(
  127. 'function' => create_function('$news', '
  128. if (is_numeric($news[\'id\']))
  129. return \'<textarea rows="3" cols="65" name="news[]" style="\' . (isBrowser(\'is_ie8\') ? \'width: 635px; max-width: 85%; min-width: 85%\' : \'width: 85%\') . \';">\' . $news[\'unparsed\'] . \'</textarea>
  130. <div style="float:right" id="preview_\' . $news[\'id\'] . \'"></div>\';
  131. else
  132. return $news[\'unparsed\'];
  133. '),
  134. 'style' => 'width: 50%;',
  135. ),
  136. ),
  137. 'preview' => array(
  138. 'header' => array(
  139. 'value' => $txt['preview'],
  140. ),
  141. 'data' => array(
  142. 'function' => create_function('$news', '
  143. return \'<div id="box_preview_\' . $news[\'id\'] . \'" style="overflow: auto; width: 100%; height: 10ex;">\' . $news[\'parsed\'] . \'</div>\';
  144. '),
  145. 'style' => 'width: 45%;',
  146. ),
  147. ),
  148. 'check' => array(
  149. 'header' => array(
  150. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  151. ),
  152. 'data' => array(
  153. 'function' => create_function('$news', '
  154. if (is_numeric($news[\'id\']))
  155. return \'<input type="checkbox" name="remove[]" value="\' . $news[\'id\'] . \'" class="input_check" />\';
  156. else
  157. return \'\';
  158. '),
  159. 'style' => 'text-align: center',
  160. ),
  161. ),
  162. ),
  163. 'form' => array(
  164. 'href' => $scripturl . '?action=admin;area=news;sa=editnews',
  165. 'hidden_fields' => array(
  166. $context['session_var'] => $context['session_id'],
  167. ),
  168. ),
  169. 'additional_rows' => array(
  170. array(
  171. 'position' => 'bottom_of_list',
  172. 'value' => '
  173. <span id="moreNewsItems_link" style="display: none;">[<a href="javascript:void(0);" onclick="addNewsItem(); return false;">' . $txt['editnews_clickadd'] . '</a>]</span>
  174. <script type="text/javascript"><!-- // --><![CDATA[
  175. document.getElementById(\'list_news_lists_last\').style.display = "none";
  176. document.getElementById("moreNewsItems_link").style.display = "";
  177. $(document).ready(function() {
  178. $("div[id ^= \'preview_\']").each(function () {
  179. $(this).css({cursor: \'hand\', cursor: \'pointer\', });
  180. $(this).text(\'' . $txt['preview'] . '\').click(function () {
  181. // @todo ajax...
  182. });
  183. });
  184. });
  185. function addNewsItem()
  186. {
  187. document.getElementById("list_news_lists_last").style.display = "";
  188. setOuterHTML(document.getElementById("moreNewsItems"), \'<div style="margin-bottom: 2ex;"><textarea rows="3" cols="65" name="news[]" style="' . (isBrowser('is_ie8') ? 'width: 635px; max-width: 85%; min-width: 85%' : 'width: 85%') . ';"><\' + \'/textarea><\' + \'/div><div id="moreNewsItems"><\' + \'/div>\');
  189. }
  190. // ]]></script>
  191. <input type="submit" name="save_items" value="' . $txt['save'] . '" class="button_submit" /> <input type="submit" name="delete_selection" value="' . $txt['editnews_remove_selected'] . '" onclick="return confirm(\'' . $txt['editnews_remove_confirm'] . '\');" class="button_submit" />',
  192. 'align' => 'right',
  193. ),
  194. ),
  195. );
  196. // Create the request list.
  197. createList($listOptions);
  198. $context['sub_template'] = 'show_list';
  199. $context['default_list'] = 'news_lists';
  200. }
  201. function list_getNews()
  202. {
  203. global $modSettings;
  204. $admin_current_news = array();
  205. // Ready the current news.
  206. foreach (explode("\n", $modSettings['news']) as $id => $line)
  207. $admin_current_news[$id] = array(
  208. 'id' => $id,
  209. 'unparsed' => un_preparsecode($line),
  210. 'parsed' => preg_replace('~<([/]?)form[^>]*?[>]*>~i', '<em class="smalltext">&lt;$1form&gt;</em>', parse_bbc($line)),
  211. );
  212. $admin_current_news['last'] = array(
  213. 'id' => 'last',
  214. 'unparsed' => '<div id="moreNewsItems"></div>
  215. <noscript><textarea rows="3" cols="65" name="news[]" style="' . (isBrowser('is_ie8') ? 'width: 635px; max-width: 85%; min-width: 85%' : 'width: 85%') . ';"></textarea></noscript>',
  216. 'parsed' => '<div id="moreNewsItems_preview"></div>',
  217. );
  218. return $admin_current_news;
  219. // $context['sub_template'] = 'edit_news';
  220. }
  221. /**
  222. * This function allows a user to select the membergroups to send their
  223. * mailing to.
  224. * Called by ?action=admin;area=news;sa=mailingmembers.
  225. * Requires the send_mail permission.
  226. * Form is submitted to ?action=admin;area=news;mailingcompose.
  227. *
  228. * @uses the ManageNews template and email_members sub template.
  229. */
  230. function SelectMailingMembers()
  231. {
  232. global $txt, $context, $modSettings, $smcFunc;
  233. $context['page_title'] = $txt['admin_newsletters'];
  234. $context['sub_template'] = 'email_members';
  235. $context['groups'] = array();
  236. $postGroups = array();
  237. $normalGroups = array();
  238. // If we have post groups disabled then we need to give a "ungrouped members" option.
  239. if (empty($modSettings['permission_enable_postgroups']))
  240. {
  241. $context['groups'][0] = array(
  242. 'id' => 0,
  243. 'name' => $txt['membergroups_members'],
  244. 'member_count' => 0,
  245. );
  246. $normalGroups[0] = 0;
  247. }
  248. // Get all the extra groups as well as Administrator and Global Moderator.
  249. $request = $smcFunc['db_query']('', '
  250. SELECT mg.id_group, mg.group_name, mg.min_posts
  251. FROM {db_prefix}membergroups AS mg' . (empty($modSettings['permission_enable_postgroups']) ? '
  252. WHERE mg.min_posts = {int:min_posts}' : '') . '
  253. GROUP BY mg.id_group, mg.min_posts, mg.group_name
  254. ORDER BY mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
  255. array(
  256. 'min_posts' => -1,
  257. 'newbie_group' => 4,
  258. )
  259. );
  260. while ($row = $smcFunc['db_fetch_assoc']($request))
  261. {
  262. $context['groups'][$row['id_group']] = array(
  263. 'id' => $row['id_group'],
  264. 'name' => $row['group_name'],
  265. 'member_count' => 0,
  266. );
  267. if ($row['min_posts'] == -1)
  268. $normalGroups[$row['id_group']] = $row['id_group'];
  269. else
  270. $postGroups[$row['id_group']] = $row['id_group'];
  271. }
  272. $smcFunc['db_free_result']($request);
  273. // If we have post groups, let's count the number of members...
  274. if (!empty($postGroups))
  275. {
  276. $query = $smcFunc['db_query']('', '
  277. SELECT mem.id_post_group AS id_group, COUNT(*) AS member_count
  278. FROM {db_prefix}members AS mem
  279. WHERE mem.id_post_group IN ({array_int:post_group_list})
  280. GROUP BY mem.id_post_group',
  281. array(
  282. 'post_group_list' => $postGroups,
  283. )
  284. );
  285. while ($row = $smcFunc['db_fetch_assoc']($query))
  286. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  287. $smcFunc['db_free_result']($query);
  288. }
  289. if (!empty($normalGroups))
  290. {
  291. // Find people who are members of this group...
  292. $query = $smcFunc['db_query']('', '
  293. SELECT id_group, COUNT(*) AS member_count
  294. FROM {db_prefix}members
  295. WHERE id_group IN ({array_int:normal_group_list})
  296. GROUP BY id_group',
  297. array(
  298. 'normal_group_list' => $normalGroups,
  299. )
  300. );
  301. while ($row = $smcFunc['db_fetch_assoc']($query))
  302. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  303. $smcFunc['db_free_result']($query);
  304. // Also do those who have it as an additional membergroup - this ones more yucky...
  305. $query = $smcFunc['db_query']('', '
  306. SELECT mg.id_group, COUNT(*) AS member_count
  307. FROM {db_prefix}membergroups AS mg
  308. INNER JOIN {db_prefix}members AS mem ON (mem.additional_groups != {string:blank_string}
  309. AND mem.id_group != mg.id_group
  310. AND FIND_IN_SET(mg.id_group, mem.additional_groups) != 0)
  311. WHERE mg.id_group IN ({array_int:normal_group_list})
  312. GROUP BY mg.id_group',
  313. array(
  314. 'normal_group_list' => $normalGroups,
  315. 'blank_string' => '',
  316. )
  317. );
  318. while ($row = $smcFunc['db_fetch_assoc']($query))
  319. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  320. $smcFunc['db_free_result']($query);
  321. }
  322. // Any moderators?
  323. $request = $smcFunc['db_query']('', '
  324. SELECT COUNT(DISTINCT id_member) AS num_distinct_mods
  325. FROM {db_prefix}moderators
  326. LIMIT 1',
  327. array(
  328. )
  329. );
  330. list ($context['groups'][3]['member_count']) = $smcFunc['db_fetch_row']($request);
  331. $smcFunc['db_free_result']($request);
  332. $context['can_send_pm'] = allowedTo('pm_send');
  333. }
  334. /**
  335. * Shows a form to edit a forum mailing and its recipients.
  336. * Called by ?action=admin;area=news;sa=mailingcompose.
  337. * Requires the send_mail permission.
  338. * Form is submitted to ?action=admin;area=news;sa=mailingsend.
  339. *
  340. * @uses ManageNews template, email_members_compose sub-template.
  341. */
  342. function ComposeMailing()
  343. {
  344. global $txt, $sourcedir, $context, $smcFunc;
  345. // Start by finding any members!
  346. $toClean = array();
  347. if (!empty($_POST['members']))
  348. $toClean[] = 'members';
  349. if (!empty($_POST['exclude_members']))
  350. $toClean[] = 'exclude_members';
  351. if (!empty($toClean))
  352. {
  353. require_once($sourcedir . '/Subs-Auth.php');
  354. foreach ($toClean as $type)
  355. {
  356. // Remove the quotes.
  357. $_POST[$type] = strtr($_POST[$type], array('\\"' => '"'));
  358. preg_match_all('~"([^"]+)"~', $_POST[$type], $matches);
  359. $_POST[$type] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST[$type]))));
  360. foreach ($_POST[$type] as $index => $member)
  361. if (strlen(trim($member)) > 0)
  362. $_POST[$type][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($member)));
  363. else
  364. unset($_POST[$type][$index]);
  365. // Find the members
  366. $_POST[$type] = implode(',', array_keys(findMembers($_POST[$type])));
  367. }
  368. }
  369. if (isset($_POST['member_list']) && is_array($_POST['member_list']))
  370. {
  371. $members = array();
  372. foreach ($_POST['member_list'] as $member_id)
  373. $members[] = (int) $member_id;
  374. $_POST['members'] = implode(',', $members);
  375. }
  376. if (isset($_POST['exclude_member_list']) && is_array($_POST['exclude_member_list']))
  377. {
  378. $members = array();
  379. foreach ($_POST['exclude_member_list'] as $member_id)
  380. $members[] = (int) $member_id;
  381. $_POST['exclude_members'] = implode(',', $members);
  382. }
  383. // Clean the other vars.
  384. SendMailing(true);
  385. // We need a couple strings from the email template file
  386. loadLanguage('EmailTemplates');
  387. // Get a list of all full banned users. Use their Username and email to find them. Only get the ones that can't login to turn off notification.
  388. $request = $smcFunc['db_query']('', '
  389. SELECT DISTINCT mem.id_member
  390. FROM {db_prefix}ban_groups AS bg
  391. INNER JOIN {db_prefix}ban_items AS bi ON (bg.id_ban_group = bi.id_ban_group)
  392. INNER JOIN {db_prefix}members AS mem ON (bi.id_member = mem.id_member)
  393. WHERE (bg.cannot_access = {int:cannot_access} OR bg.cannot_login = {int:cannot_login})
  394. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})',
  395. array(
  396. 'cannot_access' => 1,
  397. 'cannot_login' => 1,
  398. 'current_time' => time(),
  399. )
  400. );
  401. while ($row = $smcFunc['db_fetch_assoc']($request))
  402. $context['recipients']['exclude_members'][] = $row['id_member'];
  403. $smcFunc['db_free_result']($request);
  404. $request = $smcFunc['db_query']('', '
  405. SELECT DISTINCT bi.email_address
  406. FROM {db_prefix}ban_items AS bi
  407. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  408. WHERE (bg.cannot_access = {int:cannot_access} OR bg.cannot_login = {int:cannot_login})
  409. AND (COALESCE(bg.expire_time, 1=1) OR bg.expire_time > {int:current_time})
  410. AND bi.email_address != {string:blank_string}',
  411. array(
  412. 'cannot_access' => 1,
  413. 'cannot_login' => 1,
  414. 'current_time' => time(),
  415. 'blank_string' => '',
  416. )
  417. );
  418. $condition_array = array();
  419. $condition_array_params = array();
  420. $count = 0;
  421. while ($row = $smcFunc['db_fetch_assoc']($request))
  422. {
  423. $condition_array[] = '{string:email_' . $count . '}';
  424. $condition_array_params['email_' . $count++] = $row['email_address'];
  425. }
  426. if (!empty($condition_array))
  427. {
  428. $request = $smcFunc['db_query']('', '
  429. SELECT id_member
  430. FROM {db_prefix}members
  431. WHERE email_address IN(' . implode(', ', $condition_array) .')',
  432. $condition_array_params
  433. );
  434. while ($row = $smcFunc['db_fetch_assoc']($request))
  435. $context['recipients']['exclude_members'][] = $row['id_member'];
  436. }
  437. // Did they select moderators - if so add them as specific members...
  438. if ((!empty($context['recipients']['groups']) && in_array(3, $context['recipients']['groups'])) || (!empty($context['recipients']['exclude_groups']) && in_array(3, $context['recipients']['exclude_groups'])))
  439. {
  440. $request = $smcFunc['db_query']('', '
  441. SELECT DISTINCT mem.id_member AS identifier
  442. FROM {db_prefix}members AS mem
  443. INNER JOIN {db_prefix}moderators AS mods ON (mods.id_member = mem.id_member)
  444. WHERE mem.is_activated = {int:is_activated}',
  445. array(
  446. 'is_activated' => 1,
  447. )
  448. );
  449. while ($row = $smcFunc['db_fetch_assoc']($request))
  450. {
  451. if (in_array(3, $context['recipients']))
  452. $context['recipients']['exclude_members'][] = $row['identifier'];
  453. else
  454. $context['recipients']['members'][] = $row['identifier'];
  455. }
  456. $smcFunc['db_free_result']($request);
  457. }
  458. // For progress bar!
  459. $context['total_emails'] = count($context['recipients']['emails']);
  460. $request = $smcFunc['db_query']('', '
  461. SELECT MAX(id_member)
  462. FROM {db_prefix}members',
  463. array(
  464. )
  465. );
  466. list ($context['max_id_member']) = $smcFunc['db_fetch_row']($request);
  467. $smcFunc['db_free_result']($request);
  468. // Clean up the arrays.
  469. $context['recipients']['members'] = array_unique($context['recipients']['members']);
  470. $context['recipients']['exclude_members'] = array_unique($context['recipients']['exclude_members']);
  471. // Setup the template!
  472. $context['page_title'] = $txt['admin_newsletters'];
  473. $context['sub_template'] = 'email_members_compose';
  474. $context['default_subject'] = htmlspecialchars($context['forum_name'] . ': ' . $txt['subject']);
  475. $context['default_message'] = htmlspecialchars($txt['message'] . "\n\n" . $txt['regards_team'] . "\n\n" . '{$board_url}');
  476. }
  477. /**
  478. * Handles the sending of the forum mailing in batches.
  479. * Called by ?action=admin;area=news;sa=mailingsend
  480. * Requires the send_mail permission.
  481. * Redirects to itself when more batches need to be sent.
  482. * Redirects to ?action=admin after everything has been sent.
  483. *
  484. * @param bool $clean_only = false; if set, it will only clean the variables, put them in context, then return.
  485. * @uses the ManageNews template and email_members_send sub template.
  486. */
  487. function SendMailing($clean_only = false)
  488. {
  489. global $txt, $sourcedir, $context, $smcFunc;
  490. global $scripturl, $modSettings, $user_info;
  491. // How many to send at once? Quantity depends on whether we are queueing or not.
  492. $num_at_once = empty($modSettings['mail_queue']) ? 60 : 1000;
  493. // If by PM's I suggest we half the above number.
  494. if (!empty($_POST['send_pm']))
  495. $num_at_once /= 2;
  496. checkSession();
  497. // Where are we actually to?
  498. $context['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
  499. $context['email_force'] = !empty($_POST['email_force']) ? 1 : 0;
  500. $context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
  501. $context['total_emails'] = !empty($_POST['total_emails']) ? (int) $_POST['total_emails'] : 0;
  502. $context['max_id_member'] = !empty($_POST['max_id_member']) ? (int) $_POST['max_id_member'] : 0;
  503. $context['send_html'] = !empty($_POST['send_html']) ? '1' : '0';
  504. $context['parse_html'] = !empty($_POST['parse_html']) ? '1' : '0';
  505. // Create our main context.
  506. $context['recipients'] = array(
  507. 'groups' => array(),
  508. 'exclude_groups' => array(),
  509. 'members' => array(),
  510. 'exclude_members' => array(),
  511. 'emails' => array(),
  512. );
  513. // Have we any excluded members?
  514. if (!empty($_POST['exclude_members']))
  515. {
  516. $members = explode(',', $_POST['exclude_members']);
  517. foreach ($members as $member)
  518. if ($member >= $context['start'])
  519. $context['recipients']['exclude_members'][] = (int) $member;
  520. }
  521. // What about members we *must* do?
  522. if (!empty($_POST['members']))
  523. {
  524. $members = explode(',', $_POST['members']);
  525. foreach ($members as $member)
  526. if ($member >= $context['start'])
  527. $context['recipients']['members'][] = (int) $member;
  528. }
  529. // Cleaning groups is simple - although deal with both checkbox and commas.
  530. if (!empty($_POST['groups']))
  531. {
  532. if (is_array($_POST['groups']))
  533. {
  534. foreach ($_POST['groups'] as $group => $dummy)
  535. $context['recipients']['groups'][] = (int) $group;
  536. }
  537. else
  538. {
  539. $groups = explode(',', $_POST['groups']);
  540. foreach ($groups as $group)
  541. $context['recipients']['groups'][] = (int) $group;
  542. }
  543. }
  544. // Same for excluded groups
  545. if (!empty($_POST['exclude_groups']))
  546. {
  547. if (is_array($_POST['exclude_groups']))
  548. {
  549. foreach ($_POST['exclude_groups'] as $group => $dummy)
  550. $context['recipients']['exclude_groups'][] = (int) $group;
  551. }
  552. else
  553. {
  554. $groups = explode(',', $_POST['exclude_groups']);
  555. foreach ($groups as $group)
  556. $context['recipients']['exclude_groups'][] = (int) $group;
  557. }
  558. }
  559. // Finally - emails!
  560. if (!empty($_POST['emails']))
  561. {
  562. $addressed = array_unique(explode(';', strtr($_POST['emails'], array("\n" => ';', "\r" => ';', ',' => ';'))));
  563. foreach ($addressed as $curmem)
  564. {
  565. $curmem = trim($curmem);
  566. if ($curmem != '')
  567. $context['recipients']['emails'][$curmem] = $curmem;
  568. }
  569. }
  570. // If we're only cleaning drop out here.
  571. if ($clean_only)
  572. return;
  573. require_once($sourcedir . '/Subs-Post.php');
  574. // Save the message and its subject in $context
  575. $context['subject'] = htmlspecialchars($_POST['subject']);
  576. $context['message'] = htmlspecialchars($_POST['message']);
  577. // Prepare the message for sending it as HTML
  578. if (!$context['send_pm'] && !empty($_POST['send_html']))
  579. {
  580. // Prepare the message for HTML.
  581. if (!empty($_POST['parse_html']))
  582. $_POST['message'] = str_replace(array("\n", ' '), array('<br />' . "\n", '&nbsp; '), $_POST['message']);
  583. // This is here to prevent spam filters from tagging this as spam.
  584. if (preg_match('~\<html~i', $_POST['message']) == 0)
  585. {
  586. if (preg_match('~\<body~i', $_POST['message']) == 0)
  587. $_POST['message'] = '<html><head><title>' . $_POST['subject'] . '</title></head>' . "\n" . '<body>' . $_POST['message'] . '</body></html>';
  588. else
  589. $_POST['message'] = '<html>' . $_POST['message'] . '</html>';
  590. }
  591. }
  592. // Use the default time format.
  593. $user_info['time_format'] = $modSettings['time_format'];
  594. $variables = array(
  595. '{$board_url}',
  596. '{$current_time}',
  597. '{$latest_member.link}',
  598. '{$latest_member.id}',
  599. '{$latest_member.name}'
  600. );
  601. // We might need this in a bit
  602. $cleanLatestMember = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
  603. // Replace in all the standard things.
  604. $_POST['message'] = str_replace($variables,
  605. array(
  606. !empty($_POST['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl,
  607. timeformat(forum_time(), false),
  608. !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $cleanLatestMember . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . ']' . $cleanLatestMember . '[/url]' : $cleanLatestMember),
  609. $modSettings['latestMember'],
  610. $cleanLatestMember
  611. ), $_POST['message']);
  612. $_POST['subject'] = str_replace($variables,
  613. array(
  614. $scripturl,
  615. timeformat(forum_time(), false),
  616. $modSettings['latestRealName'],
  617. $modSettings['latestMember'],
  618. $modSettings['latestRealName']
  619. ), $_POST['subject']);
  620. $from_member = array(
  621. '{$member.email}',
  622. '{$member.link}',
  623. '{$member.id}',
  624. '{$member.name}'
  625. );
  626. // If we still have emails, do them first!
  627. $i = 0;
  628. foreach ($context['recipients']['emails'] as $k => $email)
  629. {
  630. // Done as many as we can?
  631. if ($i >= $num_at_once)
  632. break;
  633. // Don't sent it twice!
  634. unset($context['recipients']['emails'][$k]);
  635. // Dammit - can't PM emails!
  636. if ($context['send_pm'])
  637. continue;
  638. $to_member = array(
  639. $email,
  640. !empty($_POST['send_html']) ? '<a href="mailto:' . $email . '">' . $email . '</a>' : $email,
  641. '??',
  642. $email
  643. );
  644. sendmail($email, str_replace($from_member, $to_member, $_POST['subject']), str_replace($from_member, $to_member, $_POST['message']), null, null, !empty($_POST['send_html']), 5);
  645. // Done another...
  646. $i++;
  647. }
  648. // Got some more to send this batch?
  649. $last_id_member = 0;
  650. if ($i < $num_at_once)
  651. {
  652. // Need to build quite a query!
  653. $sendQuery = '(';
  654. $sendParams = array();
  655. if (!empty($context['recipients']['groups']))
  656. {
  657. // Take the long route...
  658. $queryBuild = array();
  659. foreach ($context['recipients']['groups'] as $group)
  660. {
  661. $sendParams['group_' . $group] = $group;
  662. $queryBuild[] = 'mem.id_group = {int:group_' . $group . '}';
  663. if (!empty($group))
  664. {
  665. $queryBuild[] = 'FIND_IN_SET({int:group_' . $group . '}, mem.additional_groups) != 0';
  666. $queryBuild[] = 'mem.id_post_group = {int:group_' . $group . '}';
  667. }
  668. }
  669. if (!empty($queryBuild))
  670. $sendQuery .= implode(' OR ', $queryBuild);
  671. }
  672. if (!empty($context['recipients']['members']))
  673. {
  674. $sendQuery .= ($sendQuery == '(' ? '' : ' OR ') . 'mem.id_member IN ({array_int:members})';
  675. $sendParams['members'] = $context['recipients']['members'];
  676. }
  677. $sendQuery .= ')';
  678. // If we've not got a query then we must be done!
  679. if ($sendQuery == '()')
  680. redirectexit('action=admin');
  681. // Anything to exclude?
  682. if (!empty($context['recipients']['exclude_groups']) && in_array(0, $context['recipients']['exclude_groups']))
  683. $sendQuery .= ' AND mem.id_group != {int:regular_group}';
  684. if (!empty($context['recipients']['exclude_members']))
  685. {
  686. $sendQuery .= ' AND mem.id_member NOT IN ({array_int:exclude_members})';
  687. $sendParams['exclude_members'] = $context['recipients']['exclude_members'];
  688. }
  689. // Force them to have it?
  690. if (empty($context['email_force']))
  691. $sendQuery .= ' AND mem.notify_announcements = {int:notify_announcements}';
  692. // Get the smelly people - note we respect the id_member range as it gives us a quicker query.
  693. $result = $smcFunc['db_query']('', '
  694. SELECT mem.id_member, mem.email_address, mem.real_name, mem.id_group, mem.additional_groups, mem.id_post_group
  695. FROM {db_prefix}members AS mem
  696. WHERE mem.id_member > {int:min_id_member}
  697. AND mem.id_member < {int:max_id_member}
  698. AND ' . $sendQuery . '
  699. AND mem.is_activated = {int:is_activated}
  700. ORDER BY mem.id_member ASC
  701. LIMIT {int:atonce}',
  702. array_merge($sendParams, array(
  703. 'min_id_member' => $context['start'],
  704. 'max_id_member' => $context['start'] + $num_at_once - $i,
  705. 'atonce' => $num_at_once - $i,
  706. 'regular_group' => 0,
  707. 'notify_announcements' => 1,
  708. 'is_activated' => 1,
  709. ))
  710. );
  711. while ($row = $smcFunc['db_fetch_assoc']($result))
  712. {
  713. $last_id_member = $row['id_member'];
  714. // What groups are we looking at here?
  715. if (empty($row['additional_groups']))
  716. $groups = array($row['id_group'], $row['id_post_group']);
  717. else
  718. $groups = array_merge(
  719. array($row['id_group'], $row['id_post_group']),
  720. explode(',', $row['additional_groups'])
  721. );
  722. // Excluded groups?
  723. if (array_intersect($groups, $context['recipients']['exclude_groups']))
  724. continue;
  725. // We might need this
  726. $cleanMemberName = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($row['real_name']) : $row['real_name'];
  727. // Replace the member-dependant variables
  728. $message = str_replace($from_member,
  729. array(
  730. $row['email_address'],
  731. !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $cleanMemberName . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $row['id_member'] . ']' . $cleanMemberName . '[/url]' : $cleanMemberName),
  732. $row['id_member'],
  733. $cleanMemberName,
  734. ), $_POST['message']);
  735. $subject = str_replace($from_member,
  736. array(
  737. $row['email_address'],
  738. $row['real_name'],
  739. $row['id_member'],
  740. $row['real_name'],
  741. ), $_POST['subject']);
  742. // Send the actual email - or a PM!
  743. if (!$context['send_pm'])
  744. sendmail($row['email_address'], $subject, $message, null, null, !empty($_POST['send_html']), 5);
  745. else
  746. sendpm(array('to' => array($row['id_member']), 'bcc' => array()), $subject, $message);
  747. }
  748. $smcFunc['db_free_result']($result);
  749. }
  750. // If used our batch assume we still have a member.
  751. if ($i >= $num_at_once)
  752. $last_id_member = $context['start'];
  753. // Or we didn't have one in range?
  754. elseif (empty($last_id_member) && $context['start'] + $num_at_once < $context['max_id_member'])
  755. $last_id_member = $context['start'] + $num_at_once;
  756. // If we have no id_member then we're done.
  757. elseif (empty($last_id_member) && empty($context['recipients']['emails']))
  758. {
  759. // Log this into the admin log.
  760. logAction('newsletter', array(), 'admin');
  761. redirectexit('action=admin');
  762. }
  763. $context['start'] = $last_id_member;
  764. // Working out progress is a black art of sorts.
  765. $percentEmails = $context['total_emails'] == 0 ? 0 : ((count($context['recipients']['emails']) / $context['total_emails']) * ($context['total_emails'] / ($context['total_emails'] + $context['max_id_member'])));
  766. $percentMembers = ($context['start'] / $context['max_id_member']) * ($context['max_id_member'] / ($context['total_emails'] + $context['max_id_member']));
  767. $context['percentage_done'] = round(($percentEmails + $percentMembers) * 100, 2);
  768. $context['page_title'] = $txt['admin_newsletters'];
  769. $context['sub_template'] = 'email_members_send';
  770. }
  771. /**
  772. * Set general news and newsletter settings and permissions.
  773. * Called by ?action=admin;area=news;sa=settings.
  774. * Requires the forum_admin permission.
  775. *
  776. * @uses ManageNews template, news_settings sub-template.
  777. * @param bool $return_config = false
  778. */
  779. function ModifyNewsSettings($return_config = false)
  780. {
  781. global $context, $sourcedir, $modSettings, $txt, $scripturl;
  782. $config_vars = array(
  783. array('title', 'settings'),
  784. // Inline permissions.
  785. array('permissions', 'edit_news', 'help' => ''),
  786. array('permissions', 'send_mail'),
  787. '',
  788. // Just the remaining settings.
  789. array('check', 'xmlnews_enable', 'onclick' => 'document.getElementById(\'xmlnews_maxlen\').disabled = !this.checked;'),
  790. array('text', 'xmlnews_maxlen', 10),
  791. );
  792. call_integration_hook('integrate_modify_news_settings', array(&$config_vars));
  793. if ($return_config)
  794. return $config_vars;
  795. $context['page_title'] = $txt['admin_edit_news'] . ' - ' . $txt['settings'];
  796. $context['sub_template'] = 'show_settings';
  797. // Needed for the inline permission functions, and the settings template.
  798. // @todo is this really needed?
  799. require_once($sourcedir . '/ManagePermissions.php');
  800. require_once($sourcedir . '/ManageServer.php');
  801. // Wrap it all up nice and warm...
  802. $context['post_url'] = $scripturl . '?action=admin;area=news;save;sa=settings';
  803. $context['permissions_excluded'] = array(-1);
  804. // Add some javascript at the bottom...
  805. $context['settings_insert_below'] = '
  806. <script type="text/javascript"><!-- // --><![CDATA[
  807. document.getElementById("xmlnews_maxlen").disabled = !document.getElementById("xmlnews_enable").checked;
  808. // ]]></script>';
  809. // Saving the settings?
  810. if (isset($_GET['save']))
  811. {
  812. checkSession();
  813. call_integration_hook('integrate_save_news_settings');
  814. saveDBSettings($config_vars);
  815. redirectexit('action=admin;area=news;sa=settings');
  816. }
  817. prepareDBSettingContext($config_vars);
  818. }
  819. ?>