ManageNews.php 36 KB

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