ManageNews.php 36 KB

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