ManageNews.php 36 KB

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