ManageNews.php 36 KB

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