ManageNews.php 30 KB

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