ManageNews.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. 'get_items' => array(
  118. 'function' => 'list_getNews',
  119. ),
  120. 'columns' => array(
  121. 'news' => array(
  122. 'header' => array(
  123. 'value' => $txt['admin_edit_news'],
  124. ),
  125. 'data' => array(
  126. 'function' => create_function('$news', '
  127. if (is_numeric($news[\'id\']))
  128. 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>
  129. <div style="float:right" id="preview_\' . $news[\'id\'] . \'"></div>\';
  130. else
  131. return $news[\'unparsed\'];
  132. '),
  133. 'style' => 'width: 50%;',
  134. ),
  135. ),
  136. 'preview' => array(
  137. 'header' => array(
  138. 'value' => $txt['preview'],
  139. ),
  140. 'data' => array(
  141. 'function' => create_function('$news', '
  142. return \'<div id="box_preview_\' . $news[\'id\'] . \'" style="overflow: auto; width: 100%; height: 10ex;">\' . $news[\'parsed\'] . \'</div>\';
  143. '),
  144. 'style' => 'width: 45%;',
  145. ),
  146. ),
  147. 'check' => array(
  148. 'header' => array(
  149. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  150. ),
  151. 'data' => array(
  152. 'function' => create_function('$news', '
  153. if (is_numeric($news[\'id\']))
  154. return \'<input type="checkbox" name="remove[]" value="\' . $news[\'id\'] . \'" class="input_check" />\';
  155. else
  156. return \'\';
  157. '),
  158. 'style' => 'text-align: center',
  159. ),
  160. ),
  161. ),
  162. 'form' => array(
  163. 'href' => $scripturl . '?action=admin;area=news;sa=editnews',
  164. 'hidden_fields' => array(
  165. $context['session_var'] => $context['session_id'],
  166. ),
  167. ),
  168. 'additional_rows' => array(
  169. array(
  170. 'position' => 'bottom_of_list',
  171. 'value' => '
  172. <span id="moreNewsItems_link" style="display: none;">[<a href="javascript:void(0);" onclick="addNewsItem(); return false;">' . $txt['editnews_clickadd'] . '</a>]</span>
  173. <script type="text/javascript"><!-- // --><![CDATA[
  174. document.getElementById(\'list_news_lists_last\').style.display = "none";
  175. document.getElementById("moreNewsItems_link").style.display = "";
  176. var last_preview = 0;
  177. $(document).ready(function () {
  178. $("div[id ^= \'preview_\']").each(function () {
  179. var preview_id = $(this).attr(\'id\').split(\'_\')[1];
  180. if (last_preview < preview_id)
  181. last_preview = preview_id;
  182. make_preview_btn(preview_id);
  183. });
  184. });
  185. function make_preview_btn (preview_id)
  186. {
  187. $("#preview_" + preview_id).css({cursor: \'hand\', cursor: \'pointer\', });
  188. $("#preview_" + preview_id).text(\'' . $txt['preview'] . '\').click(function () {
  189. $.ajax({
  190. type: "POST",
  191. url: "' . $scripturl . '?action=xmlhttp;sa=previews;xml",
  192. data: {item: "newspreview", news: $("#preview_" + preview_id).prev().val()},
  193. context: document.body,
  194. success: function(request){
  195. if ($(request).find("error").text() == \'\')
  196. $(document).find("#box_preview_" + preview_id).html($(request).text());
  197. else
  198. $(document).find("#box_preview_" + preview_id).text(\'' . $txt['news_error_no_news'] . '\');
  199. },
  200. });
  201. });
  202. }
  203. function addNewsItem ()
  204. {
  205. last_preview++;
  206. $("#list_news_lists_last").before(' . javaScriptEscape('
  207. <tr class="windowbg') . ' + (last_preview % 2 == 0 ? \'\' : \'2\') + ' . javaScriptEscape('">
  208. <td style="width: 50%;">
  209. <textarea rows="3" cols="65" name="news[]" style="' . (isBrowser('is_ie8') ? 'width: 635px; max-width: 85%; min-width: 85%' : 'width: 85%') . ';"></textarea>
  210. <div style="float:right" id="preview_') . ' + last_preview + ' . javaScriptEscape('"></div>
  211. </td>
  212. <td style="width: 45%;">
  213. <div id="box_preview_') . ' + last_preview + ' . javaScriptEscape('" style="overflow: auto; width: 100%; height: 10ex;"></div>
  214. </td>
  215. <td></td>
  216. </tr>') . ');
  217. make_preview_btn(last_preview);
  218. }
  219. // ]]></script>
  220. <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" />',
  221. 'align' => 'right',
  222. ),
  223. ),
  224. );
  225. // Create the request list.
  226. createList($listOptions);
  227. $context['sub_template'] = 'show_list';
  228. $context['default_list'] = 'news_lists';
  229. }
  230. function list_getNews()
  231. {
  232. global $modSettings;
  233. $admin_current_news = array();
  234. // Ready the current news.
  235. foreach (explode("\n", $modSettings['news']) as $id => $line)
  236. $admin_current_news[$id] = array(
  237. 'id' => $id,
  238. 'unparsed' => un_preparsecode($line),
  239. 'parsed' => preg_replace('~<([/]?)form[^>]*?[>]*>~i', '<em class="smalltext">&lt;$1form&gt;</em>', parse_bbc($line)),
  240. );
  241. $admin_current_news['last'] = array(
  242. 'id' => 'last',
  243. 'unparsed' => '<div id="moreNewsItems"></div>
  244. <noscript><textarea rows="3" cols="65" name="news[]" style="' . (isBrowser('is_ie8') ? 'width: 635px; max-width: 85%; min-width: 85%' : 'width: 85%') . ';"></textarea></noscript>',
  245. 'parsed' => '<div id="moreNewsItems_preview"></div>',
  246. );
  247. return $admin_current_news;
  248. }
  249. /**
  250. * This function allows a user to select the membergroups to send their
  251. * mailing to.
  252. * Called by ?action=admin;area=news;sa=mailingmembers.
  253. * Requires the send_mail permission.
  254. * Form is submitted to ?action=admin;area=news;mailingcompose.
  255. *
  256. * @uses the ManageNews template and email_members sub template.
  257. */
  258. function SelectMailingMembers()
  259. {
  260. global $txt, $context, $modSettings, $smcFunc;
  261. $context['page_title'] = $txt['admin_newsletters'];
  262. $context['sub_template'] = 'email_members';
  263. $context['groups'] = array();
  264. $postGroups = array();
  265. $normalGroups = array();
  266. // If we have post groups disabled then we need to give a "ungrouped members" option.
  267. if (empty($modSettings['permission_enable_postgroups']))
  268. {
  269. $context['groups'][0] = array(
  270. 'id' => 0,
  271. 'name' => $txt['membergroups_members'],
  272. 'member_count' => 0,
  273. );
  274. $normalGroups[0] = 0;
  275. }
  276. // Get all the extra groups as well as Administrator and Global Moderator.
  277. $request = $smcFunc['db_query']('', '
  278. SELECT mg.id_group, mg.group_name, mg.min_posts
  279. FROM {db_prefix}membergroups AS mg' . (empty($modSettings['permission_enable_postgroups']) ? '
  280. WHERE mg.min_posts = {int:min_posts}' : '') . '
  281. GROUP BY mg.id_group, mg.min_posts, mg.group_name
  282. ORDER BY mg.min_posts, CASE WHEN mg.id_group < {int:newbie_group} THEN mg.id_group ELSE 4 END, mg.group_name',
  283. array(
  284. 'min_posts' => -1,
  285. 'newbie_group' => 4,
  286. )
  287. );
  288. while ($row = $smcFunc['db_fetch_assoc']($request))
  289. {
  290. $context['groups'][$row['id_group']] = array(
  291. 'id' => $row['id_group'],
  292. 'name' => $row['group_name'],
  293. 'member_count' => 0,
  294. );
  295. if ($row['min_posts'] == -1)
  296. $normalGroups[$row['id_group']] = $row['id_group'];
  297. else
  298. $postGroups[$row['id_group']] = $row['id_group'];
  299. }
  300. $smcFunc['db_free_result']($request);
  301. // If we have post groups, let's count the number of members...
  302. if (!empty($postGroups))
  303. {
  304. $query = $smcFunc['db_query']('', '
  305. SELECT mem.id_post_group AS id_group, COUNT(*) AS member_count
  306. FROM {db_prefix}members AS mem
  307. WHERE mem.id_post_group IN ({array_int:post_group_list})
  308. GROUP BY mem.id_post_group',
  309. array(
  310. 'post_group_list' => $postGroups,
  311. )
  312. );
  313. while ($row = $smcFunc['db_fetch_assoc']($query))
  314. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  315. $smcFunc['db_free_result']($query);
  316. }
  317. if (!empty($normalGroups))
  318. {
  319. // Find people who are members of this group...
  320. $query = $smcFunc['db_query']('', '
  321. SELECT id_group, COUNT(*) AS member_count
  322. FROM {db_prefix}members
  323. WHERE id_group IN ({array_int:normal_group_list})
  324. GROUP BY id_group',
  325. array(
  326. 'normal_group_list' => $normalGroups,
  327. )
  328. );
  329. while ($row = $smcFunc['db_fetch_assoc']($query))
  330. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  331. $smcFunc['db_free_result']($query);
  332. // Also do those who have it as an additional membergroup - this ones more yucky...
  333. $query = $smcFunc['db_query']('', '
  334. SELECT mg.id_group, COUNT(*) AS member_count
  335. FROM {db_prefix}membergroups AS mg
  336. INNER JOIN {db_prefix}members AS mem ON (mem.additional_groups != {string:blank_string}
  337. AND mem.id_group != mg.id_group
  338. AND FIND_IN_SET(mg.id_group, mem.additional_groups) != 0)
  339. WHERE mg.id_group IN ({array_int:normal_group_list})
  340. GROUP BY mg.id_group',
  341. array(
  342. 'normal_group_list' => $normalGroups,
  343. 'blank_string' => '',
  344. )
  345. );
  346. while ($row = $smcFunc['db_fetch_assoc']($query))
  347. $context['groups'][$row['id_group']]['member_count'] += $row['member_count'];
  348. $smcFunc['db_free_result']($query);
  349. }
  350. // Any moderators?
  351. $request = $smcFunc['db_query']('', '
  352. SELECT COUNT(DISTINCT id_member) AS num_distinct_mods
  353. FROM {db_prefix}moderators
  354. LIMIT 1',
  355. array(
  356. )
  357. );
  358. list ($context['groups'][3]['member_count']) = $smcFunc['db_fetch_row']($request);
  359. $smcFunc['db_free_result']($request);
  360. $context['can_send_pm'] = allowedTo('pm_send');
  361. }
  362. /**
  363. * Prepare subject and message of an email for the preview box
  364. * Used in ComposeMailing and RetrievePreview (Xml.php)
  365. */
  366. function prepareMailingForPreview ()
  367. {
  368. global $context, $smcFunc, $modSettings, $scripturl, $user_info, $txt;
  369. loadLanguage('Errors');
  370. $processing = array('preview_subject' => 'subject', 'preview_message' => 'message');
  371. // Use the default time format.
  372. $user_info['time_format'] = $modSettings['time_format'];
  373. $variables = array(
  374. '{$board_url}',
  375. '{$current_time}',
  376. '{$latest_member.link}',
  377. '{$latest_member.id}',
  378. '{$latest_member.name}'
  379. );
  380. $html = $context['send_html'];
  381. // We might need this in a bit
  382. $cleanLatestMember = empty($context['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
  383. foreach ($processing as $key => $post)
  384. {
  385. $context[$key] = !empty($_REQUEST[$post]) ? $_REQUEST[$post] : '';
  386. if (empty($context[$key]) && empty($_REQUEST['xml']))
  387. $context['post_error']['messages'][] = $txt['error_no_' . $post];
  388. elseif (!empty($_REQUEST['xml']))
  389. continue;
  390. preparsecode($context[$key]);
  391. if ($html)
  392. {
  393. $enablePostHTML = $modSettings['enablePostHTML'];
  394. $modSettings['enablePostHTML'] = $context['send_html'];
  395. $context[$key] = parse_bbc($context[$key]);
  396. $modSettings['enablePostHTML'] = $enablePostHTML;
  397. }
  398. // Replace in all the standard things.
  399. $context[$key] = str_replace($variables,
  400. array(
  401. !empty($context['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl,
  402. timeformat(forum_time(), false),
  403. !empty($context['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),
  404. $modSettings['latestMember'],
  405. $cleanLatestMember
  406. ), $context[$key]);
  407. }
  408. }
  409. /**
  410. * Shows a form to edit a forum mailing and its recipients.
  411. * Called by ?action=admin;area=news;sa=mailingcompose.
  412. * Requires the send_mail permission.
  413. * Form is submitted to ?action=admin;area=news;sa=mailingsend.
  414. *
  415. * @uses ManageNews template, email_members_compose sub-template.
  416. */
  417. function ComposeMailing()
  418. {
  419. global $txt, $sourcedir, $context, $smcFunc, $scripturl, $modSettings;
  420. // Setup the template!
  421. $context['page_title'] = $txt['admin_newsletters'];
  422. $context['sub_template'] = 'email_members_compose';
  423. $context['subject'] = !empty($_POST['subject']) ? $_POST['subject'] : htmlspecialchars($context['forum_name'] . ': ' . $txt['subject']);
  424. $context['message'] = !empty($_POST['message']) ? $_POST['message'] : htmlspecialchars($txt['message'] . "\n\n" . $txt['regards_team'] . "\n\n" . '{$board_url}');
  425. // Needed for the WYSIWYG editor.
  426. require_once($sourcedir . '/Subs-Editor.php');
  427. // Now create the editor.
  428. $editorOptions = array(
  429. 'id' => 'message',
  430. 'value' => $context['message'],
  431. 'height' => '175px',
  432. 'width' => '100%',
  433. 'labels' => array(
  434. 'post_button' => $txt['sendtopic_send'],
  435. ),
  436. 'preview_type' => 2,
  437. );
  438. create_control_richedit($editorOptions);
  439. // Store the ID for old compatibility.
  440. $context['post_box_name'] = $editorOptions['id'];
  441. if (isset($context['preview']))
  442. {
  443. require_once($sourcedir . '/Subs-Post.php');
  444. $context['recipients']['members'] = !empty($_POST['members']) ? explode(',', $_POST['members']) : array();
  445. $context['recipients']['exclude_members'] = !empty($_POST['exclude_members']) ? explode(',', $_POST['exclude_members']) : array();
  446. $context['recipients']['groups'] = !empty($_POST['groups']) ? explode(',', $_POST['groups']) : array();
  447. $context['recipients']['exclude_groups'] = !empty($_POST['exclude_groups']) ? explode(',', $_POST['exclude_groups']) : array();
  448. $context['recipients']['emails'] = !empty($_POST['emails']) ? explode(';', $_POST['emails']) : array();
  449. $context['email_force'] = !empty($_POST['email_force']) ? 1 : 0;
  450. $context['total_emails'] = !empty($_POST['total_emails']) ? (int) $_POST['total_emails'] : 0;
  451. $context['max_id_member'] = !empty($_POST['max_id_member']) ? (int) $_POST['max_id_member'] : 0;
  452. $context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
  453. $context['send_html'] = !empty($_POST['send_html']) ? '1' : '0';
  454. return prepareMailingForPreview();
  455. }
  456. // Start by finding any members!
  457. $toClean = array();
  458. if (!empty($_POST['members']))
  459. $toClean[] = 'members';
  460. if (!empty($_POST['exclude_members']))
  461. $toClean[] = 'exclude_members';
  462. if (!empty($toClean))
  463. {
  464. require_once($sourcedir . '/Subs-Auth.php');
  465. foreach ($toClean as $type)
  466. {
  467. // Remove the quotes.
  468. $_POST[$type] = strtr($_POST[$type], array('\\"' => '"'));
  469. preg_match_all('~"([^"]+)"~', $_POST[$type], $matches);
  470. $_POST[$type] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST[$type]))));
  471. foreach ($_POST[$type] as $index => $member)
  472. if (strlen(trim($member)) > 0)
  473. $_POST[$type][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($member)));
  474. else
  475. unset($_POST[$type][$index]);
  476. // Find the members
  477. $_POST[$type] = implode(',', array_keys(findMembers($_POST[$type])));
  478. }
  479. }
  480. if (isset($_POST['member_list']) && is_array($_POST['member_list']))
  481. {
  482. $members = array();
  483. foreach ($_POST['member_list'] as $member_id)
  484. $members[] = (int) $member_id;
  485. $_POST['members'] = implode(',', $members);
  486. }
  487. if (isset($_POST['exclude_member_list']) && is_array($_POST['exclude_member_list']))
  488. {
  489. $members = array();
  490. foreach ($_POST['exclude_member_list'] as $member_id)
  491. $members[] = (int) $member_id;
  492. $_POST['exclude_members'] = implode(',', $members);
  493. }
  494. // Clean the other vars.
  495. SendMailing(true);
  496. // We need a couple strings from the email template file
  497. loadLanguage('EmailTemplates');
  498. // 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.
  499. $request = $smcFunc['db_query']('', '
  500. SELECT DISTINCT mem.id_member
  501. FROM {db_prefix}ban_groups AS bg
  502. INNER JOIN {db_prefix}ban_items AS bi ON (bg.id_ban_group = bi.id_ban_group)
  503. INNER JOIN {db_prefix}members AS mem ON (bi.id_member = mem.id_member)
  504. WHERE (bg.cannot_access = {int:cannot_access} OR bg.cannot_login = {int:cannot_login})
  505. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})',
  506. array(
  507. 'cannot_access' => 1,
  508. 'cannot_login' => 1,
  509. 'current_time' => time(),
  510. )
  511. );
  512. while ($row = $smcFunc['db_fetch_assoc']($request))
  513. $context['recipients']['exclude_members'][] = $row['id_member'];
  514. $smcFunc['db_free_result']($request);
  515. $request = $smcFunc['db_query']('', '
  516. SELECT DISTINCT bi.email_address
  517. FROM {db_prefix}ban_items AS bi
  518. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  519. WHERE (bg.cannot_access = {int:cannot_access} OR bg.cannot_login = {int:cannot_login})
  520. AND (COALESCE(bg.expire_time, 1=1) OR bg.expire_time > {int:current_time})
  521. AND bi.email_address != {string:blank_string}',
  522. array(
  523. 'cannot_access' => 1,
  524. 'cannot_login' => 1,
  525. 'current_time' => time(),
  526. 'blank_string' => '',
  527. )
  528. );
  529. $condition_array = array();
  530. $condition_array_params = array();
  531. $count = 0;
  532. while ($row = $smcFunc['db_fetch_assoc']($request))
  533. {
  534. $condition_array[] = '{string:email_' . $count . '}';
  535. $condition_array_params['email_' . $count++] = $row['email_address'];
  536. }
  537. $smcFunc['db_free_result']($request);
  538. if (!empty($condition_array))
  539. {
  540. $request = $smcFunc['db_query']('', '
  541. SELECT id_member
  542. FROM {db_prefix}members
  543. WHERE email_address IN(' . implode(', ', $condition_array) .')',
  544. $condition_array_params
  545. );
  546. while ($row = $smcFunc['db_fetch_assoc']($request))
  547. $context['recipients']['exclude_members'][] = $row['id_member'];
  548. $smcFunc['db_free_result']($request);
  549. }
  550. // Did they select moderators - if so add them as specific members...
  551. if ((!empty($context['recipients']['groups']) && in_array(3, $context['recipients']['groups'])) || (!empty($context['recipients']['exclude_groups']) && in_array(3, $context['recipients']['exclude_groups'])))
  552. {
  553. $request = $smcFunc['db_query']('', '
  554. SELECT DISTINCT mem.id_member AS identifier
  555. FROM {db_prefix}members AS mem
  556. INNER JOIN {db_prefix}moderators AS mods ON (mods.id_member = mem.id_member)
  557. WHERE mem.is_activated = {int:is_activated}',
  558. array(
  559. 'is_activated' => 1,
  560. )
  561. );
  562. while ($row = $smcFunc['db_fetch_assoc']($request))
  563. {
  564. if (in_array(3, $context['recipients']))
  565. $context['recipients']['exclude_members'][] = $row['identifier'];
  566. else
  567. $context['recipients']['members'][] = $row['identifier'];
  568. }
  569. $smcFunc['db_free_result']($request);
  570. }
  571. // For progress bar!
  572. $context['total_emails'] = count($context['recipients']['emails']);
  573. $request = $smcFunc['db_query']('', '
  574. SELECT MAX(id_member)
  575. FROM {db_prefix}members',
  576. array(
  577. )
  578. );
  579. list ($context['max_id_member']) = $smcFunc['db_fetch_row']($request);
  580. $smcFunc['db_free_result']($request);
  581. // Clean up the arrays.
  582. $context['recipients']['members'] = array_unique($context['recipients']['members']);
  583. $context['recipients']['exclude_members'] = array_unique($context['recipients']['exclude_members']);
  584. }
  585. /**
  586. * Handles the sending of the forum mailing in batches.
  587. * Called by ?action=admin;area=news;sa=mailingsend
  588. * Requires the send_mail permission.
  589. * Redirects to itself when more batches need to be sent.
  590. * Redirects to ?action=admin after everything has been sent.
  591. *
  592. * @param bool $clean_only = false; if set, it will only clean the variables, put them in context, then return.
  593. * @uses the ManageNews template and email_members_send sub template.
  594. */
  595. function SendMailing($clean_only = false)
  596. {
  597. global $txt, $sourcedir, $context, $smcFunc;
  598. global $scripturl, $modSettings, $user_info;
  599. if (isset($_POST['preview']))
  600. {
  601. $context['preview'] = true;
  602. return ComposeMailing();
  603. }
  604. // How many to send at once? Quantity depends on whether we are queueing or not.
  605. $num_at_once = empty($modSettings['mail_queue']) ? 60 : 1000;
  606. // If by PM's I suggest we half the above number.
  607. if (!empty($_POST['send_pm']))
  608. $num_at_once /= 2;
  609. checkSession();
  610. // Where are we actually to?
  611. $context['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
  612. $context['email_force'] = !empty($_POST['email_force']) ? 1 : 0;
  613. $context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
  614. $context['total_emails'] = !empty($_POST['total_emails']) ? (int) $_POST['total_emails'] : 0;
  615. $context['max_id_member'] = !empty($_POST['max_id_member']) ? (int) $_POST['max_id_member'] : 0;
  616. $context['send_html'] = !empty($_POST['send_html']) ? '1' : '0';
  617. $context['parse_html'] = !empty($_POST['parse_html']) ? '1' : '0';
  618. // Create our main context.
  619. $context['recipients'] = array(
  620. 'groups' => array(),
  621. 'exclude_groups' => array(),
  622. 'members' => array(),
  623. 'exclude_members' => array(),
  624. 'emails' => array(),
  625. );
  626. // Have we any excluded members?
  627. if (!empty($_POST['exclude_members']))
  628. {
  629. $members = explode(',', $_POST['exclude_members']);
  630. foreach ($members as $member)
  631. if ($member >= $context['start'])
  632. $context['recipients']['exclude_members'][] = (int) $member;
  633. }
  634. // What about members we *must* do?
  635. if (!empty($_POST['members']))
  636. {
  637. $members = explode(',', $_POST['members']);
  638. foreach ($members as $member)
  639. if ($member >= $context['start'])
  640. $context['recipients']['members'][] = (int) $member;
  641. }
  642. // Cleaning groups is simple - although deal with both checkbox and commas.
  643. if (!empty($_POST['groups']))
  644. {
  645. if (is_array($_POST['groups']))
  646. {
  647. foreach ($_POST['groups'] as $group => $dummy)
  648. $context['recipients']['groups'][] = (int) $group;
  649. }
  650. else
  651. {
  652. $groups = explode(',', $_POST['groups']);
  653. foreach ($groups as $group)
  654. $context['recipients']['groups'][] = (int) $group;
  655. }
  656. }
  657. // Same for excluded groups
  658. if (!empty($_POST['exclude_groups']))
  659. {
  660. if (is_array($_POST['exclude_groups']))
  661. {
  662. foreach ($_POST['exclude_groups'] as $group => $dummy)
  663. $context['recipients']['exclude_groups'][] = (int) $group;
  664. }
  665. else
  666. {
  667. $groups = explode(',', $_POST['exclude_groups']);
  668. foreach ($groups as $group)
  669. $context['recipients']['exclude_groups'][] = (int) $group;
  670. }
  671. }
  672. // Finally - emails!
  673. if (!empty($_POST['emails']))
  674. {
  675. $addressed = array_unique(explode(';', strtr($_POST['emails'], array("\n" => ';', "\r" => ';', ',' => ';'))));
  676. foreach ($addressed as $curmem)
  677. {
  678. $curmem = trim($curmem);
  679. if ($curmem != '')
  680. $context['recipients']['emails'][$curmem] = $curmem;
  681. }
  682. }
  683. // If we're only cleaning drop out here.
  684. if ($clean_only)
  685. return;
  686. require_once($sourcedir . '/Subs-Post.php');
  687. // We are relying too much on writing to superglobals...
  688. $_POST['subject'] = !empty($_POST['subject']) ? $_POST['subject'] : '';
  689. $_POST['message'] = !empty($_POST['message']) ? $_POST['message'] : '';
  690. // Save the message and its subject in $context
  691. $context['subject'] = htmlspecialchars($_POST['subject']);
  692. $context['message'] = htmlspecialchars($_POST['message']);
  693. // Prepare the message for sending it as HTML
  694. if (!$context['send_pm'] && !empty($_POST['send_html']))
  695. {
  696. // Prepare the message for HTML.
  697. if (!empty($_POST['parse_html']))
  698. $_POST['message'] = str_replace(array("\n", ' '), array('<br />' . "\n", '&nbsp; '), $_POST['message']);
  699. // This is here to prevent spam filters from tagging this as spam.
  700. if (preg_match('~\<html~i', $_POST['message']) == 0)
  701. {
  702. if (preg_match('~\<body~i', $_POST['message']) == 0)
  703. $_POST['message'] = '<html><head><title>' . $_POST['subject'] . '</title></head>' . "\n" . '<body>' . $_POST['message'] . '</body></html>';
  704. else
  705. $_POST['message'] = '<html>' . $_POST['message'] . '</html>';
  706. }
  707. }
  708. if (empty($_POST['message']) || empty($_POST['subject']))
  709. {
  710. $context['preview'] = true;
  711. return ComposeMailing();
  712. }
  713. // Use the default time format.
  714. $user_info['time_format'] = $modSettings['time_format'];
  715. $variables = array(
  716. '{$board_url}',
  717. '{$current_time}',
  718. '{$latest_member.link}',
  719. '{$latest_member.id}',
  720. '{$latest_member.name}'
  721. );
  722. // We might need this in a bit
  723. $cleanLatestMember = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
  724. // Replace in all the standard things.
  725. $_POST['message'] = str_replace($variables,
  726. array(
  727. !empty($_POST['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl,
  728. timeformat(forum_time(), false),
  729. !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),
  730. $modSettings['latestMember'],
  731. $cleanLatestMember
  732. ), $_POST['message']);
  733. $_POST['subject'] = str_replace($variables,
  734. array(
  735. $scripturl,
  736. timeformat(forum_time(), false),
  737. $modSettings['latestRealName'],
  738. $modSettings['latestMember'],
  739. $modSettings['latestRealName']
  740. ), $_POST['subject']);
  741. $from_member = array(
  742. '{$member.email}',
  743. '{$member.link}',
  744. '{$member.id}',
  745. '{$member.name}'
  746. );
  747. // If we still have emails, do them first!
  748. $i = 0;
  749. foreach ($context['recipients']['emails'] as $k => $email)
  750. {
  751. // Done as many as we can?
  752. if ($i >= $num_at_once)
  753. break;
  754. // Don't sent it twice!
  755. unset($context['recipients']['emails'][$k]);
  756. // Dammit - can't PM emails!
  757. if ($context['send_pm'])
  758. continue;
  759. $to_member = array(
  760. $email,
  761. !empty($_POST['send_html']) ? '<a href="mailto:' . $email . '">' . $email . '</a>' : $email,
  762. '??',
  763. $email
  764. );
  765. 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);
  766. // Done another...
  767. $i++;
  768. }
  769. // Got some more to send this batch?
  770. $last_id_member = 0;
  771. if ($i < $num_at_once)
  772. {
  773. // Need to build quite a query!
  774. $sendQuery = '(';
  775. $sendParams = array();
  776. if (!empty($context['recipients']['groups']))
  777. {
  778. // Take the long route...
  779. $queryBuild = array();
  780. foreach ($context['recipients']['groups'] as $group)
  781. {
  782. $sendParams['group_' . $group] = $group;
  783. $queryBuild[] = 'mem.id_group = {int:group_' . $group . '}';
  784. if (!empty($group))
  785. {
  786. $queryBuild[] = 'FIND_IN_SET({int:group_' . $group . '}, mem.additional_groups) != 0';
  787. $queryBuild[] = 'mem.id_post_group = {int:group_' . $group . '}';
  788. }
  789. }
  790. if (!empty($queryBuild))
  791. $sendQuery .= implode(' OR ', $queryBuild);
  792. }
  793. if (!empty($context['recipients']['members']))
  794. {
  795. $sendQuery .= ($sendQuery == '(' ? '' : ' OR ') . 'mem.id_member IN ({array_int:members})';
  796. $sendParams['members'] = $context['recipients']['members'];
  797. }
  798. $sendQuery .= ')';
  799. // If we've not got a query then we must be done!
  800. if ($sendQuery == '()')
  801. redirectexit('action=admin');
  802. // Anything to exclude?
  803. if (!empty($context['recipients']['exclude_groups']) && in_array(0, $context['recipients']['exclude_groups']))
  804. $sendQuery .= ' AND mem.id_group != {int:regular_group}';
  805. if (!empty($context['recipients']['exclude_members']))
  806. {
  807. $sendQuery .= ' AND mem.id_member NOT IN ({array_int:exclude_members})';
  808. $sendParams['exclude_members'] = $context['recipients']['exclude_members'];
  809. }
  810. // Force them to have it?
  811. if (empty($context['email_force']))
  812. $sendQuery .= ' AND mem.notify_announcements = {int:notify_announcements}';
  813. // Get the smelly people - note we respect the id_member range as it gives us a quicker query.
  814. $result = $smcFunc['db_query']('', '
  815. SELECT mem.id_member, mem.email_address, mem.real_name, mem.id_group, mem.additional_groups, mem.id_post_group
  816. FROM {db_prefix}members AS mem
  817. WHERE mem.id_member > {int:min_id_member}
  818. AND mem.id_member < {int:max_id_member}
  819. AND ' . $sendQuery . '
  820. AND mem.is_activated = {int:is_activated}
  821. ORDER BY mem.id_member ASC
  822. LIMIT {int:atonce}',
  823. array_merge($sendParams, array(
  824. 'min_id_member' => $context['start'],
  825. 'max_id_member' => $context['start'] + $num_at_once - $i,
  826. 'atonce' => $num_at_once - $i,
  827. 'regular_group' => 0,
  828. 'notify_announcements' => 1,
  829. 'is_activated' => 1,
  830. ))
  831. );
  832. while ($row = $smcFunc['db_fetch_assoc']($result))
  833. {
  834. $last_id_member = $row['id_member'];
  835. // What groups are we looking at here?
  836. if (empty($row['additional_groups']))
  837. $groups = array($row['id_group'], $row['id_post_group']);
  838. else
  839. $groups = array_merge(
  840. array($row['id_group'], $row['id_post_group']),
  841. explode(',', $row['additional_groups'])
  842. );
  843. // Excluded groups?
  844. if (array_intersect($groups, $context['recipients']['exclude_groups']))
  845. continue;
  846. // We might need this
  847. $cleanMemberName = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($row['real_name']) : $row['real_name'];
  848. // Replace the member-dependant variables
  849. $message = str_replace($from_member,
  850. array(
  851. $row['email_address'],
  852. !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),
  853. $row['id_member'],
  854. $cleanMemberName,
  855. ), $_POST['message']);
  856. $subject = str_replace($from_member,
  857. array(
  858. $row['email_address'],
  859. $row['real_name'],
  860. $row['id_member'],
  861. $row['real_name'],
  862. ), $_POST['subject']);
  863. // Send the actual email - or a PM!
  864. if (!$context['send_pm'])
  865. sendmail($row['email_address'], $subject, $message, null, null, !empty($_POST['send_html']), 5);
  866. else
  867. sendpm(array('to' => array($row['id_member']), 'bcc' => array()), $subject, $message);
  868. }
  869. $smcFunc['db_free_result']($result);
  870. }
  871. // If used our batch assume we still have a member.
  872. if ($i >= $num_at_once)
  873. $last_id_member = $context['start'];
  874. // Or we didn't have one in range?
  875. elseif (empty($last_id_member) && $context['start'] + $num_at_once < $context['max_id_member'])
  876. $last_id_member = $context['start'] + $num_at_once;
  877. // If we have no id_member then we're done.
  878. elseif (empty($last_id_member) && empty($context['recipients']['emails']))
  879. {
  880. // Log this into the admin log.
  881. logAction('newsletter', array(), 'admin');
  882. redirectexit('action=admin');
  883. }
  884. $context['start'] = $last_id_member;
  885. // Working out progress is a black art of sorts.
  886. $percentEmails = $context['total_emails'] == 0 ? 0 : ((count($context['recipients']['emails']) / $context['total_emails']) * ($context['total_emails'] / ($context['total_emails'] + $context['max_id_member'])));
  887. $percentMembers = ($context['start'] / $context['max_id_member']) * ($context['max_id_member'] / ($context['total_emails'] + $context['max_id_member']));
  888. $context['percentage_done'] = round(($percentEmails + $percentMembers) * 100, 2);
  889. $context['page_title'] = $txt['admin_newsletters'];
  890. $context['sub_template'] = 'email_members_send';
  891. }
  892. /**
  893. * Set general news and newsletter settings and permissions.
  894. * Called by ?action=admin;area=news;sa=settings.
  895. * Requires the forum_admin permission.
  896. *
  897. * @uses ManageNews template, news_settings sub-template.
  898. * @param bool $return_config = false
  899. */
  900. function ModifyNewsSettings($return_config = false)
  901. {
  902. global $context, $sourcedir, $modSettings, $txt, $scripturl;
  903. $config_vars = array(
  904. array('title', 'settings'),
  905. // Inline permissions.
  906. array('permissions', 'edit_news', 'help' => ''),
  907. array('permissions', 'send_mail'),
  908. '',
  909. // Just the remaining settings.
  910. array('check', 'xmlnews_enable', 'onclick' => 'document.getElementById(\'xmlnews_maxlen\').disabled = !this.checked;'),
  911. array('text', 'xmlnews_maxlen', 'subtext' => $txt['xmlnews_maxlen_note'], 10),
  912. );
  913. call_integration_hook('integrate_modify_news_settings', array(&$config_vars));
  914. if ($return_config)
  915. return $config_vars;
  916. $context['page_title'] = $txt['admin_edit_news'] . ' - ' . $txt['settings'];
  917. $context['sub_template'] = 'show_settings';
  918. // Needed for the inline permission functions, and the settings template.
  919. // @todo is this really needed?
  920. require_once($sourcedir . '/ManagePermissions.php');
  921. require_once($sourcedir . '/ManageServer.php');
  922. // Wrap it all up nice and warm...
  923. $context['post_url'] = $scripturl . '?action=admin;area=news;save;sa=settings';
  924. $context['permissions_excluded'] = array(-1);
  925. // Add some javascript at the bottom...
  926. $context['settings_insert_below'] = '
  927. <script type="text/javascript"><!-- // --><![CDATA[
  928. document.getElementById("xmlnews_maxlen").disabled = !document.getElementById("xmlnews_enable").checked;
  929. // ]]></script>';
  930. // Saving the settings?
  931. if (isset($_GET['save']))
  932. {
  933. checkSession();
  934. call_integration_hook('integrate_save_news_settings');
  935. saveDBSettings($config_vars);
  936. redirectexit('action=admin;area=news;sa=settings');
  937. }
  938. // We need this for the in-line permissions
  939. createToken('admin-mp');
  940. prepareDBSettingContext($config_vars);
  941. }
  942. ?>