ManageNews.php 36 KB

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