ManageNews.php 36 KB

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