function activateAccount($memID) { global $sourcedir, $context, $user_profile, $modSettings; isAllowedTo('moderate_forum'); if (isset($_REQUEST['save']) && isset($user_profile[$memID]['is_activated']) && $user_profile[$memID]['is_activated'] != 1) { // If we are approving the deletion of an account, we do something special ;) if ($user_profile[$memID]['is_activated'] == 4) { require_once $sourcedir . '/Subs-Members.php'; deleteMembers($context['id_member']); redirectexit(); } // Let the integrations know of the activation. call_integration_hook('integrate_activate', array($user_profile[$memID]['member_name'])); // Actually update this member now, as it guarantees the unapproved count can't get corrupted. updateMemberData($context['id_member'], array('is_activated' => $user_profile[$memID]['is_activated'] >= 10 ? 11 : 1, 'validation_code' => '')); // If we are doing approval, update the stats for the member just in case. if (in_array($user_profile[$memID]['is_activated'], array(3, 4, 13, 14))) { updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > 1 ? $modSettings['unapprovedMembers'] - 1 : 0)); } // Make sure we update the stats too. updateStats('member', false); } // Leave it be... redirectexit('action=profile;u=' . $memID . ';area=summary'); }
function updateUniqueClicks($class, $id) { if (!isset($_COOKIE["ffjvisit_" . $class . $id])) { setcookie("ffjvisit_" . $class . $id, "true", time() + 86400, "/", ".fastfoodjobsuk.co.uk"); updateStats($class, $id, "clicks"); } }
function returnSeed() { global $db, $seedtable; global $reservationid, $externaldns, $secondDCstart, $indexid; # Find external dns of first node $query = $db->prepare("SELECT seed_dns\n FROM {$seedtable} \n WHERE reservation_id=:reservationid AND index_id=0"); $query->bindParam(':reservationid', $reservationid, PDO::PARAM_STR, 20); $query->execute(); $results = $query->fetchAll(); $zeronodedns = $results[0]['seed_dns']; # Query for the seeds. $query = $db->prepare("SELECT seed_ip, index_id \n FROM {$seedtable} \n WHERE reservation_id=:reservationid AND (index_id=0 OR index_id=:secondDCstart)\n ORDER BY index_id"); $query->bindParam(':reservationid', $reservationid, PDO::PARAM_STR, 20); $query->bindParam(':secondDCstart', $secondDCstart, PDO::PARAM_STR, 20); $query->execute(); $results = $query->fetchAll(); if ($indexid == 0 and sizeof($results) >= 1) { newStats(1); } elseif ($indexid > 0) { updateStats(); } echo sizeof($results); echo "\n" . $externaldns; #print_r($results); foreach ($results as $result) { echo "\n" . $result['seed_ip']; } }
/** * Finds or repairs errors in the database to fix possible problems. * Requires the admin_forum permission. * Calls createSalvageArea() to create a new board, if necesary. * Accessed by ?action=admin;area=repairboards. * * @uses raw_data sub-template. */ function RepairBoards() { global $txt, $context, $sourcedir, $salvageBoardID; isAllowedTo('admin_forum'); // Try secure more memory. setMemoryLimit('128M'); // Print out the top of the webpage. $context['page_title'] = $txt['admin_repair']; $context['sub_template'] = 'repair_boards'; $context[$context['admin_menu_name']]['current_subsection'] = 'general'; // Load the language file. loadLanguage('ManageMaintenance'); // Make sure the tabs stay nice. $context[$context['admin_menu_name']]['tab_data'] = array('title' => $txt['maintain_title'], 'help' => '', 'description' => $txt['maintain_info'], 'tabs' => array()); // Start displaying errors without fixing them. if (isset($_GET['fixErrors'])) { checkSession('get'); } // Will want this. loadForumTests(); // Giant if/else. The first displays the forum errors if a variable is not set and asks // if you would like to continue, the other fixes the errors. if (!isset($_GET['fixErrors'])) { $context['error_search'] = true; $context['repair_errors'] = array(); $context['to_fix'] = findForumErrors(); if (!empty($context['to_fix'])) { $_SESSION['repairboards_to_fix'] = $context['to_fix']; $_SESSION['repairboards_to_fix2'] = null; if (empty($context['repair_errors'])) { $context['repair_errors'][] = '???'; } } } else { $context['error_search'] = false; $context['to_fix'] = isset($_SESSION['repairboards_to_fix']) ? $_SESSION['repairboards_to_fix'] : array(); require_once $sourcedir . '/Subs-Boards.php'; // Actually do the fix. findForumErrors(true); // Note that we've changed everything possible ;) updateSettings(array('settings_updated' => time())); updateStats('message'); updateStats('topic'); updateSettings(array('calendar_updated' => time())); if (!empty($salvageBoardID)) { $context['redirect_to_recount'] = true; } $_SESSION['repairboards_to_fix'] = null; $_SESSION['repairboards_to_fix2'] = null; } }
function resetStats() { $games = file_get_contents('games.log'); $games = explode("\n", $games); file_put_contents('games.stats', ''); file_put_contents('players.stats', ''); foreach ($games as $game) { if (empty($game)) { continue; } $game = explode("\t", $game); updateStats($game[0], $game[1], $game[2], $game[3], false); } }
function fix_serialized_columns() { global $db_prefix; $request = db_query("\n\t\tSELECT ID_ACTION, extra\n\t\tFROM {$db_prefix}log_actions\n\t\tWHERE action IN ('remove', 'delete')", __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { if (@unserialize($row['extra']) === false && preg_match('~^(a:3:{s:5:"topic";i:\\d+;s:7:"subject";s:)(\\d+):"(.+)"(;s:6:"member";s:5:"\\d+";})$~', $row['extra'], $matches) === 1) { db_query("\n\t\t\t\tUPDATE {$db_prefix}log_actions\n\t\t\t\tSET extra = '{$matches['1']}" . strlen($matches[3]) . ":\"{$matches['3']}\"{$matches['4']}'\n\t\t\t\tWHERE ID_ACTION = {$row['ID_ACTION']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); } } mysql_free_result($request); // Refresh some serialized strings stored in the settings table. updateStats('calendar'); // The memberlist cache needs to be recalculated too. updateSettings(array('memberlist_updated' => time())); }
function ModifySettings() { global $modSettings, $context, $settings, $db_prefix, $txt, $boarddir, $sourcedir; loadTemplate('ManageCalendar'); $context['page_title'] = $txt['calendar_settings']; $context['sub_template'] = 'modify_settings'; // A file we need to show permissions inline. require_once $sourcedir . '/ManagePermissions.php'; $calendarPermissions = array('calendar_view', 'calendar_post', 'calendar_edit_own', 'calendar_edit_any'); // A form was submitted. if (isset($_POST['sc'], $_POST['cal_days_for_index'])) { checkSession(); // Although the display settings are combined to the user, they are seperate to the database. $toSet['cal_showholidaysonindex'] = $_POST['cal_showholidays'] == 'index' || $_POST['cal_showholidays'] == 'all' ? '1' : '0'; $toSet['cal_showbdaysonindex'] = $_POST['cal_showbdays'] == 'index' || $_POST['cal_showbdays'] == 'all' ? '1' : '0'; $toSet['cal_showeventsonindex'] = $_POST['cal_showevents'] == 'index' || $_POST['cal_showevents'] == 'all' ? '1' : '0'; $toSet['cal_showholidaysoncalendar'] = $_POST['cal_showholidays'] == 'cal' || $_POST['cal_showholidays'] == 'all' ? '1' : '0'; $toSet['cal_showbdaysoncalendar'] = $_POST['cal_showbdays'] == 'cal' || $_POST['cal_showbdays'] == 'all' ? '1' : '0'; $toSet['cal_showeventsoncalendar'] = $_POST['cal_showevents'] == 'cal' || $_POST['cal_showevents'] == 'all' ? '1' : '0'; updateSettings(array('cal_enabled' => isset($_POST['cal_enabled']) ? '1' : '0', 'cal_daysaslink' => isset($_POST['cal_daysaslink']) ? '1' : '0', 'cal_showweeknum' => isset($_POST['cal_showweeknum']) ? '1' : '0', 'cal_days_for_index' => (int) $_POST['cal_days_for_index'], 'cal_showholidaysonindex' => $toSet['cal_showholidaysonindex'], 'cal_showbdaysonindex' => $toSet['cal_showbdaysonindex'], 'cal_showeventsonindex' => $toSet['cal_showeventsonindex'], 'cal_showholidaysoncalendar' => $toSet['cal_showholidaysoncalendar'], 'cal_showbdaysoncalendar' => $toSet['cal_showbdaysoncalendar'], 'cal_showeventsoncalendar' => $toSet['cal_showeventsoncalendar'], 'cal_defaultboard' => (int) $_POST['cal_defaultboard'], 'cal_allow_unlinked' => isset($_POST['cal_allow_unlinked']) ? '1' : '0', 'cal_minyear' => (int) $_POST['cal_minyear'], 'cal_maxyear' => (int) $_POST['cal_maxyear'], 'cal_bdaycolor' => $_POST['cal_bdaycolor'], 'cal_eventcolor' => $_POST['cal_eventcolor'], 'cal_holidaycolor' => $_POST['cal_holidaycolor'], 'cal_allowspan' => isset($_POST['cal_allowspan']) ? '1' : '0', 'cal_maxspan' => (int) $_POST['cal_maxspan'], 'cal_showInTopic' => isset($_POST['cal_showInTopic']) ? '1' : '0')); save_inline_permissions($calendarPermissions); updateStats('calendar'); // Ensure we redirect incase the change in settings means the tabs are outdated. redirectexit('action=managecalendar;sa=settings'); } // Load the boards list. $context['cal_boards'] = array(''); $request = db_query("\n\t\tSELECT b.ID_BOARD, b.name AS bName, c.name AS cName\n\t\tFROM {$db_prefix}boards AS b\n\t\t\tLEFT JOIN {$db_prefix}categories AS c ON (c.ID_CAT = b.ID_CAT)", __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { $context['cal_boards'][$row['ID_BOARD']] = $row['cName'] . ' - ' . $row['bName']; } mysql_free_result($request); // Initialize the inline permission settings. init_inline_permissions($calendarPermissions); // Setup the display settings, just for better UI ;) $context['cal_showholidays'] = empty($modSettings['cal_showholidaysonindex']) ? empty($modSettings['cal_showholidaysoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showholidaysoncalendar']) ? 'index' : 'all'); $context['cal_showbdays'] = empty($modSettings['cal_showbdaysonindex']) ? empty($modSettings['cal_showbdaysoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showbdaysoncalendar']) ? 'index' : 'all'); $context['cal_showevents'] = empty($modSettings['cal_showeventsonindex']) ? empty($modSettings['cal_showeventsoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showeventsoncalendar']) ? 'index' : 'all'); }
/** * Activate an account. * This function is called from the profile account actions area. */ public function action_activateaccount() { global $context, $user_profile, $modSettings; isAllowedTo('moderate_forum'); $memID = currentMemberID(); if (isset($_REQUEST['save']) && isset($user_profile[$memID]['is_activated']) && $user_profile[$memID]['is_activated'] != 1) { require_once SUBSDIR . '/Members.subs.php'; // If we are approving the deletion of an account, we do something special ;) if ($user_profile[$memID]['is_activated'] == 4) { deleteMembers($context['id_member']); redirectexit(); } // Actually update this member now, as it guarantees the unapproved count can't get corrupted. approveMembers(array('members' => array($context['id_member']), 'activated_status' => $user_profile[$memID]['is_activated'])); // Log what we did? logAction('approve_member', array('member' => $memID), 'admin'); // If we are doing approval, update the stats for the member just in case. if (in_array($user_profile[$memID]['is_activated'], array(3, 4, 13, 14))) { updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > 1 ? $modSettings['unapprovedMembers'] - 1 : 0)); } // Make sure we update the stats too. updateStats('member', false); } // Leave it be... redirectexit('action=profile;u=' . $memID . ';area=summary'); }
function DeleteInstall() { global $txt, $HTTP_SESSION_VARS, $incontext; global $current_smf_version, $sourcedir, $forum_version, $modSettings, $user_info, $db_type; $incontext['page_title'] = $txt['congratulations']; $incontext['sub_template'] = 'delete_install'; $incontext['continue'] = 0; require dirname(__FILE__) . '/Settings.php'; load_database(); chdir(dirname(__FILE__)); require_once $sourcedir . '/Errors.php'; require_once $sourcedir . '/lib/Subs.php'; require_once $sourcedir . '/CommonAPI.php'; require_once $sourcedir . '/Load.php'; require_once $sourcedir . '/Security.php'; require_once $sourcedir . '/lib/Subs-Auth.php'; // Bring a warning over. if (!empty($incontext['account_existed'])) { $incontext['warning'] = $incontext['account_existed']; } smf_db_query(' SET NAMES utf8', array()); // As track stats is by default enabled let's add some activity. smf_db_insert('ignore', '{db_prefix}log_activity', array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'), array(strftime('%Y-%m-%d', time()), 1, 1, !empty($incontext['member_id']) ? 1 : 0), array('date')); // Automatically log them in ;) if (isset($incontext['member_id']) && isset($incontext['member_salt'])) { setLoginCookie(3153600 * 60, $incontext['member_id'], sha1(sha1(strtolower($_POST['username']) . $_POST['password1']) . $incontext['member_salt'])); } $result = smf_db_query(' SELECT value FROM {db_prefix}settings WHERE variable = {string:db_sessions}', array('db_sessions' => 'databaseSession_enable', 'db_error_skip' => true)); if (mysql_num_rows($result) != 0) { list($db_sessions) = mysql_fetch_row($result); } mysql_free_result($result); if (empty($db_sessions)) { if (@version_compare(PHP_VERSION, '4.2.0') == -1) { $HTTP_SESSION_VARS['php_412_bugfix'] = true; } $_SESSION['admin_time'] = time(); } else { $_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211); smf_db_insert('replace', '{db_prefix}sessions', array('session_id' => 'string', 'last_update' => 'int', 'data' => 'string'), array(session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';'), array('session_id')); } // We're going to want our lovely $modSettings now. $request = smf_db_query(' SELECT variable, value FROM {db_prefix}settings', array('db_error_skip' => true)); // Only proceed if we can load the data. if ($request) { while ($row = mysql_fetch_row($request)) { $modSettings[$row[0]] = $row[1]; } mysql_free_result($request); } updateStats('member'); updateStats('message'); updateStats('topic'); $request = smf_db_query(' SELECT id_msg FROM {db_prefix}messages WHERE id_msg = 1 AND modified_time = 0 LIMIT 1', array('db_error_skip' => true)); if (mysql_num_rows($request) > 0) { updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject'])); } mysql_free_result($request); // Now is the perfect time to fetch the SM files. require_once $sourcedir . '/ScheduledTasks.php'; // Sanity check that they loaded earlier! if (isset($modSettings['recycle_board'])) { $forum_version = $current_smf_version; // The variable is usually defined in index.php so lets just use our variable to do it for us. scheduled_fetchSMfiles(); // Now go get those files! // We've just installed! $user_info['ip'] = $_SERVER['REMOTE_ADDR']; $user_info['id'] = isset($incontext['member_id']) ? $incontext['member_id'] : 0; logAction('install', array('version' => $forum_version), 'admin'); } // Check if we need some stupid MySQL fix. $server_version = smf_db_get_version(); if ($db_type == 'mysql' && in_array(substr($server_version, 0, 6), array('5.0.50', '5.0.51'))) { updateSettings(array('db_mysql_group_by_fix' => '1')); } // Some final context for the template. $incontext['dir_still_writable'] = is_writable(dirname(__FILE__)) && substr(__FILE__, 1, 2) != ':\\'; $incontext['probably_delete_install'] = isset($_SESSION['installer_temp_ftp']) || is_writable(dirname(__FILE__)) || is_writable(__FILE__); return false; }
/** * Allows for moderation from the message index. * @todo refactor this... */ function QuickModeration() { global $sourcedir, $board, $user_info, $modSettings, $smcFunc, $context; // Check the session = get or post. checkSession('request'); // Lets go straight to the restore area. if (isset($_REQUEST['qaction']) && $_REQUEST['qaction'] == 'restore' && !empty($_REQUEST['topics'])) { redirectexit('action=restoretopic;topics=' . implode(',', $_REQUEST['topics']) . ';' . $context['session_var'] . '=' . $context['session_id']); } if (isset($_SESSION['topicseen_cache'])) { $_SESSION['topicseen_cache'] = array(); } // This is going to be needed to send off the notifications and for updateLastMessages(). require_once $sourcedir . '/Subs-Post.php'; // Remember the last board they moved things to. if (isset($_REQUEST['move_to'])) { $_SESSION['move_to_topic'] = $_REQUEST['move_to']; } // Only a few possible actions. $possibleActions = array(); if (!empty($board)) { $boards_can = array('make_sticky' => allowedTo('make_sticky') ? array($board) : array(), 'move_any' => allowedTo('move_any') ? array($board) : array(), 'move_own' => allowedTo('move_own') ? array($board) : array(), 'remove_any' => allowedTo('remove_any') ? array($board) : array(), 'remove_own' => allowedTo('remove_own') ? array($board) : array(), 'lock_any' => allowedTo('lock_any') ? array($board) : array(), 'lock_own' => allowedTo('lock_own') ? array($board) : array(), 'merge_any' => allowedTo('merge_any') ? array($board) : array(), 'approve_posts' => allowedTo('approve_posts') ? array($board) : array()); $redirect_url = 'board=' . $board . '.' . $_REQUEST['start']; } else { /** * @todo Ugly. There's no getting around this, is there? * @todo Maybe just do this on the actions people want to use? */ $boards_can = boardsAllowedTo(array('make_sticky', 'move_any', 'move_own', 'remove_any', 'remove_own', 'lock_any', 'lock_own', 'merge_any', 'approve_posts'), true, false); $redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SESSION['old_url']) ? $_SESSION['old_url'] : ''); } if (!$user_info['is_guest']) { $possibleActions[] = 'markread'; } if (!empty($boards_can['make_sticky']) && !empty($modSettings['enableStickyTopics'])) { $possibleActions[] = 'sticky'; } if (!empty($boards_can['move_any']) || !empty($boards_can['move_own'])) { $possibleActions[] = 'move'; } if (!empty($boards_can['remove_any']) || !empty($boards_can['remove_own'])) { $possibleActions[] = 'remove'; } if (!empty($boards_can['lock_any']) || !empty($boards_can['lock_own'])) { $possibleActions[] = 'lock'; } if (!empty($boards_can['merge_any'])) { $possibleActions[] = 'merge'; } if (!empty($boards_can['approve_posts'])) { $possibleActions[] = 'approve'; } // Two methods: $_REQUEST['actions'] (id_topic => action), and $_REQUEST['topics'] and $_REQUEST['qaction']. // (if action is 'move', $_REQUEST['move_to'] or $_REQUEST['move_tos'][$topic] is used.) if (!empty($_REQUEST['topics'])) { // If the action isn't valid, just quit now. if (empty($_REQUEST['qaction']) || !in_array($_REQUEST['qaction'], $possibleActions)) { redirectexit($redirect_url); } // Merge requires all topics as one parameter and can be done at once. if ($_REQUEST['qaction'] == 'merge') { // Merge requires at least two topics. if (empty($_REQUEST['topics']) || count($_REQUEST['topics']) < 2) { redirectexit($redirect_url); } require_once $sourcedir . '/SplitTopics.php'; return MergeExecute($_REQUEST['topics']); } // Just convert to the other method, to make it easier. foreach ($_REQUEST['topics'] as $topic) { $_REQUEST['actions'][(int) $topic] = $_REQUEST['qaction']; } } // Weird... how'd you get here? if (empty($_REQUEST['actions'])) { redirectexit($redirect_url); } // Validate each action. $temp = array(); foreach ($_REQUEST['actions'] as $topic => $action) { if (in_array($action, $possibleActions)) { $temp[(int) $topic] = $action; } } $_REQUEST['actions'] = $temp; if (!empty($_REQUEST['actions'])) { // Find all topics... $request = $smcFunc['db_query']('', ' SELECT id_topic, id_member_started, id_board, locked, approved, unapproved_posts FROM {db_prefix}topics WHERE id_topic IN ({array_int:action_topic_ids}) LIMIT ' . count($_REQUEST['actions']), array('action_topic_ids' => array_keys($_REQUEST['actions']))); while ($row = $smcFunc['db_fetch_assoc']($request)) { if (!empty($board)) { if ($row['id_board'] != $board || $modSettings['postmod_active'] && !$row['approved'] && !allowedTo('approve_posts')) { unset($_REQUEST['actions'][$row['id_topic']]); } } else { // Don't allow them to act on unapproved posts they can't see... if ($modSettings['postmod_active'] && !$row['approved'] && !in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts'])) { unset($_REQUEST['actions'][$row['id_topic']]); } elseif ($_REQUEST['actions'][$row['id_topic']] == 'sticky' && !in_array(0, $boards_can['make_sticky']) && !in_array($row['id_board'], $boards_can['make_sticky'])) { unset($_REQUEST['actions'][$row['id_topic']]); } elseif ($_REQUEST['actions'][$row['id_topic']] == 'move' && !in_array(0, $boards_can['move_any']) && !in_array($row['id_board'], $boards_can['move_any']) && ($row['id_member_started'] != $user_info['id'] || !in_array(0, $boards_can['move_own']) && !in_array($row['id_board'], $boards_can['move_own']))) { unset($_REQUEST['actions'][$row['id_topic']]); } elseif ($_REQUEST['actions'][$row['id_topic']] == 'remove' && !in_array(0, $boards_can['remove_any']) && !in_array($row['id_board'], $boards_can['remove_any']) && ($row['id_member_started'] != $user_info['id'] || !in_array(0, $boards_can['remove_own']) && !in_array($row['id_board'], $boards_can['remove_own']))) { unset($_REQUEST['actions'][$row['id_topic']]); } elseif ($_REQUEST['actions'][$row['id_topic']] == 'lock' && !in_array(0, $boards_can['lock_any']) && !in_array($row['id_board'], $boards_can['lock_any']) && ($row['id_member_started'] != $user_info['id'] || $row['locked'] == 1 || !in_array(0, $boards_can['lock_own']) && !in_array($row['id_board'], $boards_can['lock_own']))) { unset($_REQUEST['actions'][$row['id_topic']]); } elseif ($_REQUEST['actions'][$row['id_topic']] == 'approve' && (!$row['unapproved_posts'] || !in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts']))) { unset($_REQUEST['actions'][$row['id_topic']]); } } } $smcFunc['db_free_result']($request); } $stickyCache = array(); $moveCache = array(0 => array(), 1 => array()); $removeCache = array(); $lockCache = array(); $markCache = array(); $approveCache = array(); // Separate the actions. foreach ($_REQUEST['actions'] as $topic => $action) { $topic = (int) $topic; if ($action == 'markread') { $markCache[] = $topic; } elseif ($action == 'sticky') { $stickyCache[] = $topic; } elseif ($action == 'move') { require_once $sourcedir . '/MoveTopic.php'; moveTopicConcurrence(); // $moveCache[0] is the topic, $moveCache[1] is the board to move to. $moveCache[1][$topic] = (int) (isset($_REQUEST['move_tos'][$topic]) ? $_REQUEST['move_tos'][$topic] : $_REQUEST['move_to']); if (empty($moveCache[1][$topic])) { continue; } $moveCache[0][] = $topic; } elseif ($action == 'remove') { $removeCache[] = $topic; } elseif ($action == 'lock') { $lockCache[] = $topic; } elseif ($action == 'approve') { $approveCache[] = $topic; } } if (empty($board)) { $affectedBoards = array(); } else { $affectedBoards = array($board => array(0, 0)); } // Do all the stickies... if (!empty($stickyCache)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET is_sticky = CASE WHEN is_sticky = {int:is_sticky} THEN 0 ELSE 1 END WHERE id_topic IN ({array_int:sticky_topic_ids})', array('sticky_topic_ids' => $stickyCache, 'is_sticky' => 1)); // Get the board IDs and Sticky status $request = $smcFunc['db_query']('', ' SELECT id_topic, id_board, is_sticky FROM {db_prefix}topics WHERE id_topic IN ({array_int:sticky_topic_ids}) LIMIT ' . count($stickyCache), array('sticky_topic_ids' => $stickyCache)); $stickyCacheBoards = array(); $stickyCacheStatus = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $stickyCacheBoards[$row['id_topic']] = $row['id_board']; $stickyCacheStatus[$row['id_topic']] = empty($row['is_sticky']); } $smcFunc['db_free_result']($request); } // Move sucka! (this is, by the by, probably the most complicated part....) if (!empty($moveCache[0])) { // I know - I just KNOW you're trying to beat the system. Too bad for you... we CHECK :P. $request = $smcFunc['db_query']('', ' SELECT t.id_topic, t.id_board, b.count_posts FROM {db_prefix}topics AS t LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board) WHERE t.id_topic IN ({array_int:move_topic_ids})' . (!empty($board) && !allowedTo('move_any') ? ' AND t.id_member_started = {int:current_member}' : '') . ' LIMIT ' . count($moveCache[0]), array('current_member' => $user_info['id'], 'move_topic_ids' => $moveCache[0])); $moveTos = array(); $moveCache2 = array(); $countPosts = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $to = $moveCache[1][$row['id_topic']]; if (empty($to)) { continue; } // Does this topic's board count the posts or not? $countPosts[$row['id_topic']] = empty($row['count_posts']); if (!isset($moveTos[$to])) { $moveTos[$to] = array(); } $moveTos[$to][] = $row['id_topic']; // For reporting... $moveCache2[] = array($row['id_topic'], $row['id_board'], $to); } $smcFunc['db_free_result']($request); $moveCache = $moveCache2; require_once $sourcedir . '/MoveTopic.php'; // Do the actual moves... foreach ($moveTos as $to => $topics) { moveTopics($topics, $to); } // Does the post counts need to be updated? if (!empty($moveTos)) { $topicRecounts = array(); $request = $smcFunc['db_query']('', ' SELECT id_board, count_posts FROM {db_prefix}boards WHERE id_board IN ({array_int:move_boards})', array('move_boards' => array_keys($moveTos))); while ($row = $smcFunc['db_fetch_assoc']($request)) { $cp = empty($row['count_posts']); // Go through all the topics that are being moved to this board. foreach ($moveTos[$row['id_board']] as $topic) { // If both boards have the same value for post counting then no adjustment needs to be made. if ($countPosts[$topic] != $cp) { // If the board being moved to does count the posts then the other one doesn't so add to their post count. $topicRecounts[$topic] = $cp ? '+' : '-'; } } } $smcFunc['db_free_result']($request); if (!empty($topicRecounts)) { $members = array(); // Get all the members who have posted in the moved topics. $request = $smcFunc['db_query']('', ' SELECT id_member, id_topic FROM {db_prefix}messages WHERE id_topic IN ({array_int:moved_topic_ids})', array('moved_topic_ids' => array_keys($topicRecounts))); while ($row = $smcFunc['db_fetch_assoc']($request)) { if (!isset($members[$row['id_member']])) { $members[$row['id_member']] = 0; } if ($topicRecounts[$row['id_topic']] === '+') { $members[$row['id_member']] += 1; } else { $members[$row['id_member']] -= 1; } } $smcFunc['db_free_result']($request); // And now update them member's post counts foreach ($members as $id_member => $post_adj) { updateMemberData($id_member, array('posts' => 'posts + ' . $post_adj)); } } } } // Now delete the topics... if (!empty($removeCache)) { // They can only delete their own topics. (we wouldn't be here if they couldn't do that..) $result = $smcFunc['db_query']('', ' SELECT id_topic, id_board FROM {db_prefix}topics WHERE id_topic IN ({array_int:removed_topic_ids})' . (!empty($board) && !allowedTo('remove_any') ? ' AND id_member_started = {int:current_member}' : '') . ' LIMIT ' . count($removeCache), array('current_member' => $user_info['id'], 'removed_topic_ids' => $removeCache)); $removeCache = array(); $removeCacheBoards = array(); while ($row = $smcFunc['db_fetch_assoc']($result)) { $removeCache[] = $row['id_topic']; $removeCacheBoards[$row['id_topic']] = $row['id_board']; } $smcFunc['db_free_result']($result); // Maybe *none* were their own topics. if (!empty($removeCache)) { // Gotta send the notifications *first*! foreach ($removeCache as $topic) { // Only log the topic ID if it's not in the recycle board. logAction('remove', array(empty($modSettings['recycle_enable']) || $modSettings['recycle_board'] != $removeCacheBoards[$topic] ? 'topic' : 'old_topic_id' => $topic, 'board' => $removeCacheBoards[$topic])); sendNotifications($topic, 'remove'); } require_once $sourcedir . '/RemoveTopic.php'; removeTopics($removeCache); } } // Approve the topics... if (!empty($approveCache)) { // We need unapproved topic ids and their authors! $request = $smcFunc['db_query']('', ' SELECT id_topic, id_member_started FROM {db_prefix}topics WHERE id_topic IN ({array_int:approve_topic_ids}) AND approved = {int:not_approved} LIMIT ' . count($approveCache), array('approve_topic_ids' => $approveCache, 'not_approved' => 0)); $approveCache = array(); $approveCacheMembers = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $approveCache[] = $row['id_topic']; $approveCacheMembers[$row['id_topic']] = $row['id_member_started']; } $smcFunc['db_free_result']($request); // Any topics to approve? if (!empty($approveCache)) { // Handle the approval part... approveTopics($approveCache); // Time for some logging! foreach ($approveCache as $topic) { logAction('approve_topic', array('topic' => $topic, 'member' => $approveCacheMembers[$topic])); } } } // And (almost) lastly, lock the topics... if (!empty($lockCache)) { $lockStatus = array(); // Gotta make sure they CAN lock/unlock these topics... if (!empty($board) && !allowedTo('lock_any')) { // Make sure they started the topic AND it isn't already locked by someone with higher priv's. $result = $smcFunc['db_query']('', ' SELECT id_topic, locked, id_board FROM {db_prefix}topics WHERE id_topic IN ({array_int:locked_topic_ids}) AND id_member_started = {int:current_member} AND locked IN (2, 0) LIMIT ' . count($lockCache), array('current_member' => $user_info['id'], 'locked_topic_ids' => $lockCache)); $lockCache = array(); $lockCacheBoards = array(); while ($row = $smcFunc['db_fetch_assoc']($result)) { $lockCache[] = $row['id_topic']; $lockCacheBoards[$row['id_topic']] = $row['id_board']; $lockStatus[$row['id_topic']] = empty($row['locked']); } $smcFunc['db_free_result']($result); } else { $result = $smcFunc['db_query']('', ' SELECT id_topic, locked, id_board FROM {db_prefix}topics WHERE id_topic IN ({array_int:locked_topic_ids}) LIMIT ' . count($lockCache), array('locked_topic_ids' => $lockCache)); $lockCacheBoards = array(); while ($row = $smcFunc['db_fetch_assoc']($result)) { $lockStatus[$row['id_topic']] = empty($row['locked']); $lockCacheBoards[$row['id_topic']] = $row['id_board']; } $smcFunc['db_free_result']($result); } // It could just be that *none* were their own topics... if (!empty($lockCache)) { // Alternate the locked value. $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET locked = CASE WHEN locked = {int:is_locked} THEN ' . (allowedTo('lock_any') ? '1' : '2') . ' ELSE 0 END WHERE id_topic IN ({array_int:locked_topic_ids})', array('locked_topic_ids' => $lockCache, 'is_locked' => 0)); } } if (!empty($markCache)) { $markArray = array(); foreach ($markCache as $topic) { $markArray[] = array($modSettings['maxMsgID'], $user_info['id'], $topic); } $smcFunc['db_insert']('replace', '{db_prefix}log_topics', array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int'), $markArray, array('id_member', 'id_topic')); } foreach ($moveCache as $topic) { // Didn't actually move anything! if (!isset($topic[0])) { break; } logAction('move', array('topic' => $topic[0], 'board_from' => $topic[1], 'board_to' => $topic[2])); sendNotifications($topic[0], 'move'); } foreach ($lockCache as $topic) { logAction($lockStatus[$topic] ? 'lock' : 'unlock', array('topic' => $topic, 'board' => $lockCacheBoards[$topic])); sendNotifications($topic, $lockStatus[$topic] ? 'lock' : 'unlock'); } foreach ($stickyCache as $topic) { logAction($stickyCacheStatus[$topic] ? 'unsticky' : 'sticky', array('topic' => $topic, 'board' => $stickyCacheBoards[$topic])); sendNotifications($topic, 'sticky'); } updateStats('topic'); updateStats('message'); updateSettings(array('calendar_updated' => time())); if (!empty($affectedBoards)) { updateLastMessages(array_keys($affectedBoards)); } redirectexit($redirect_url); }
function updateMemberData($members, $data) { global $modSettings, $user_info, $smcFunc; $parameters = array(); if (is_array($members)) { $condition = 'id_member IN ({array_int:members})'; $parameters['members'] = $members; } elseif ($members === null) { $condition = '1=1'; } else { $condition = 'id_member = {int:member}'; $parameters['member'] = $members; } if (!empty($modSettings['integrate_change_member_data'])) { // Only a few member variables are really interesting for integration. $integration_vars = array('member_name', 'real_name', 'email_address', 'id_group', 'gender', 'birthdate', 'website_title', 'website_url', 'location', 'hide_email', 'time_format', 'time_offset', 'avatar', 'lngfile'); $vars_to_integrate = array_intersect($integration_vars, array_keys($data)); // Only proceed if there are any variables left to call the integration function. if (count($vars_to_integrate) != 0) { // Fetch a list of member_names if necessary if (!is_array($members) && $members === $user_info['id'] || is_array($members) && count($members) == 1 && in_array($user_info['id'], $members)) { $member_names = array($user_info['username']); } else { $member_names = array(); $request = $smcFunc['db_query']('', ' SELECT member_name FROM {db_prefix}members WHERE ' . $condition, $parameters); while ($row = $smcFunc['db_fetch_assoc']($request)) { $member_names[] = $row['member_name']; } $smcFunc['db_free_result']($request); } if (!empty($member_names)) { foreach ($vars_to_integrate as $var) { call_integration_hook('integrate_change_member_data', array($member_names, $var, $data[$var])); } } } } // Everything is assumed to be a string unless it's in the below. $knownInts = array('date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages', 'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'pm_receive_from', 'karma_good', 'karma_bad', 'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types', 'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning'); $knownFloats = array('time_offset'); $setString = ''; foreach ($data as $var => $val) { $type = 'string'; if (in_array($var, $knownInts)) { $type = 'int'; } elseif (in_array($var, $knownFloats)) { $type = 'float'; } elseif ($var == 'birthdate') { $type = 'date'; } // Doing an increment? if ($type == 'int' && ($val === '+' || $val === '-')) { $val = $var . ' ' . $val . ' 1'; $type = 'raw'; } // Ensure posts, instant_messages, and unread_messages don't overflow or underflow. if (in_array($var, array('posts', 'instant_messages', 'unread_messages'))) { if (preg_match('~^' . $var . ' (\\+ |- |\\+ -)([\\d]+)~', $val, $match)) { if ($match[1] != '+ ') { $val = 'CASE WHEN ' . $var . ' <= ' . abs($match[2]) . ' THEN 0 ELSE ' . $val . ' END'; } $type = 'raw'; } } $setString .= ' ' . $var . ' = {' . $type . ':p_' . $var . '},'; $parameters['p_' . $var] = $val; } $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET' . substr($setString, 0, -1) . ' WHERE ' . $condition, $parameters); updateStats('postgroups', $members, array_keys($data)); // Clear any caching? if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !empty($members)) { if (!is_array($members)) { $members = array($members); } foreach ($members as $member) { if ($modSettings['cache_enable'] >= 3) { cache_put_data('member_data-profile-' . $member, null, 120); cache_put_data('member_data-normal-' . $member, null, 120); cache_put_data('member_data-minimal-' . $member, null, 120); } cache_put_data('user_settings-' . $member, null, 60); } } }
/** * Modifying a post... * * @package Posts * @param mixed[] $msgOptions * @param mixed[] $topicOptions * @param mixed[] $posterOptions */ function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions) { global $user_info, $modSettings; $db = database(); $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null; $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null; $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null; // This is longer than it has to be, but makes it so we only set/change what we have to. $messages_columns = array(); if (isset($posterOptions['name'])) { $messages_columns['poster_name'] = $posterOptions['name']; } if (isset($posterOptions['email'])) { $messages_columns['poster_email'] = $posterOptions['email']; } if (isset($msgOptions['icon'])) { $messages_columns['icon'] = $msgOptions['icon']; } if (isset($msgOptions['subject'])) { $messages_columns['subject'] = $msgOptions['subject']; } if (isset($msgOptions['body'])) { $messages_columns['body'] = $msgOptions['body']; // using a custom search index, then lets get the old message so we can update our index as needed if (!empty($modSettings['search_custom_index_config'])) { require_once SUBSDIR . '/Messages.subs.php'; $message = basicMessageInfo($msgOptions['id'], true); $msgOptions['old_body'] = $message['body']; } } if (!empty($msgOptions['modify_time'])) { $messages_columns['modified_time'] = $msgOptions['modify_time']; $messages_columns['modified_name'] = $msgOptions['modify_name']; $messages_columns['id_msg_modified'] = $modSettings['maxMsgID']; } if (isset($msgOptions['smileys_enabled'])) { $messages_columns['smileys_enabled'] = empty($msgOptions['smileys_enabled']) ? 0 : 1; } // Which columns need to be ints? $messageInts = array('modified_time', 'id_msg_modified', 'smileys_enabled'); $update_parameters = array('id_msg' => $msgOptions['id']); call_integration_hook('integrate_before_modify_post', array(&$messages_columns, &$update_parameters, &$msgOptions, &$topicOptions, &$posterOptions, &$messageInts)); foreach ($messages_columns as $var => $val) { $messages_columns[$var] = $var . ' = {' . (in_array($var, $messageInts) ? 'int' : 'string') . ':var_' . $var . '}'; $update_parameters['var_' . $var] = $val; } // Nothing to do? if (empty($messages_columns)) { return true; } // Change the post. $db->query('', ' UPDATE {db_prefix}messages SET ' . implode(', ', $messages_columns) . ' WHERE id_msg = {int:id_msg}', $update_parameters); // Lock and or sticky the post. if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null) { $db->query('', ' UPDATE {db_prefix}topics SET is_sticky = {raw:is_sticky}, locked = {raw:locked}, id_poll = {raw:id_poll} WHERE id_topic = {int:id_topic}', array('is_sticky' => $topicOptions['sticky_mode'] === null ? 'is_sticky' : (int) $topicOptions['sticky_mode'], 'locked' => $topicOptions['lock_mode'] === null ? 'locked' : (int) $topicOptions['lock_mode'], 'id_poll' => $topicOptions['poll'] === null ? 'id_poll' : (int) $topicOptions['poll'], 'id_topic' => $topicOptions['id'])); } // Mark the edited post as read. if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest']) { // Since it's likely they *read* it before editing, let's try an UPDATE first. $db->query('', ' UPDATE {db_prefix}log_topics SET id_msg = {int:id_msg} WHERE id_member = {int:current_member} AND id_topic = {int:id_topic}', array('current_member' => $user_info['id'], 'id_msg' => $modSettings['maxMsgID'], 'id_topic' => $topicOptions['id'])); $flag = $db->affected_rows() != 0; if (empty($flag)) { require_once SUBSDIR . '/Topic.subs.php'; markTopicsRead(array($user_info['id'], $topicOptions['id'], $modSettings['maxMsgID'], 0), false); } } // If there's a custom search index, it needs to be modified... require_once SUBSDIR . '/Search.subs.php'; $searchAPI = findSearchAPI(); if (is_callable(array($searchAPI, 'postModified'))) { $searchAPI->postModified($msgOptions, $topicOptions, $posterOptions); } if (isset($msgOptions['subject'])) { // Only update the subject if this was the first message in the topic. $request = $db->query('', ' SELECT id_topic FROM {db_prefix}topics WHERE id_first_msg = {int:id_first_msg} LIMIT 1', array('id_first_msg' => $msgOptions['id'])); if ($db->num_rows($request) == 1) { updateStats('subject', $topicOptions['id'], $msgOptions['subject']); } $db->free_result($request); } // Finally, if we are setting the approved state we need to do much more work :( if ($modSettings['postmod_active'] && isset($msgOptions['approved'])) { approvePosts($msgOptions['id'], $msgOptions['approved']); } return true; }
/** * Final step, clean up and a complete message! */ function action_deleteInstall() { global $txt, $incontext, $db_character_set; global $current_version, $databases, $forum_version, $modSettings, $user_info, $db_type; // A few items we will load in from settings and make avaialble. global $boardurl, $db_prefix, $cookiename, $mbname, $language; $incontext['page_title'] = $txt['congratulations']; $incontext['sub_template'] = 'delete_install'; $incontext['continue'] = 0; require dirname(__FILE__) . '/Settings.php'; if (!defined('ELK')) { define('ELK', 1); } definePaths(); $db = load_database(); if (!defined('SUBSDIR')) { define('SUBSDIR', dirname(__FILE__) . '/sources/subs'); } chdir(dirname(__FILE__)); require_once SOURCEDIR . '/Errors.php'; require_once SOURCEDIR . '/Logging.php'; require_once SOURCEDIR . '/Subs.php'; require_once SOURCEDIR . '/Load.php'; require_once SUBSDIR . '/Cache.subs.php'; require_once SOURCEDIR . '/Security.php'; require_once SUBSDIR . '/Auth.subs.php'; require_once SUBSDIR . '/Util.class.php'; // Bring a warning over. if (!empty($incontext['account_existed'])) { $incontext['warning'] = $incontext['account_existed']; } if (!empty($db_character_set) && !empty($databases[$db_type]['utf8_support'])) { $db->query('', ' SET NAMES {raw:db_character_set}', array('db_character_set' => $db_character_set, 'db_error_skip' => true)); } // As track stats is by default enabled let's add some activity. $db->insert('ignore', '{db_prefix}log_activity', array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'), array(strftime('%Y-%m-%d', time()), 1, 1, !empty($incontext['member_id']) ? 1 : 0), array('date')); // We're going to want our lovely $modSettings now. $request = $db->query('', ' SELECT variable, value FROM {db_prefix}settings', array('db_error_skip' => true)); // Only proceed if we can load the data. if ($request) { while ($row = $db->fetch_row($request)) { $modSettings[$row[0]] = $row[1]; } $db->free_result($request); } // Automatically log them in ;) if (isset($incontext['member_id']) && isset($incontext['member_salt'])) { setLoginCookie(3153600 * 60, $incontext['member_id'], hash('sha256', $incontext['passwd'] . $incontext['member_salt'])); } $result = $db->query('', ' SELECT value FROM {db_prefix}settings WHERE variable = {string:db_sessions}', array('db_sessions' => 'databaseSession_enable', 'db_error_skip' => true)); if ($db->num_rows($result) != 0) { list($db_sessions) = $db->fetch_row($result); } $db->free_result($result); if (empty($db_sessions)) { $_SESSION['admin_time'] = time(); } else { $_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211); $db->insert('replace', '{db_prefix}sessions', array('session_id' => 'string', 'last_update' => 'int', 'data' => 'string'), array(session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';'), array('session_id')); } updateStats('member'); updateStats('message'); updateStats('topic'); $request = $db->query('', ' SELECT id_msg FROM {db_prefix}messages WHERE id_msg = 1 AND modified_time = 0 LIMIT 1', array('db_error_skip' => true)); if ($db->num_rows($request) > 0) { updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject'])); } $db->free_result($request); // Now is the perfect time to fetch remote files. require_once SUBSDIR . '/ScheduledTask.class.php'; // Sanity check that they loaded earlier! if (isset($modSettings['recycle_board'])) { // The variable is usually defined in index.php so lets just use our variable to do it for us. $forum_version = $current_version; // Now go get those files! $task = new Scheduled_Task(); $task->fetchFiles(); // We've just installed! $user_info['ip'] = $_SERVER['REMOTE_ADDR']; $user_info['id'] = isset($incontext['member_id']) ? $incontext['member_id'] : 0; logAction('install', array('version' => $forum_version), 'admin'); } // Check if we need some stupid MySQL fix. $server_version = $db->db_server_info(); if ($db_type == 'mysql' && in_array(substr($server_version, 0, 6), array('5.0.50', '5.0.51'))) { updateSettings(array('db_mysql_group_by_fix' => '1')); } // Some final context for the template. $incontext['dir_still_writable'] = is_writable(dirname(__FILE__)) && substr(__FILE__, 1, 2) != ':\\'; $incontext['probably_delete_install'] = isset($_SESSION['installer_temp_ftp']) || is_writable(dirname(__FILE__)) || is_writable(__FILE__); return false; }
function RepairBoards() { global $db_prefix, $txt, $scripturl, $db_connection, $sc, $context, $sourcedir; global $salvageCatID, $salvageBoardID; isAllowedTo('admin_forum'); // Set up the administrative bar thing. adminIndex('maintain_forum'); // Print out the top of the webpage. $context['page_title'] = $txt[610]; $context['sub_template'] = 'rawdata'; // Start displaying errors without fixing them. if (isset($_GET['fixErrors'])) { checkSession('get'); } // Giant if/else. The first displays the forum errors if a variable is not set and asks // if you would like to continue, the other fixes the errors. if (!isset($_GET['fixErrors'])) { $context['repair_errors'] = array(); $to_fix = findForumErrors(); if (!empty($to_fix)) { $_SESSION['repairboards_to_fix'] = $to_fix; $_SESSION['repairboards_to_fix2'] = null; if (empty($context['repair_errors'])) { $context['repair_errors'][] = '???'; } } $context['raw_data'] = ' <table width="100%" border="0" cellspacing="0" cellpadding="4" class="tborder"> <tr class="titlebg"> <td>' . $txt['smf73'] . '</td> </tr><tr> <td class="windowbg">'; if (!empty($to_fix)) { $context['raw_data'] .= ' ' . $txt['smf74'] . ':<br /> ' . implode(' <br />', $context['repair_errors']) . '<br /> <br /> ' . $txt['smf85'] . '<br /> <b><a href="' . $scripturl . '?action=repairboards;fixErrors;sesc=' . $sc . '">' . $txt[163] . '</a> - <a href="' . $scripturl . '?action=maintain">' . $txt[164] . '</a></b>'; } else { $context['raw_data'] .= ' ' . $txt['maintain_no_errors'] . '<br /> <br /> <a href="' . $scripturl . '?action=maintain">' . $txt['maintain_return'] . '</a>'; } $context['raw_data'] .= ' </td> </tr> </table>'; } else { $to_fix = isset($_SESSION['repairboards_to_fix']) ? $_SESSION['repairboards_to_fix'] : array(); require_once $sourcedir . '/Subs-Boards.php'; // Get the MySQL version for future reference. $mysql_version = mysql_get_server_info($db_connection); if (empty($to_fix) || in_array('zero_ids', $to_fix)) { // We don't allow 0's in the IDs... db_query("\n\t\t\t\tUPDATE {$db_prefix}topics\n\t\t\t\tSET ID_TOPIC = NULL\n\t\t\t\tWHERE ID_TOPIC = 0", __FILE__, __LINE__); db_query("\n\t\t\t\tUPDATE {$db_prefix}messages\n\t\t\t\tSET ID_MSG = NULL\n\t\t\t\tWHERE ID_MSG = 0", __FILE__, __LINE__); } // Remove all topics that have zero messages in the messages table. if (empty($to_fix) || in_array('missing_messages', $to_fix)) { $resultTopic = db_query("\n\t\t\t\tSELECT t.ID_TOPIC, COUNT(m.ID_MSG) AS numMsg\n\t\t\t\tFROM {$db_prefix}topics AS t\n\t\t\t\t\tLEFT JOIN {$db_prefix}messages AS m ON (m.ID_TOPIC = t.ID_TOPIC)\n\t\t\t\tGROUP BY t.ID_TOPIC\n\t\t\t\tHAVING numMsg = 0", __FILE__, __LINE__); if (mysql_num_rows($resultTopic) > 0) { $stupidTopics = array(); while ($topicArray = mysql_fetch_assoc($resultTopic)) { $stupidTopics[] = $topicArray['ID_TOPIC']; } db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}topics\n\t\t\t\t\tWHERE ID_TOPIC IN (" . implode(',', $stupidTopics) . ') LIMIT ' . count($stupidTopics), __FILE__, __LINE__); db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_topics\n\t\t\t\t\tWHERE ID_TOPIC IN (" . implode(',', $stupidTopics) . ')', __FILE__, __LINE__); } mysql_free_result($resultTopic); } // Fix all messages that have a topic ID that cannot be found in the topics table. if (empty($to_fix) || in_array('missing_topics', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT\n\t\t\t\t\tm.ID_BOARD, m.ID_TOPIC, MIN(m.ID_MSG) AS myID_FIRST_MSG, MAX(m.ID_MSG) AS myID_LAST_MSG,\n\t\t\t\t\tCOUNT(*) - 1 AS myNumReplies\n\t\t\t\tFROM {$db_prefix}messages AS m\n\t\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = m.ID_TOPIC)\n\t\t\t\tWHERE t.ID_TOPIC IS NULL\n\t\t\t\tGROUP BY m.ID_TOPIC", __FILE__, __LINE__); while ($row = mysql_fetch_assoc($result)) { // Only if we don't have a reasonable idea of where to put it. if ($row['ID_BOARD'] == 0) { createSalvageArea(); $row['ID_BOARD'] = $salvageBoardID; } $memberStartedID = getMsgMemberID($row['myID_FIRST_MSG']); $memberUpdatedID = getMsgMemberID($row['myID_LAST_MSG']); db_query("\n\t\t\t\t\tINSERT INTO {$db_prefix}topics\n\t\t\t\t\t\t(ID_BOARD, ID_MEMBER_STARTED, ID_MEMBER_UPDATED, ID_FIRST_MSG, ID_LAST_MSG, numReplies)\n\t\t\t\t\tVALUES ({$row['ID_BOARD']}, {$memberStartedID}, {$memberUpdatedID},\n\t\t\t\t\t\t{$row['myID_FIRST_MSG']}, {$row['myID_LAST_MSG']}, {$row['myNumReplies']})", __FILE__, __LINE__); $newTopicID = db_insert_id(); db_query("\n\t\t\t\t\tUPDATE {$db_prefix}messages\n\t\t\t\t\tSET ID_TOPIC = {$newTopicID}, ID_BOARD = {$row['ID_BOARD']}\n\t\t\t\t\tWHERE ID_TOPIC = {$row['ID_TOPIC']}", __FILE__, __LINE__); } mysql_free_result($result); } // Fix all ID_FIRST_MSG, ID_LAST_MSG and numReplies in the topic table. if (empty($to_fix) || in_array('stats_topics', $to_fix)) { $resultTopic = db_query("\n\t\t\t\tSELECT\n\t\t\t\t\tt.ID_TOPIC, MIN(m.ID_MSG) AS myID_FIRST_MSG, t.ID_FIRST_MSG,\n\t\t\t\t\tMAX(m.ID_MSG) AS myID_LAST_MSG, t.ID_LAST_MSG, COUNT(m.ID_MSG) - 1 AS myNumReplies,\n\t\t\t\t\tt.numReplies\n\t\t\t\tFROM {$db_prefix}topics AS t\n\t\t\t\t\tLEFT JOIN {$db_prefix}messages AS m ON (m.ID_TOPIC = t.ID_TOPIC)\n\t\t\t\tGROUP BY t.ID_TOPIC\n\t\t\t\tHAVING ID_FIRST_MSG != myID_FIRST_MSG OR ID_LAST_MSG != myID_LAST_MSG OR numReplies != myNumReplies", __FILE__, __LINE__); while ($topicArray = mysql_fetch_assoc($resultTopic)) { $memberStartedID = getMsgMemberID($topicArray['myID_FIRST_MSG']); $memberUpdatedID = getMsgMemberID($topicArray['myID_LAST_MSG']); db_query("\n\t\t\t\t\tUPDATE {$db_prefix}topics\n\t\t\t\t\tSET ID_FIRST_MSG = '{$topicArray['myID_FIRST_MSG']}',\n\t\t\t\t\t\tID_MEMBER_STARTED = '{$memberStartedID}', ID_LAST_MSG = '{$topicArray['myID_LAST_MSG']}',\n\t\t\t\t\t\tID_MEMBER_UPDATED = '{$memberUpdatedID}', numReplies = '{$topicArray['myNumReplies']}'\n\t\t\t\t\tWHERE ID_TOPIC = {$topicArray['ID_TOPIC']}\n\t\t\t\t\tLIMIT 1", __FILE__, __LINE__); } mysql_free_result($resultTopic); } // Fix all topics that have a board ID that cannot be found in the boards table. if (empty($to_fix) || in_array('missing_boards', $to_fix)) { $resultTopics = db_query("\n\t\t\t\tSELECT t.ID_BOARD, COUNT(*) AS myNumTopics, COUNT(m.ID_MSG) AS myNumPosts\n\t\t\t\tFROM {$db_prefix}topics AS t\n\t\t\t\t\tLEFT JOIN {$db_prefix}boards AS b ON (b.ID_BOARD = t.ID_BOARD)\n\t\t\t\t\tLEFT JOIN {$db_prefix}messages AS m ON (m.ID_TOPIC = t.ID_TOPIC)\n\t\t\t\tWHERE b.ID_BOARD IS NULL\n\t\t\t\tGROUP BY t.ID_BOARD", __FILE__, __LINE__); if (mysql_num_rows($resultTopics) > 0) { createSalvageArea(); } while ($topicArray = mysql_fetch_assoc($resultTopics)) { db_query("\n\t\t\t\t\tINSERT INTO {$db_prefix}boards\n\t\t\t\t\t\t(ID_CAT, name, description, numTopics, numPosts, memberGroups)\n\t\t\t\t\tVALUES ({$salvageCatID}, 'Salvaged board', '', {$topicArray['myNumTopics']}, {$topicArray['myNumPosts']}, '1')", __FILE__, __LINE__); $newBoardID = db_insert_id(); db_query("\n\t\t\t\t\tUPDATE {$db_prefix}topics\n\t\t\t\t\tSET ID_BOARD = {$newBoardID}\n\t\t\t\t\tWHERE ID_BOARD = {$topicArray['ID_BOARD']}", __FILE__, __LINE__); db_query("\n\t\t\t\t\tUPDATE {$db_prefix}messages\n\t\t\t\t\tSET ID_BOARD = {$newBoardID}\n\t\t\t\t\tWHERE ID_BOARD = {$topicArray['ID_BOARD']}", __FILE__, __LINE__); } mysql_free_result($resultTopics); } // Fix all boards that have a cat ID that cannot be found in the cats table. if (empty($to_fix) || in_array('missing_categories', $to_fix)) { $resultBoards = db_query("\n\t\t\t\tSELECT b.ID_CAT\n\t\t\t\tFROM {$db_prefix}boards AS b\n\t\t\t\t\tLEFT JOIN {$db_prefix}categories AS c ON (c.ID_CAT = b.ID_CAT)\n\t\t\t\tWHERE c.ID_CAT IS NULL\n\t\t\t\tGROUP BY b.ID_CAT", __FILE__, __LINE__); if (mysql_num_rows($resultBoards) > 0) { createSalvageArea(); } while ($boardArray = mysql_fetch_assoc($resultBoards)) { db_query("\n\t\t\t\t\tUPDATE {$db_prefix}boards\n\t\t\t\t\tSET ID_CAT = {$salvageCatID}\n\t\t\t\t\tWHERE ID_CAT = {$boardArray['ID_CAT']}", __FILE__, __LINE__); } mysql_free_result($resultBoards); } // Last step-make sure all non-guest posters still exist. if (empty($to_fix) || in_array('missing_posters', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT m.ID_MSG\n\t\t\t\tFROM {$db_prefix}messages AS m\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = m.ID_MEMBER)\n\t\t\t\tWHERE m.ID_MEMBER != 0\n\t\t\t\t\tAND mem.ID_MEMBER IS NULL", __FILE__, __LINE__); if (mysql_num_rows($result) > 0) { $guestMessages = array(); while ($row = mysql_fetch_assoc($result)) { $guestMessages[] = $row['ID_MSG']; } db_query("\n\t\t\t\t\tUPDATE {$db_prefix}messages\n\t\t\t\t\tSET ID_MEMBER = 0\n\t\t\t\t\tWHERE ID_MSG IN (" . implode(',', $guestMessages) . ') LIMIT ' . count($guestMessages), __FILE__, __LINE__); } mysql_free_result($result); } // Fix all boards that have a parent ID that cannot be found in the boards table. if (empty($to_fix) || in_array('missing_parents', $to_fix)) { $resultParents = db_query("\n\t\t\t\tSELECT b.ID_PARENT\n\t\t\t\tFROM {$db_prefix}boards AS b\n\t\t\t\t\tLEFT JOIN {$db_prefix}boards AS p ON (p.ID_BOARD = b.ID_PARENT)\n\t\t\t\tWHERE b.ID_PARENT != 0\n\t\t\t\t\tAND (p.ID_BOARD IS NULL OR p.ID_BOARD = b.ID_BOARD)\n\t\t\t\tGROUP BY b.ID_PARENT", __FILE__, __LINE__); if (mysql_num_rows($resultParents) > 0) { createSalvageArea(); } while ($parentArray = mysql_fetch_assoc($resultParents)) { db_query("\n\t\t\t\t\tUPDATE {$db_prefix}boards\n\t\t\t\t\tSET ID_PARENT = {$salvageBoardID}, ID_CAT = {$salvageCatID}, childLevel = 1\n\t\t\t\t\tWHERE ID_PARENT = {$parentArray['ID_PARENT']}", __FILE__, __LINE__); } mysql_free_result($resultParents); } if (empty($to_fix) || in_array('missing_polls', $to_fix)) { if (version_compare($mysql_version, '4.0.4') >= 0) { db_query("\n\t\t\t\t\tUPDATE {$db_prefix}topics AS t\n\t\t\t\t\t\tLEFT JOIN {$db_prefix}polls AS p ON (p.ID_POLL = t.ID_POLL)\n\t\t\t\t\tSET t.ID_POLL = 0\n\t\t\t\t\tWHERE t.ID_POLL != 0\n\t\t\t\t\t\tAND p.ID_POLL IS NULL", __FILE__, __LINE__); } else { $resultPolls = db_query("\n\t\t\t\t\tSELECT t.ID_POLL\n\t\t\t\t\tFROM {$db_prefix}topics AS t\n\t\t\t\t\t\tLEFT JOIN {$db_prefix}polls AS p ON (p.ID_POLL = t.ID_POLL)\n\t\t\t\t\tWHERE t.ID_POLL != 0\n\t\t\t\t\t\tAND p.ID_POLL IS NULL\n\t\t\t\t\tGROUP BY t.ID_POLL", __FILE__, __LINE__); $polls = array(); while ($rowPolls = mysql_fetch_assoc($resultPolls)) { $polls[] = $rowPolls['ID_POLL']; } mysql_free_result($resultPolls); if (!empty($polls)) { db_query("\n\t\t\t\t\t\tUPDATE {$db_prefix}topics\n\t\t\t\t\t\tSET ID_POLL = 0\n\t\t\t\t\t\tWHERE ID_POLL IN (" . implode(', ', $polls) . ")\n\t\t\t\t\t\tLIMIT " . count($polls), __FILE__, __LINE__); } } } if (empty($to_fix) || in_array('missing_calendar_topics', $to_fix)) { if (version_compare($mysql_version, '4.0.4') >= 0) { db_query("\n\t\t\t\t\tUPDATE {$db_prefix}calendar AS cal\n\t\t\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = cal.ID_TOPIC)\n\t\t\t\t\tSET cal.ID_BOARD = 0, cal.ID_TOPIC = 0\n\t\t\t\t\tWHERE cal.ID_TOPIC != 0\n\t\t\t\t\t\tAND t.ID_TOPIC IS NULL", __FILE__, __LINE__); } else { $resultEvents = db_query("\n\t\t\t\t\tSELECT cal.ID_TOPIC\n\t\t\t\t\tFROM {$db_prefix}calendar AS cal\n\t\t\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = cal.ID_TOPIC)\n\t\t\t\t\tWHERE cal.ID_TOPIC != 0\n\t\t\t\t\t\tAND t.ID_TOPIC IS NULL\n\t\t\t\t\tGROUP BY cal.ID_TOPIC", __FILE__, __LINE__); $events = array(); while ($rowEvents = mysql_fetch_assoc($resultEvents)) { $events[] = $rowEvents['ID_TOPIC']; } mysql_free_result($resultEvents); if (!empty($events)) { db_query("\n\t\t\t\t\t\tUPDATE {$db_prefix}calendar\n\t\t\t\t\t\tSET ID_TOPIC = 0, ID_BOARD = 0\n\t\t\t\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $events) . ")\n\t\t\t\t\t\tLIMIT " . count($events), __FILE__, __LINE__); } } } if (empty($to_fix) || in_array('missing_log_topics', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lt.ID_TOPIC\n\t\t\t\tFROM {$db_prefix}log_topics AS lt\n\t\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = lt.ID_TOPIC)\n\t\t\t\tWHERE t.ID_TOPIC IS NULL\n\t\t\t\tGROUP BY lt.ID_TOPIC", __FILE__, __LINE__); $topics = array(); while ($row = mysql_fetch_assoc($result)) { $topics[] = $row['ID_TOPIC']; } mysql_free_result($result); if (!empty($topics)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_topics\n\t\t\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $topics) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_topics_members', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lt.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}log_topics AS lt\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = lt.ID_MEMBER)\n\t\t\t\tWHERE mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY lt.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_topics\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_boards', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lb.ID_BOARD\n\t\t\t\tFROM {$db_prefix}log_boards AS lb\n\t\t\t\t\tLEFT JOIN {$db_prefix}boards AS b ON (b.ID_BOARD = lb.ID_BOARD)\n\t\t\t\tWHERE b.ID_BOARD IS NULL\n\t\t\t\tGROUP BY lb.ID_BOARD", __FILE__, __LINE__); $boards = array(); while ($row = mysql_fetch_assoc($result)) { $boards[] = $row['ID_BOARD']; } mysql_free_result($result); if (!empty($boards)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_boards\n\t\t\t\t\tWHERE ID_BOARD IN (" . implode(', ', $boards) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_boards_members', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lb.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}log_boards AS lb\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = lb.ID_MEMBER)\n\t\t\t\tWHERE mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY lb.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_boards\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_mark_read', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lmr.ID_BOARD\n\t\t\t\tFROM {$db_prefix}log_mark_read AS lmr\n\t\t\t\t\tLEFT JOIN {$db_prefix}boards AS b ON (b.ID_BOARD = lmr.ID_BOARD)\n\t\t\t\tWHERE b.ID_BOARD IS NULL\n\t\t\t\tGROUP BY lmr.ID_BOARD", __FILE__, __LINE__); $boards = array(); while ($row = mysql_fetch_assoc($result)) { $boards[] = $row['ID_BOARD']; } mysql_free_result($result); if (!empty($boards)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_mark_read\n\t\t\t\t\tWHERE ID_BOARD IN (" . implode(', ', $boards) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_mark_read_members', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lmr.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}log_mark_read AS lmr\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = lmr.ID_MEMBER)\n\t\t\t\tWHERE mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY lmr.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_mark_read\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_pms', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT pmr.ID_PM\n\t\t\t\tFROM {$db_prefix}pm_recipients AS pmr\n\t\t\t\t\tLEFT JOIN {$db_prefix}personal_messages AS pm ON (pm.ID_PM = pmr.ID_PM)\n\t\t\t\tWHERE pm.ID_PM IS NULL\n\t\t\t\tGROUP BY pmr.ID_PM", __FILE__, __LINE__); $pms = array(); while ($row = mysql_fetch_assoc($result)) { $pms[] = $row['ID_PM']; } mysql_free_result($result); if (!empty($pms)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}pm_recipients\n\t\t\t\t\tWHERE ID_PM IN (" . implode(', ', $pms) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_recipients', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT pmr.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}pm_recipients AS pmr\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = pmr.ID_MEMBER)\n\t\t\t\tWHERE pmr.ID_MEMBER != 0\n\t\t\t\t\tAND mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY pmr.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}pm_recipients\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_senders', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT pm.ID_PM\n\t\t\t\tFROM {$db_prefix}personal_messages AS pm\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = pm.ID_MEMBER_FROM)\n\t\t\t\tWHERE pm.ID_MEMBER_FROM != 0\n\t\t\t\t\tAND mem.ID_MEMBER IS NULL", __FILE__, __LINE__); if (mysql_num_rows($result) > 0) { $guestMessages = array(); while ($row = mysql_fetch_assoc($result)) { $guestMessages[] = $row['ID_PM']; } db_query("\n\t\t\t\t\tUPDATE {$db_prefix}personal_messages\n\t\t\t\t\tSET ID_MEMBER_FROM = 0\n\t\t\t\t\tWHERE ID_PM IN (" . implode(',', $guestMessages) . ') LIMIT ' . count($guestMessages), __FILE__, __LINE__); } mysql_free_result($result); } if (empty($to_fix) || in_array('missing_notify_members', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT ln.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}log_notify AS ln\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = ln.ID_MEMBER)\n\t\t\t\tWHERE mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY ln.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_notify\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_cached_subject', $to_fix)) { $request = db_query("\n\t\t\t\tSELECT t.ID_TOPIC, m.subject\n\t\t\t\tFROM ({$db_prefix}topics AS t, {$db_prefix}messages AS m)\n\t\t\t\t\tLEFT JOIN {$db_prefix}log_search_subjects AS lss ON (lss.ID_TOPIC = t.ID_TOPIC)\n\t\t\t\tWHERE m.ID_MSG = t.ID_FIRST_MSG\n\t\t\t\t\tAND lss.ID_TOPIC IS NULL", __FILE__, __LINE__); $insertRows = array(); while ($row = mysql_fetch_assoc($request)) { foreach (text2words($row['subject']) as $word) { $insertRows[] = "'{$word}', {$row['ID_TOPIC']}"; } if (count($insertRows) > 500) { db_query("\n\t\t\t\t\t\tINSERT IGNORE INTO {$db_prefix}log_search_subjects\n\t\t\t\t\t\t\t(word, ID_TOPIC)\n\t\t\t\t\t\tVALUES (" . implode('), (', $insertRows) . ")", __FILE__, __LINE__); $insertRows = array(); } } mysql_free_result($request); if (!empty($insertRows)) { db_query("\n\t\t\t\t\tINSERT IGNORE INTO {$db_prefix}log_search_subjects\n\t\t\t\t\t\t(word, ID_TOPIC)\n\t\t\t\t\tVALUES (" . implode('), (', $insertRows) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_topic_for_cache', $to_fix)) { $request = db_query("\n\t\t\t\tSELECT lss.ID_TOPIC\n\t\t\t\tFROM {$db_prefix}log_search_subjects AS lss\n\t\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = lss.ID_TOPIC)\n\t\t\t\tWHERE t.ID_TOPIC IS NULL\n\t\t\t\tGROUP BY lss.ID_TOPIC", __FILE__, __LINE__); $deleteTopics = array(); while ($row = mysql_fetch_assoc($request)) { $deleteTopics[] = $row['ID_TOPIC']; } mysql_free_result($request); if (!empty($deleteTopics)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_search_subjects\n\t\t\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleteTopics) . ')', __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_member_vote', $to_fix)) { $result = db_query("\n\t\t\t\tSELECT lp.ID_MEMBER\n\t\t\t\tFROM {$db_prefix}log_polls AS lp\n\t\t\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = lp.ID_MEMBER)\n\t\t\t\tWHERE mem.ID_MEMBER IS NULL\n\t\t\t\tGROUP BY lp.ID_MEMBER", __FILE__, __LINE__); $members = array(); while ($row = mysql_fetch_assoc($result)) { $members[] = $row['ID_MEMBER']; } mysql_free_result($result); if (!empty($members)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_polls\n\t\t\t\t\tWHERE ID_MEMBER IN (" . implode(', ', $members) . ")", __FILE__, __LINE__); } } if (empty($to_fix) || in_array('missing_log_poll_vote', $to_fix)) { $request = db_query("\n\t\t\t\tSELECT lp.ID_POLL\n\t\t\t\tFROM {$db_prefix}log_polls AS lp\n\t\t\t\t\tLEFT JOIN {$db_prefix}polls AS p ON (p.ID_POLL = lp.ID_POLL)\n\t\t\t\tWHERE p.ID_POLL IS NULL\n\t\t\t\tGROUP BY lp.ID_POLL", __FILE__, __LINE__); $polls = array(); while ($row = mysql_fetch_assoc($request)) { $polls[] = $row['ID_POLL']; } mysql_free_result($request); if (!empty($polls)) { db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}log_polls\n\t\t\t\t\tWHERE ID_POLL IN (" . implode(', ', $polls) . ")", __FILE__, __LINE__); } } updateStats('message'); updateStats('topic'); updateStats('calendar'); $context['raw_data'] = ' <table width="100%" border="0" cellspacing="0" cellpadding="4" class="tborder"> <tr class="titlebg"> <td>' . $txt['smf86'] . '</td> </tr><tr> <td class="windowbg"> ' . $txt['smf92'] . '<br /> <br /> <a href="' . $scripturl . '?action=maintain">' . $txt['maintain_return'] . '</a> </td> </tr> </table>'; $_SESSION['repairboards_to_fix'] = null; $_SESSION['repairboards_to_fix2'] = null; } }
/** * eventScoresUpdate - Re-calculate the scores and players of an event */ function eventScoresUpdate($current_match) { global $sql; global $time; //echo "dbg: current_match $current_match<br>"; $numMatchsPerUpdate = 10; $q = "SELECT " . TBL_MATCHS . ".*" . " FROM " . TBL_MATCHS . " WHERE (" . TBL_MATCHS . ".Event = '" . $this->fields['EventID'] . "')" . " AND (" . TBL_MATCHS . ".Status = 'active')" . " ORDER BY TimeReported"; $result = $sql->db_Query($q); $num_matches = mysql_numrows($result); if ($current_match > $num_matches) { switch ($this->fields['Type']) { case "One Player Ladder": updateStats($this->fields['EventID'], $time, true); break; case "Team Ladder": updateStats($this->fields['EventID'], $time, true); updateTeamStats($this->fields['EventID'], $time, true); break; case "Clan Ladder": updateTeamStats($this->fields['EventID'], $time, true); break; case "One Player Tournament": case "Clan Tournament": break; default: } echo "Done."; echo '<META HTTP-EQUIV="Refresh" Content="0; URL=eventmanage.php?eventid=' . $this->fields['EventID'] . '">'; } else { $next_match = 1; if ($current_match == 0) { // Reset players stats $this->resetPlayers(); $this->resetTeams(); switch ($this->fields['Type']) { case "One Player Ladder": updateStats($this->fields['EventID'], $this->fields['StartDateTime'], false); break; case "Team Ladder": updateStats($this->fields['EventID'], $this->fields['StartDateTime'], false); updateTeamStats($this->fields['EventID'], $this->fields['StartDateTime'], false); break; case "Clan Ladder": updateTeamStats($this->fields['EventID'], $this->fields['getStartDateTime'], false); break; case "One Player Tournament": case "Clan Tournament": break; default: } } else { if (ob_get_level() == 0) { ob_start(); } // Output a 'waiting message' echo str_pad('Please wait while this task completes... ', 4096) . "<br />\n"; // Update matchs scores for ($j = $current_match - 1; $j < min($current_match + $numMatchsPerUpdate - 1, $num_matches); $j++) { set_time_limit(10); $next_match = $j + 2; $match_id = mysql_result($result, $j, TBL_MATCHS . ".MatchID"); $match = new Match($match_id); $time_reported = mysql_result($result, $j, TBL_MATCHS . ".TimeReported"); //echo "dbg: match: $match_id<br>"; //echo "dbg: etype: $this->fields['Type']<br>"; $match->match_scores_update(); switch ($this->fields['Type']) { case "One Player Ladder": $match->match_players_update(); updateStats($this->fields['EventID'], $this->fields['StartDateTime'], false); break; case "Team Ladder": $match->match_players_update(); updateStats($this->fields['EventID'], $this->fields['StartDateTime'], false); updateTeamStats($this->fields['EventID'], $this->fields['StartDateTime'], false); break; case "Clan Ladder": $match->match_teams_update(); updateTeamStats($this->fields['EventID'], $this->fields['StartDateTime'], false); break; case "One Player Tournament": case "Clan Tournament": break; default: } //echo 'match '.$j.': '.$match_id.'<br>'; //echo '<div class="percents">match '.$j.': '.$match_id.'</div>'; echo '<div class="percents">' . number_format(100 * ($j + 1) / $num_matches, 0, '.', '') . '% complete</div>'; echo str_pad('', 4096) . "\n"; ob_flush(); flush(); } } echo '<form name="updateform" action="' . e_PLUGIN . 'ebattles/eventprocess.php?eventid=' . $this->fields['EventID'] . '" method="post">'; echo '<input type="hidden" name="match" value="' . $next_match . '"/>'; echo '<input type="hidden" name="eventupdatescores" value="1"/>'; echo '</form>'; echo '<script language="javascript">document.updateform.submit()</script>'; ob_end_flush(); } exit; }
function registerMember(&$regOptions, $return_errors = false) { global $scripturl, $txt, $modSettings, $context, $sourcedir; global $user_info, $options, $settings, $smcFunc; loadLanguage('Login'); // We'll need some external functions. require_once $sourcedir . '/lib/Subs-Auth.php'; require_once $sourcedir . '/lib/Subs-Post.php'; // Put any errors in here. $reg_errors = array(); // Registration from the admin center, let them sweat a little more. if ($regOptions['interface'] == 'admin') { is_not_guest(); isAllowedTo('moderate_forum'); } elseif ($regOptions['interface'] == 'guest') { // You cannot register twice... if (empty($user_info['is_guest'])) { redirectexit(); } // Make sure they didn't just register with this session. if (!empty($_SESSION['just_registered']) && empty($modSettings['disableRegisterCheck'])) { fatal_lang_error('register_only_once', false); } } // What method of authorization are we going to use? if (empty($regOptions['auth_method']) || !in_array($regOptions['auth_method'], array('password', 'openid'))) { if (!empty($regOptions['openid'])) { $regOptions['auth_method'] = 'openid'; } else { $regOptions['auth_method'] = 'password'; } } // No name?! How can you register with no name? if (empty($regOptions['username'])) { $reg_errors[] = array('lang', 'need_username'); } // Spaces and other odd characters are evil... $regOptions['username'] = preg_replace('~[\\t\\n\\r\\x0B\\0' . ($context['server']['complex_preg_chars'] ? '\\x{A0}' : " ") . ']+~u', ' ', $regOptions['username']); // Don't use too long a name. if (commonAPI::strlen($regOptions['username']) > 25) { $reg_errors[] = array('lang', 'error_long_name'); } // Only these characters are permitted. if (preg_match('~[<>&"\'=\\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $regOptions['username'])) != 0 || $regOptions['username'] == '_' || $regOptions['username'] == '|' || strpos($regOptions['username'], '[code') !== false || strpos($regOptions['username'], '[/code') !== false) { $reg_errors[] = array('lang', 'error_invalid_characters_username'); } if (commonAPI::strtolower($regOptions['username']) === commonAPI::strtolower($txt['guest_title'])) { $reg_errors[] = array('lang', 'username_reserved', 'general', array($txt['guest_title'])); } // !!! Separate the sprintf? if (empty($regOptions['email']) || preg_match('~^[0-9A-Za-z=_+\\-/][0-9A-Za-z=_\'+\\-/\\.]*@[\\w\\-]+(\\.[\\w\\-]+)*(\\.[\\w]{2,6})$~', $regOptions['email']) === 0 || strlen($regOptions['email']) > 255) { $reg_errors[] = array('done', sprintf($txt['valid_email_needed'], commonAPI::htmlspecialchars($regOptions['username']))); } if (!empty($regOptions['check_reserved_name']) && isReservedName($regOptions['username'], 0, false)) { if ($regOptions['password'] == 'chocolate cake') { $reg_errors[] = array('done', 'Sorry, I don\'t take bribes... you\'ll need to come up with a different name.'); } $reg_errors[] = array('done', '(' . htmlspecialchars($regOptions['username']) . ') ' . $txt['name_in_use']); } // Generate a validation code if it's supposed to be emailed. $validation_code = ''; if ($regOptions['require'] == 'activation') { $validation_code = generateValidationCode(); } // If you haven't put in a password generate one. if ($regOptions['interface'] == 'admin' && $regOptions['password'] == '' && $regOptions['auth_method'] == 'password') { mt_srand(time() + 1277); $regOptions['password'] = generateValidationCode(); $regOptions['password_check'] = $regOptions['password']; } elseif ($regOptions['password'] != $regOptions['password_check'] && $regOptions['auth_method'] == 'password') { $reg_errors[] = array('lang', 'passwords_dont_match'); } // That's kind of easy to guess... if ($regOptions['password'] == '') { if ($regOptions['auth_method'] == 'password') { $reg_errors[] = array('lang', 'no_password'); } else { $regOptions['password'] = sha1(mt_rand()); } } // Now perform hard password validation as required. if (!empty($regOptions['check_password_strength'])) { $passwordError = validatePassword($regOptions['password'], $regOptions['username'], array($regOptions['email'])); // Password isn't legal? if ($passwordError != null) { $reg_errors[] = array('lang', 'profile_error_password_' . $passwordError); } } // If they are using an OpenID that hasn't been verified yet error out. // !!! Change this so they can register without having to attempt a login first if ($regOptions['auth_method'] == 'openid' && (empty($_SESSION['openid']['verified']) || $_SESSION['openid']['openid_uri'] != $regOptions['openid'])) { $reg_errors[] = array('lang', 'openid_not_verified'); } // You may not be allowed to register this email. if (!empty($regOptions['check_email_ban'])) { isBannedEmail($regOptions['email'], 'cannot_register', $txt['ban_register_prohibited']); } // Check if the email address is in use. $request = smf_db_query(' SELECT id_member FROM {db_prefix}members WHERE email_address = {string:email_address} OR email_address = {string:username} LIMIT 1', array('email_address' => $regOptions['email'], 'username' => $regOptions['username'])); // !!! Separate the sprintf? if (mysql_num_rows($request) != 0) { $reg_errors[] = array('lang', 'email_in_use', false, array(htmlspecialchars($regOptions['email']))); } mysql_free_result($request); // If we found any errors we need to do something about it right away! foreach ($reg_errors as $key => $error) { /* Note for each error: 0 = 'lang' if it's an index, 'done' if it's clear text. 1 = The text/index. 2 = Whether to log. 3 = sprintf data if necessary. */ if ($error[0] == 'lang') { loadLanguage('Errors'); } $message = $error[0] == 'lang' ? empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], $error[3]) : $error[1]; // What to do, what to do, what to do. if ($return_errors) { if (!empty($error[2])) { log_error($message, $error[2]); } $reg_errors[$key] = $message; } else { fatal_error($message, empty($error[2]) ? false : $error[2]); } } // If there's any errors left return them at once! if (!empty($reg_errors)) { return $reg_errors; } $reservedVars = array('actual_theme_url', 'actual_images_url', 'base_theme_dir', 'base_theme_url', 'default_images_url', 'default_theme_dir', 'default_theme_url', 'default_template', 'images_url', 'number_recent_posts', 'smiley_sets_default', 'theme_dir', 'theme_id', 'theme_layers', 'theme_templates', 'theme_url'); // Can't change reserved vars. if (isset($regOptions['theme_vars']) && array_intersect($regOptions['theme_vars'], $reservedVars) != array()) { fatal_lang_error('no_theme'); } // Some of these might be overwritten. (the lower ones that are in the arrays below.) $regOptions['register_vars'] = array('member_name' => $regOptions['username'], 'email_address' => $regOptions['email'], 'passwd' => sha1(strtolower($regOptions['username']) . $regOptions['password']), 'password_salt' => substr(md5(mt_rand()), 0, 4), 'posts' => 0, 'date_registered' => time(), 'member_ip' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $user_info['ip'], 'member_ip2' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $_SERVER['BAN_CHECK_IP'], 'validation_code' => $validation_code, 'real_name' => $regOptions['username'], 'personal_text' => $modSettings['default_personal_text'], 'pm_email_notify' => 1, 'id_theme' => 0, 'id_post_group' => 4, 'lngfile' => '', 'buddy_list' => '', 'pm_ignore_list' => '', 'message_labels' => '', 'location' => '', 'time_format' => '', 'signature' => '', 'avatar' => '', 'usertitle' => '', 'secret_question' => '', 'secret_answer' => '', 'additional_groups' => '', 'ignore_boards' => '', 'smiley_set' => '', 'openid_uri' => !empty($regOptions['openid']) ? $regOptions['openid'] : ''); // Setup the activation status on this new account so it is correct - firstly is it an under age account? if ($regOptions['require'] == 'coppa') { $regOptions['register_vars']['is_activated'] = 5; // !!! This should be changed. To what should be it be changed?? $regOptions['register_vars']['validation_code'] = ''; } elseif ($regOptions['require'] == 'nothing') { $regOptions['register_vars']['is_activated'] = 1; } elseif ($regOptions['require'] == 'activation') { $regOptions['register_vars']['is_activated'] = 0; } else { $regOptions['register_vars']['is_activated'] = 3; } if (isset($regOptions['memberGroup'])) { // Make sure the id_group will be valid, if this is an administator. $regOptions['register_vars']['id_group'] = $regOptions['memberGroup'] == 1 && !allowedTo('admin_forum') ? 0 : $regOptions['memberGroup']; // Check if this group is assignable. $unassignableGroups = array(-1, 3); $request = smf_db_query(' SELECT id_group FROM {db_prefix}membergroups WHERE min_posts != {int:min_posts}' . (allowedTo('admin_forum') ? '' : ' OR group_type = {int:is_protected}'), array('min_posts' => -1, 'is_protected' => 1)); while ($row = mysql_fetch_assoc($request)) { $unassignableGroups[] = $row['id_group']; } mysql_free_result($request); if (in_array($regOptions['register_vars']['id_group'], $unassignableGroups)) { $regOptions['register_vars']['id_group'] = 0; } } // Integrate optional member settings to be set. if (!empty($regOptions['extra_register_vars'])) { foreach ($regOptions['extra_register_vars'] as $var => $value) { $regOptions['register_vars'][$var] = $value; } } // Integrate optional user theme options to be set. $theme_vars = array(); if (!empty($regOptions['theme_vars'])) { foreach ($regOptions['theme_vars'] as $var => $value) { $theme_vars[$var] = $value; } } // Call an optional function to validate the users' input. HookAPI::callHook('integrate_register', array(&$regOptions, &$theme_vars)); // Right, now let's prepare for insertion. $knownInts = array('date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages', 'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'karma_good', 'karma_bad', 'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types', 'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning'); $knownFloats = array('time_offset'); $column_names = array(); $values = array(); foreach ($regOptions['register_vars'] as $var => $val) { $type = 'string'; if (in_array($var, $knownInts)) { $type = 'int'; } elseif (in_array($var, $knownFloats)) { $type = 'float'; } elseif ($var == 'birthdate') { $type = 'date'; } $column_names[$var] = $type; $values[$var] = $val; } // Register them into the database. smf_db_insert('', '{db_prefix}members', $column_names, $values, array('id_member')); $memberID = smf_db_insert_id('{db_prefix}members', 'id_member'); // Update the number of members and latest member's info - and pass the name, but remove the 's. if ($regOptions['register_vars']['is_activated'] == 1) { updateStats('member', $memberID, $regOptions['register_vars']['real_name']); } else { updateStats('member'); } // Theme variables too? if (!empty($theme_vars)) { $inserts = array(); foreach ($theme_vars as $var => $val) { $inserts[] = array($memberID, $var, $val); } smf_db_insert('insert', '{db_prefix}themes', array('id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'), $inserts, array('id_member', 'variable')); } // If it's enabled, increase the registrations for today. trackStats(array('registers' => '+')); // Administrative registrations are a bit different... if ($regOptions['interface'] == 'admin') { if ($regOptions['require'] == 'activation') { $email_message = 'admin_register_activate'; } elseif (!empty($regOptions['send_welcome_email'])) { $email_message = 'admin_register_immediate'; } if (isset($email_message)) { $replacements = array('REALNAME' => $regOptions['register_vars']['real_name'], 'USERNAME' => $regOptions['username'], 'PASSWORD' => $regOptions['password'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder', 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code, 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID, 'ACTIVATIONCODE' => $validation_code); $emaildata = loadEmailTemplate($email_message, $replacements); sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); } // All admins are finished here. return $memberID; } // Can post straight away - welcome them to your fantastic community... if ($regOptions['require'] == 'nothing') { if (!empty($regOptions['send_welcome_email'])) { $replacements = array('REALNAME' => $regOptions['register_vars']['real_name'], 'USERNAME' => $regOptions['username'], 'PASSWORD' => $regOptions['password'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder', 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : ''); $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'immediate', $replacements); sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); } // Send admin their notification. adminNotify('standard', $memberID, $regOptions['username']); } elseif ($regOptions['require'] == 'activation' || $regOptions['require'] == 'coppa') { $replacements = array('REALNAME' => $regOptions['register_vars']['real_name'], 'USERNAME' => $regOptions['username'], 'PASSWORD' => $regOptions['password'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder', 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : ''); if ($regOptions['require'] == 'activation') { $replacements += array('ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code, 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID, 'ACTIVATIONCODE' => $validation_code); } else { $replacements += array('COPPALINK' => $scripturl . '?action=coppa;u=' . $memberID); } $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . ($regOptions['require'] == 'activation' ? 'activate' : 'coppa'), $replacements); sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); } else { $replacements = array('REALNAME' => $regOptions['register_vars']['real_name'], 'USERNAME' => $regOptions['username'], 'PASSWORD' => $regOptions['password'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder', 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : ''); $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'pending', $replacements); sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); // Admin gets informed here... adminNotify('approval', $memberID, $regOptions['username']); } // Okay, they're for sure registered... make sure the session is aware of this for security. (Just married :P!) $_SESSION['just_registered'] = 1; return $memberID; }
function AdminApprove() { global $txt, $context, $scripturl, $modSettings, $sourcedir, $language, $user_info, $smcFunc; // First, check our session. checkSession(); require_once $sourcedir . '/Subs-Post.php'; // We also need to the login languages here - for emails. loadLanguage('Login'); // Sort out where we are going... $browse_type = isset($_REQUEST['type']) ? $_REQUEST['type'] : (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1 ? 'activate' : 'approve'); $current_filter = (int) $_REQUEST['orig_filter']; // If we are applying a filter do just that - then redirect. if (isset($_REQUEST['filter']) && $_REQUEST['filter'] != $_REQUEST['orig_filter']) { redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $_REQUEST['filter'] . ';start=' . $_REQUEST['start']); } // Nothing to do? if (!isset($_POST['todoAction']) && !isset($_POST['time_passed'])) { redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); } // Are we dealing with members who have been waiting for > set amount of time? if (isset($_POST['time_passed'])) { $timeBefore = time() - 86400 * (int) $_POST['time_passed']; $condition = ' AND date_registered < {int:time_before}'; } else { $members = array(); foreach ($_POST['todoAction'] as $id) { $members[] = (int) $id; } $condition = ' AND id_member IN ({array_int:members})'; } // Get information on each of the members, things that are important to us, like email address... $request = $smcFunc['db_query']('', ' SELECT id_member, member_name, real_name, email_address, validation_code, lngfile FROM {db_prefix}members WHERE is_activated = {int:activated_status}' . $condition . ' ORDER BY lngfile', array('activated_status' => $current_filter, 'time_before' => empty($timeBefore) ? 0 : $timeBefore, 'members' => empty($members) ? array() : $members)); $member_count = $smcFunc['db_num_rows']($request); // If no results then just return! if ($member_count == 0) { redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); } $member_info = array(); $members = array(); // Fill the info array. while ($row = $smcFunc['db_fetch_assoc']($request)) { $members[] = $row['id_member']; $member_info[] = array('id' => $row['id_member'], 'username' => $row['member_name'], 'name' => $row['real_name'], 'email' => $row['email_address'], 'language' => empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'], 'code' => $row['validation_code']); } $smcFunc['db_free_result']($request); // Are we activating or approving the members? if ($_POST['todo'] == 'ok' || $_POST['todo'] == 'okemail') { // Approve/activate this member. $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET validation_code = {string:blank_string}, is_activated = {int:is_activated} WHERE is_activated = {int:activated_status}' . $condition, array('is_activated' => 1, 'time_before' => empty($timeBefore) ? 0 : $timeBefore, 'members' => empty($members) ? array() : $members, 'activated_status' => $current_filter, 'blank_string' => '')); // Do we have to let the integration code know about the activations? if (!empty($modSettings['integrate_activate'])) { foreach ($member_info as $member) { call_integration_hook('integrate_activate', array($member['username'])); } } // Check for email. if ($_POST['todo'] == 'okemail') { foreach ($member_info as $member) { $replacements = array('NAME' => $member['name'], 'USERNAME' => $member['username'], 'PROFILELINK' => $scripturl . '?action=profile;u=' . $member['id'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder'); $emaildata = loadEmailTemplate('admin_approve_accept', $replacements, $member['language']); sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); } } } elseif ($_POST['todo'] == 'require_activation') { require_once $sourcedir . '/Subs-Members.php'; // We have to do this for each member I'm afraid. foreach ($member_info as $member) { // Generate a random activation code. $validation_code = generateValidationCode(); // Set these members for activation - I know this includes two id_member checks but it's safer than bodging $condition ;). $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET validation_code = {string:validation_code}, is_activated = {int:not_activated} WHERE is_activated = {int:activated_status} ' . $condition . ' AND id_member = {int:selected_member}', array('not_activated' => 0, 'activated_status' => $current_filter, 'selected_member' => $member['id'], 'validation_code' => $validation_code, 'time_before' => empty($timeBefore) ? 0 : $timeBefore, 'members' => empty($members) ? array() : $members)); $replacements = array('USERNAME' => $member['name'], 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $member['id'] . ';code=' . $validation_code, 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $member['id'], 'ACTIVATIONCODE' => $validation_code); $emaildata = loadEmailTemplate('admin_approve_activation', $replacements, $member['language']); sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); } } elseif ($_POST['todo'] == 'reject' || $_POST['todo'] == 'rejectemail') { require_once $sourcedir . '/Subs-Members.php'; deleteMembers($members); // Send email telling them they aren't welcome? if ($_POST['todo'] == 'rejectemail') { foreach ($member_info as $member) { $replacements = array('USERNAME' => $member['name']); $emaildata = loadEmailTemplate('admin_approve_reject', $replacements, $member['language']); sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 1); } } } elseif ($_POST['todo'] == 'delete' || $_POST['todo'] == 'deleteemail') { require_once $sourcedir . '/Subs-Members.php'; deleteMembers($members); // Send email telling them they aren't welcome? if ($_POST['todo'] == 'deleteemail') { foreach ($member_info as $member) { $replacements = array('USERNAME' => $member['name']); $emaildata = loadEmailTemplate('admin_approve_delete', $replacements, $member['language']); sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 1); } } } elseif ($_POST['todo'] == 'remind') { foreach ($member_info as $member) { $replacements = array('USERNAME' => $member['name'], 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $member['id'] . ';code=' . $member['code'], 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $member['id'], 'ACTIVATIONCODE' => $member['code']); $emaildata = loadEmailTemplate('admin_approve_remind', $replacements, $member['language']); sendmail($member['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 1); } } // Back to the user's language! if (isset($current_language) && $current_language != $user_info['language']) { loadLanguage('index'); loadLanguage('ManageMembers'); } // Log what we did? if (!empty($modSettings['modlog_enabled']) && in_array($_POST['todo'], array('ok', 'okemail', 'require_activation', 'remind'))) { $log_action = $_POST['todo'] == 'remind' ? 'remind_member' : 'approve_member'; $log_inserts = array(); foreach ($member_info as $member) { $log_inserts[] = array(time(), 3, $user_info['id'], $user_info['ip'], $log_action, 0, 0, 0, serialize(array('member' => $member['id']))); } $smcFunc['db_insert']('', '{db_prefix}log_actions', array('log_time' => 'int', 'id_log' => 'int', 'id_member' => 'int', 'ip' => 'string-16', 'action' => 'string', 'id_board' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'extra' => 'string-65534'), $log_inserts, array('id_action')); } // Although updateStats *may* catch this, best to do it manually just in case (Doesn't always sort out unapprovedMembers). if (in_array($current_filter, array(3, 4))) { updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > $member_count ? $modSettings['unapprovedMembers'] - $member_count : 0)); } // Update the member's stats. (but, we know the member didn't change their name.) updateStats('member', false); // If they haven't been deleted, update the post group statistics on them... if (!in_array($_POST['todo'], array('delete', 'deleteemail', 'reject', 'rejectemail', 'remind'))) { updateStats('postgroups', $members); } redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); }
function Activate() { global $context, $txt, $modSettings, $scripturl, $sourcedir, $language; loadLanguage('Login'); //loadTemplate('Login'); if (empty($_REQUEST['u']) && empty($_POST['user'])) { if (empty($modSettings['registration_method']) || $modSettings['registration_method'] == 3) { fatal_lang_error('no_access', false); } $context['member_id'] = 0; EoS_Smarty::loadTemplate('generic_skeleton'); EoS_Smarty::getConfigInstance()->registerHookTemplate('generic_content_area', 'loginout/resend'); $context['page_title'] = $txt['invalid_activation_resend']; $context['can_activate'] = empty($modSettings['registration_method']) || $modSettings['registration_method'] == 1; $context['default_username'] = isset($_GET['user']) ? $_GET['user'] : ''; return; } // Get the code from the database... $request = smf_db_query(' SELECT id_member, validation_code, member_name, real_name, email_address, is_activated, passwd, lngfile FROM {db_prefix}members' . (empty($_REQUEST['u']) ? ' WHERE member_name = {string:email_address} OR email_address = {string:email_address}' : ' WHERE id_member = {int:id_member}') . ' LIMIT 1', array('id_member' => isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0, 'email_address' => isset($_POST['user']) ? $_POST['user'] : '')); // Does this user exist at all? if (mysql_num_rows($request) == 0) { EoS_Smarty::loadTemplate('generic_skeleton'); EoS_Smarty::getConfigInstance()->registerHookTemplate('generic_content_area', 'loginout/retry_activate'); $context['page_title'] = $txt['invalid_userid']; $context['member_id'] = 0; return; } $row = mysql_fetch_assoc($request); mysql_free_result($request); // Change their email address? (they probably tried a fake one first :P.) if (isset($_POST['new_email'], $_REQUEST['passwd']) && sha1(strtolower($row['member_name']) . $_REQUEST['passwd']) == $row['passwd']) { if (empty($modSettings['registration_method']) || $modSettings['registration_method'] == 3) { fatal_lang_error('no_access', false); } // !!! Separate the sprintf? if (preg_match('~^[0-9A-Za-z=_+\\-/][0-9A-Za-z=_\'+\\-/\\.]*@[\\w\\-]+(\\.[\\w\\-]+)*(\\.[\\w]{2,6})$~', $_POST['new_email']) == 0) { fatal_error(sprintf($txt['valid_email_needed'], htmlspecialchars($_POST['new_email'])), false); } // Make sure their email isn't banned. isBannedEmail($_POST['new_email'], 'cannot_register', $txt['ban_register_prohibited']); // Ummm... don't even dare try to take someone else's email!! $request = smf_db_query(' SELECT id_member FROM {db_prefix}members WHERE email_address = {string:email_address} LIMIT 1', array('email_address' => $_POST['new_email'])); // !!! Separate the sprintf? if (mysql_num_rows($request) != 0) { fatal_lang_error('email_in_use', false, array(htmlspecialchars($_POST['new_email']))); } mysql_free_result($request); updateMemberData($row['id_member'], array('email_address' => $_POST['new_email'])); $row['email_address'] = $_POST['new_email']; $email_change = true; } // Resend the password, but only if the account wasn't activated yet. if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'resend' && ($row['is_activated'] == 0 || $row['is_activated'] == 2) && (!isset($_REQUEST['code']) || $_REQUEST['code'] == '')) { require_once $sourcedir . '/lib/Subs-Post.php'; $replacements = array('REALNAME' => $row['real_name'], 'USERNAME' => $row['member_name'], 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $row['id_member'] . ';code=' . $row['validation_code'], 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $row['id_member'], 'ACTIVATIONCODE' => $row['validation_code'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder'); $emaildata = loadEmailTemplate('resend_activate_message', $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']); sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); $context['page_title'] = $txt['invalid_activation_resend']; // This will ensure we don't actually get an error message if it works! $context['error_title'] = ''; fatal_lang_error(!empty($email_change) ? 'change_email_success' : 'resend_email_success', false); } // Quit if this code is not right. if (empty($_REQUEST['code']) || $row['validation_code'] != $_REQUEST['code']) { if (!empty($row['is_activated'])) { fatal_lang_error('already_activated', false); } elseif ($row['validation_code'] == '') { loadLanguage('Profile'); fatal_error($txt['registration_not_approved'] . ' <a href="' . $scripturl . '?action=activate;user='******'member_name'] . '">' . $txt['here'] . '</a>.', false); } EoS_Smarty::loadTemplate('generic_skeleton'); EoS_Smarty::getConfigInstance()->registerHookTemplate('generic_content_area', 'loginout/retry_activate'); $context['page_title'] = $txt['invalid_activation_code']; $context['member_id'] = $row['id_member']; return; } // Let the integration know that they've been activated! HookAPI::callHook('integrate_activate', array($row['member_name'])); // Validation complete - update the database! updateMemberData($row['id_member'], array('is_activated' => 1, 'validation_code' => '')); // Also do a proper member stat re-evaluation. updateStats('member', false); if (!isset($_POST['new_email'])) { $actid = 0; require_once $sourcedir . '/lib/Subs-Post.php'; // add to the activity stream if ($modSettings['astream_active']) { require_once $sourcedir . '/lib/Subs-Activities.php'; $actid = aStreamAdd($row['id_member'], ACT_NEWMEMBER, array('member_name' => $row['member_name']), 0, 0, 0, $row['id_member']); } adminNotify('activation', $row['id_member'], $row['member_name'], $actid, ACT_NEWMEMBER); } EoS_Smarty::loadTemplate('generic_skeleton'); EoS_Smarty::getConfigInstance()->registerHookTemplate('generic_content_area', 'loginout/login'); $context += array('page_title' => $txt['registration_successful'], 'sub_template' => 'login', 'default_username' => $row['member_name'], 'default_password' => '', 'never_expire' => false, 'description' => $txt['activate_success']); }
<?php $timeStart = microtime(true); session_start(); ob_start(); if (empty($_SESSION)) { exit(header("Location: ../../index.php")); } require_once $_SESSION['File_Root'] . '/Kernel/Include.php'; require_once $_SESSION['File_Root'] . '/HTML/Header.php'; require_once 'Functions/SQL.php'; redirectToLogin($accountID, $linkRoot); redirectToBattle($verifyBattle, $linkRoot); $inventoryID = htmlspecialchars(addslashes($_POST['inventoryID'])); $itemID = htmlspecialchars(addslashes($_POST['itemID'])); $parchment = newItem($bdd, $itemID); $parchmentHP = $parchment->getHP(); $parchmentMP = $parchment->getMP(); $parchmentStrength = $parchment->getStrength(); $parchmentMagic = $parchment->getMagic(); $parchmentAgility = $parchment->getAgility(); $parchmentDefense = $parchment->getDefense(); $parchmentWisdom = $parchment->getSagesse(); addStats($bdd, $parchmentHP, $parchmentMP, $parchmentStrength, $parchmentMagic, $parchmentAgility, $parchmentDefense, $parchmentWisdom, $characterID); deleteItem($bdd, $itemID, $characterID); updateStats($bdd, $characterID); updateAllStats($bdd, $characterID); exit(header("Location: {$linkRoot}/Modules/Inventory/index.php")); require_once $_SESSION['File_Root'] . '/HTML/Footer.php';
/** * Verify the activation code, and activate the user if correct. * Accessed by ?action=activate */ public function action_activate() { global $context, $txt, $modSettings, $scripturl, $language, $user_info; require_once SUBSDIR . '/Auth.subs.php'; // Logged in users should not bother to activate their accounts if (!empty($user_info['id'])) { redirectexit(); } loadLanguage('Login'); loadTemplate('Login'); loadJavascriptFile('sha256.js', array('defer' => true)); if (empty($_REQUEST['u']) && empty($_POST['user'])) { if (empty($modSettings['registration_method']) || $modSettings['registration_method'] == '3') { fatal_lang_error('no_access', false); } $context['member_id'] = 0; $context['sub_template'] = 'resend'; $context['page_title'] = $txt['invalid_activation_resend']; $context['can_activate'] = empty($modSettings['registration_method']) || $modSettings['registration_method'] == '1'; $context['default_username'] = isset($_GET['user']) ? $_GET['user'] : ''; return; } // Get the code from the database... $row = findUser(empty($_REQUEST['u']) ? ' member_name = {string:email_address} OR email_address = {string:email_address}' : ' id_member = {int:id_member}', array('id_member' => isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : 0, 'email_address' => isset($_POST['user']) ? $_POST['user'] : ''), false); // Does this user exist at all? if (empty($row)) { $context['sub_template'] = 'retry_activate'; $context['page_title'] = $txt['invalid_userid']; $context['member_id'] = 0; return; } // Change their email address? (they probably tried a fake one first :P.) require_once SUBSDIR . '/Auth.subs.php'; if (isset($_POST['new_email'], $_REQUEST['passwd']) && validateLoginPassword($_REQUEST['passwd'], $row['passwd'], $row['member_name'], true) && ($row['is_activated'] == 0 || $row['is_activated'] == 2)) { if (empty($modSettings['registration_method']) || $modSettings['registration_method'] == 3) { fatal_lang_error('no_access', false); } // @todo Separate the sprintf? require_once SUBSDIR . '/DataValidator.class.php'; if (!Data_Validator::is_valid($_POST, array('new_email' => 'valid_email|required|max_length[255]'), array('new_email' => 'trim'))) { fatal_error(sprintf($txt['valid_email_needed'], htmlspecialchars($_POST['new_email'], ENT_COMPAT, 'UTF-8')), false); } // Make sure their email isn't banned. isBannedEmail($_POST['new_email'], 'cannot_register', $txt['ban_register_prohibited']); // Ummm... don't even dare try to take someone else's email!! // @todo Separate the sprintf? if (userByEmail($_POST['new_email'])) { fatal_lang_error('email_in_use', false, array(htmlspecialchars($_POST['new_email'], ENT_COMPAT, 'UTF-8'))); } updateMemberData($row['id_member'], array('email_address' => $_POST['new_email'])); $row['email_address'] = $_POST['new_email']; $email_change = true; } // Resend the password, but only if the account wasn't activated yet. if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'resend' && ($row['is_activated'] == 0 || $row['is_activated'] == 2) && (!isset($_REQUEST['code']) || $_REQUEST['code'] == '')) { require_once SUBSDIR . '/Mail.subs.php'; $replacements = array('REALNAME' => $row['real_name'], 'USERNAME' => $row['member_name'], 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $row['id_member'] . ';code=' . $row['validation_code'], 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $row['id_member'], 'ACTIVATIONCODE' => $row['validation_code'], 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder'); $emaildata = loadEmailTemplate('resend_activate_message', $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']); sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, null, false, 0); $context['page_title'] = $txt['invalid_activation_resend']; // This will ensure we don't actually get an error message if it works! $context['error_title'] = ''; fatal_lang_error(!empty($email_change) ? 'change_email_success' : 'resend_email_success', false); } // Quit if this code is not right. if (empty($_REQUEST['code']) || $row['validation_code'] != $_REQUEST['code']) { if (!empty($row['is_activated'])) { fatal_lang_error('already_activated', false); } elseif ($row['validation_code'] == '') { loadLanguage('Profile'); fatal_error($txt['registration_not_approved'] . ' <a href="' . $scripturl . '?action=activate;user='******'member_name'] . '">' . $txt['here'] . '</a>.', false); } $context['sub_template'] = 'retry_activate'; $context['page_title'] = $txt['invalid_activation_code']; $context['member_id'] = $row['id_member']; return; } // Let the integration know that they've been activated! call_integration_hook('integrate_activate', array($row['member_name'])); // Validation complete - update the database! updateMemberData($row['id_member'], array('is_activated' => 1, 'validation_code' => '')); // Also do a proper member stat re-evaluation. updateStats('member', false); if (!isset($_POST['new_email'])) { require_once SUBSDIR . '/Notification.subs.php'; sendAdminNotifications('activation', $row['id_member'], $row['member_name']); } $context += array('page_title' => $txt['registration_successful'], 'sub_template' => 'login', 'default_username' => $row['member_name'], 'default_password' => '', 'never_expire' => false, 'description' => $txt['activate_success']); }
/** * Editing a membergroup. * Screen to edit a specific membergroup. * Called by ?action=admin;area=membergroups;sa=edit;group=x. * It requires the manage_membergroups permission. * Also handles the delete button of the edit form. * Redirects to ?action=admin;area=membergroups. * * @uses the edit_group sub template of ManageMembergroups. */ function EditMembergroup() { global $context, $txt, $sourcedir, $modSettings, $smcFunc; $_REQUEST['group'] = isset($_REQUEST['group']) && $_REQUEST['group'] > 0 ? (int) $_REQUEST['group'] : 0; if (!empty($modSettings['deny_boards_access'])) { loadLanguage('ManagePermissions'); } // Make sure this group is editable. if (!empty($_REQUEST['group'])) { $request = $smcFunc['db_query']('', ' SELECT id_group FROM {db_prefix}membergroups WHERE id_group = {int:current_group}' . (allowedTo('admin_forum') ? '' : ' AND group_type != {int:is_protected}') . ' LIMIT {int:limit}', array('current_group' => $_REQUEST['group'], 'is_protected' => 1, 'limit' => 1)); list($_REQUEST['group']) = $smcFunc['db_fetch_row']($request); $smcFunc['db_free_result']($request); } // Now, do we have a valid id? if (empty($_REQUEST['group'])) { fatal_lang_error('membergroup_does_not_exist', false); } // The delete this membergroup button was pressed. if (isset($_POST['delete'])) { checkSession(); validateToken('admin-mmg'); require_once $sourcedir . '/Subs-Membergroups.php'; deleteMembergroups($_REQUEST['group']); redirectexit('action=admin;area=membergroups;'); } elseif (isset($_POST['save'])) { // Validate the session. checkSession(); validateToken('admin-mmg'); // Can they really inherit from this group? if (isset($_POST['group_inherit']) && $_POST['group_inherit'] != -2 && !allowedTo('admin_forum')) { $request = $smcFunc['db_query']('', ' SELECT group_type FROM {db_prefix}membergroups WHERE id_group = {int:inherit_from} LIMIT {int:limit}', array('inherit_from' => $_POST['group_inherit'], 'limit' => 1)); list($inherit_type) = $smcFunc['db_fetch_row']($request); $smcFunc['db_free_result']($request); } // Set variables to their proper value. $_POST['max_messages'] = isset($_POST['max_messages']) ? (int) $_POST['max_messages'] : 0; $_POST['min_posts'] = isset($_POST['min_posts']) && isset($_POST['group_type']) && $_POST['group_type'] == -1 && $_REQUEST['group'] > 3 ? abs($_POST['min_posts']) : ($_REQUEST['group'] == 4 ? 0 : -1); $_POST['icons'] = empty($_POST['icon_count']) || $_POST['icon_count'] < 0 ? '' : min((int) $_POST['icon_count'], 99) . '#' . $_POST['icon_image']; $_POST['group_desc'] = isset($_POST['group_desc']) && ($_REQUEST['group'] == 1 || isset($_POST['group_type']) && $_POST['group_type'] != -1) ? trim($_POST['group_desc']) : ''; $_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || $_POST['group_type'] == 1 && !allowedTo('admin_forum') ? 0 : (int) $_POST['group_type']; $_POST['group_hidden'] = empty($_POST['group_hidden']) || $_POST['min_posts'] != -1 || $_REQUEST['group'] == 3 ? 0 : (int) $_POST['group_hidden']; $_POST['group_inherit'] = $_REQUEST['group'] > 1 && $_REQUEST['group'] != 3 && (empty($inherit_type) || $inherit_type != 1) ? (int) $_POST['group_inherit'] : -2; //@todo Don't set online_color for the Moderators group? // Do the update of the membergroup settings. $smcFunc['db_query']('', ' UPDATE {db_prefix}membergroups SET group_name = {string:group_name}, online_color = {string:online_color}, max_messages = {int:max_messages}, min_posts = {int:min_posts}, icons = {string:icons}, description = {string:group_desc}, group_type = {int:group_type}, hidden = {int:group_hidden}, id_parent = {int:group_inherit} WHERE id_group = {int:current_group}', array('max_messages' => $_POST['max_messages'], 'min_posts' => $_POST['min_posts'], 'group_type' => $_POST['group_type'], 'group_hidden' => $_POST['group_hidden'], 'group_inherit' => $_POST['group_inherit'], 'current_group' => (int) $_REQUEST['group'], 'group_name' => $smcFunc['htmlspecialchars']($_POST['group_name']), 'online_color' => $_POST['online_color'], 'icons' => $_POST['icons'], 'group_desc' => $_POST['group_desc'])); call_integration_hook('integrate_save_membergroup', array((int) $_REQUEST['group'])); // Time to update the boards this membergroup has access to. if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3) { $accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess']; $changed_boards['allow'] = array(); $changed_boards['deny'] = array(); $changed_boards['ignore'] = array(); foreach ($accesses as $group_id => $action) { $changed_boards[$action][] = (int) $group_id; } foreach (array('allow', 'deny') as $board_action) { // Find all board this group is in, but shouldn't be in. $request = $smcFunc['db_query']('', ' SELECT id_board, {raw:column} FROM {db_prefix}boards WHERE FIND_IN_SET({string:current_group}, {raw:column}) != 0' . (empty($changed_boards[$board_action]) ? '' : ' AND id_board NOT IN ({array_int:board_access_list})'), array('current_group' => (int) $_REQUEST['group'], 'board_access_list' => $changed_boards[$board_action], 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups')); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET {raw:column} = {string:member_group_access} WHERE id_board = {int:current_board}', array('current_board' => $row['id_board'], 'member_group_access' => implode(',', array_diff(explode(',', $row['member_groups']), array($_REQUEST['group']))), 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups')); } $smcFunc['db_free_result']($request); // Add the membergroup to all boards that hadn't been set yet. if (!empty($changed_boards[$board_action])) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END WHERE id_board IN ({array_int:board_list}) AND FIND_IN_SET({int:current_group}, {raw:column}) = 0', array('board_list' => $changed_boards[$board_action], 'blank_string' => '', 'current_group' => (int) $_REQUEST['group'], 'group_id_string' => (string) (int) $_REQUEST['group'], 'comma_group' => ',' . $_REQUEST['group'], 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups')); } } } // Remove everyone from this group! if ($_POST['min_posts'] != -1) { $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET id_group = {int:regular_member} WHERE id_group = {int:current_group}', array('regular_member' => 0, 'current_group' => (int) $_REQUEST['group'])); $request = $smcFunc['db_query']('', ' SELECT id_member, additional_groups FROM {db_prefix}members WHERE FIND_IN_SET({string:current_group}, additional_groups) != 0', array('current_group' => (int) $_REQUEST['group'])); $updates = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $updates[$row['additional_groups']][] = $row['id_member']; } $smcFunc['db_free_result']($request); foreach ($updates as $additional_groups => $memberArray) { updateMemberData($memberArray, array('additional_groups' => implode(',', array_diff(explode(',', $additional_groups), array((int) $_REQUEST['group']))))); } } elseif ($_REQUEST['group'] != 3) { // Making it a hidden group? If so remove everyone with it as primary group (Actually, just make them additional). if ($_POST['group_hidden'] == 2) { $request = $smcFunc['db_query']('', ' SELECT id_member, additional_groups FROM {db_prefix}members WHERE id_group = {int:current_group} AND FIND_IN_SET({int:current_group}, additional_groups) = 0', array('current_group' => (int) $_REQUEST['group'])); $updates = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $updates[$row['additional_groups']][] = $row['id_member']; } $smcFunc['db_free_result']($request); foreach ($updates as $additional_groups => $memberArray) { updateMemberData($memberArray, array('additional_groups' => implode(',', array_merge(explode(',', $additional_groups), array((int) $_REQUEST['group']))))); } $smcFunc['db_query']('', ' UPDATE {db_prefix}members SET id_group = {int:regular_member} WHERE id_group = {int:current_group}', array('regular_member' => 0, 'current_group' => $_REQUEST['group'])); } // Either way, let's check our "show group membership" setting is correct. $request = $smcFunc['db_query']('', ' SELECT COUNT(*) FROM {db_prefix}membergroups WHERE group_type > {int:non_joinable}', array('non_joinable' => 1)); list($have_joinable) = $smcFunc['db_fetch_row']($request); $smcFunc['db_free_result']($request); // Do we need to update the setting? if (empty($modSettings['show_group_membership']) && $have_joinable || !empty($modSettings['show_group_membership']) && !$have_joinable) { updateSettings(array('show_group_membership' => $have_joinable ? 1 : 0)); } } // Do we need to set inherited permissions? if ($_POST['group_inherit'] != -2 && $_POST['group_inherit'] != $_POST['old_inherit']) { require_once $sourcedir . '/ManagePermissions.php'; updateChildPermissions($_POST['group_inherit']); } // Finally, moderators! $moderator_string = isset($_POST['group_moderators']) ? trim($_POST['group_moderators']) : ''; $smcFunc['db_query']('', ' DELETE FROM {db_prefix}group_moderators WHERE id_group = {int:current_group}', array('current_group' => $_REQUEST['group'])); if ((!empty($moderator_string) || !empty($_POST['moderator_list'])) && $_POST['min_posts'] == -1 && $_REQUEST['group'] != 3) { // Get all the usernames from the string if (!empty($moderator_string)) { $moderator_string = strtr(preg_replace('~&#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', htmlspecialchars($moderator_string), ENT_QUOTES), array('"' => '"')); preg_match_all('~"([^"]+)"~', $moderator_string, $matches); $moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string))); for ($k = 0, $n = count($moderators); $k < $n; $k++) { $moderators[$k] = trim($moderators[$k]); if (strlen($moderators[$k]) == 0) { unset($moderators[$k]); } } // Find all the id_member's for the member_name's in the list. $group_moderators = array(); if (!empty($moderators)) { $request = $smcFunc['db_query']('', ' SELECT id_member FROM {db_prefix}members WHERE member_name IN ({array_string:moderators}) OR real_name IN ({array_string:moderators}) LIMIT ' . count($moderators), array('moderators' => $moderators)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $group_moderators[] = $row['id_member']; } $smcFunc['db_free_result']($request); } } else { $moderators = array(); foreach ($_POST['moderator_list'] as $moderator) { $moderators[] = (int) $moderator; } $group_moderators = array(); if (!empty($moderators)) { $request = $smcFunc['db_query']('', ' SELECT id_member FROM {db_prefix}members WHERE id_member IN ({array_int:moderators}) LIMIT {int:num_moderators}', array('moderators' => $moderators, 'num_moderators' => count($moderators))); while ($row = $smcFunc['db_fetch_assoc']($request)) { $group_moderators[] = $row['id_member']; } $smcFunc['db_free_result']($request); } } // Found some? if (!empty($group_moderators)) { $mod_insert = array(); foreach ($group_moderators as $moderator) { $mod_insert[] = array($_REQUEST['group'], $moderator); } $smcFunc['db_insert']('insert', '{db_prefix}group_moderators', array('id_group' => 'int', 'id_member' => 'int'), $mod_insert, array('id_group', 'id_member')); } } // There might have been some post group changes. updateStats('postgroups'); // We've definitely changed some group stuff. updateSettings(array('settings_updated' => time())); // Log the edit. logAction('edited_group', array('group' => $_POST['group_name']), 'admin'); redirectexit('action=admin;area=membergroups'); } // Fetch the current group information. $request = $smcFunc['db_query']('', ' SELECT group_name, description, min_posts, online_color, max_messages, icons, group_type, hidden, id_parent FROM {db_prefix}membergroups WHERE id_group = {int:current_group} LIMIT 1', array('current_group' => (int) $_REQUEST['group'])); if ($smcFunc['db_num_rows']($request) == 0) { fatal_lang_error('membergroup_does_not_exist', false); } $row = $smcFunc['db_fetch_assoc']($request); $smcFunc['db_free_result']($request); $row['icons'] = explode('#', $row['icons']); $context['group'] = array('id' => $_REQUEST['group'], 'name' => $row['group_name'], 'description' => htmlspecialchars($row['description']), 'editable_name' => $row['group_name'], 'color' => $row['online_color'], 'min_posts' => $row['min_posts'], 'max_messages' => $row['max_messages'], 'icon_count' => (int) $row['icons'][0], 'icon_image' => isset($row['icons'][1]) ? $row['icons'][1] : '', 'is_post_group' => $row['min_posts'] != -1, 'type' => $row['min_posts'] != -1 ? 0 : $row['group_type'], 'hidden' => $row['min_posts'] == -1 ? $row['hidden'] : 0, 'inherited_from' => $row['id_parent'], 'allow_post_group' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4, 'allow_delete' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4, 'allow_protected' => allowedTo('admin_forum')); // Get any moderators for this group $request = $smcFunc['db_query']('', ' SELECT mem.id_member, mem.real_name FROM {db_prefix}group_moderators AS mods INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member) WHERE mods.id_group = {int:current_group}', array('current_group' => $_REQUEST['group'])); $context['group']['moderators'] = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $context['group']['moderators'][$row['id_member']] = $row['real_name']; } $smcFunc['db_free_result']($request); $context['group']['moderator_list'] = empty($context['group']['moderators']) ? '' : '"' . implode('", "', $context['group']['moderators']) . '"'; if (!empty($context['group']['moderators'])) { list($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1); } // Get a list of boards this membergroup is allowed to see. $context['boards'] = array(); if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3) { $request = $smcFunc['db_query']('', ' SELECT b.id_cat, c.name as cat_name, b.id_board, b.name, b.child_level, FIND_IN_SET({string:current_group}, b.member_groups) != 0 AS can_access, FIND_IN_SET({string:current_group}, b.deny_member_groups) != 0 AS cannot_access FROM {db_prefix}boards AS b LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat) ORDER BY board_order', array('current_group' => (int) $_REQUEST['group'])); $context['categories'] = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { // This category hasn't been set up yet.. if (!isset($context['categories'][$row['id_cat']])) { $context['categories'][$row['id_cat']] = array('id' => $row['id_cat'], 'name' => $row['cat_name'], 'boards' => array()); } // Set this board up, and let the template know when it's a child. (indent them..) $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array('id' => $row['id_board'], 'name' => $row['name'], 'child_level' => $row['child_level'], 'allow' => !(empty($row['can_access']) || $row['can_access'] == 'f'), 'deny' => !(empty($row['cannot_access']) || $row['cannot_access'] == 'f')); } $smcFunc['db_free_result']($request); // Now, let's sort the list of categories into the boards for templates that like that. $temp_boards = array(); foreach ($context['categories'] as $category) { $temp_boards[] = array('name' => $category['name'], 'child_ids' => array_keys($category['boards'])); $temp_boards = array_merge($temp_boards, array_values($category['boards'])); // Include a list of boards per category for easy toggling. $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']); } $max_boards = ceil(count($temp_boards) / 2); if ($max_boards == 1) { $max_boards = 2; } } // Finally, get all the groups this could be inherited off. $request = $smcFunc['db_query']('', ' SELECT id_group, group_name FROM {db_prefix}membergroups WHERE id_group != {int:current_group}' . (empty($modSettings['permission_enable_postgroups']) ? ' AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : ' AND group_type != {int:is_protected}') . ' AND id_group NOT IN (1, 3) AND id_parent = {int:not_inherited}', array('current_group' => (int) $_REQUEST['group'], 'min_posts' => -1, 'not_inherited' => -2, 'is_protected' => 1)); $context['inheritable_groups'] = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $context['inheritable_groups'][$row['id_group']] = $row['group_name']; } $smcFunc['db_free_result']($request); call_integration_hook('integrate_view_membergroup'); $context['sub_template'] = 'edit_group'; $context['page_title'] = $txt['membergroups_edit_group']; createToken('admin-mmg'); }
function MergeExecute($topics = array()) { global $db_prefix, $user_info, $txt, $context, $scripturl, $sourcedir; global $func, $language, $modSettings; // The parameters of MergeExecute were set, so this must've been an internal call. if (!empty($topics)) { isAllowedTo('merge_any'); loadTemplate('SplitTopics'); } checkSession('request'); // Handle URLs from MergeIndex. if (!empty($_GET['from']) && !empty($_GET['to'])) { $topics = array((int) $_GET['from'], (int) $_GET['to']); } // If we came from a form, the topic IDs came by post. if (!empty($_POST['topics']) && is_array($_POST['topics'])) { $topics = $_POST['topics']; } // There's nothing to merge with just one topic... if (empty($topics) || !is_array($topics) || count($topics) == 1) { fatal_lang_error('merge_need_more_topics'); } // Make sure every topic is numeric, or some nasty things could be done with the DB. foreach ($topics as $id => $topic) { $topics[$id] = (int) $topic; } // Get info about the topics and polls that will be merged. $request = db_query("\n\t\tSELECT\n\t\t\tt.ID_TOPIC, t.ID_BOARD, t.ID_POLL, t.numViews, t.isSticky,\n\t\t\tm1.subject, m1.posterTime AS time_started, IFNULL(mem1.ID_MEMBER, 0) AS ID_MEMBER_STARTED, IFNULL(mem1.realName, m1.posterName) AS name_started,\n\t\t\tm2.posterTime AS time_updated, IFNULL(mem2.ID_MEMBER, 0) AS ID_MEMBER_UPDATED, IFNULL(mem2.realName, m2.posterName) AS name_updated\n\t\tFROM ({$db_prefix}topics AS t, {$db_prefix}messages AS m1, {$db_prefix}messages AS m2)\n\t\t\tLEFT JOIN {$db_prefix}members AS mem1 ON (mem1.ID_MEMBER = m1.ID_MEMBER)\n\t\t\tLEFT JOIN {$db_prefix}members AS mem2 ON (mem2.ID_MEMBER = m2.ID_MEMBER)\n\t\tWHERE t.ID_TOPIC IN (" . implode(', ', $topics) . ")\n\t\t\tAND m1.ID_MSG = t.ID_FIRST_MSG\n\t\t\tAND m2.ID_MSG = t.ID_LAST_MSG\n\t\tORDER BY t.ID_FIRST_MSG\n\t\tLIMIT " . count($topics), __FILE__, __LINE__); if (mysql_num_rows($request) < 2) { fatal_lang_error('smf263'); } $num_views = 0; $isSticky = 0; $boards = array(); $polls = array(); while ($row = mysql_fetch_assoc($request)) { $topic_data[$row['ID_TOPIC']] = array('id' => $row['ID_TOPIC'], 'board' => $row['ID_BOARD'], 'poll' => $row['ID_POLL'], 'numViews' => $row['numViews'], 'subject' => $row['subject'], 'started' => array('time' => timeformat($row['time_started']), 'timestamp' => forum_time(true, $row['time_started']), 'href' => empty($row['ID_MEMBER_STARTED']) ? '' : $scripturl . '?action=profile;u=' . $row['ID_MEMBER_STARTED'], 'link' => empty($row['ID_MEMBER_STARTED']) ? $row['name_started'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['ID_MEMBER_STARTED'] . '">' . $row['name_started'] . '</a>'), 'updated' => array('time' => timeformat($row['time_updated']), 'timestamp' => forum_time(true, $row['time_updated']), 'href' => empty($row['ID_MEMBER_UPDATED']) ? '' : $scripturl . '?action=profile;u=' . $row['ID_MEMBER_UPDATED'], 'link' => empty($row['ID_MEMBER_UPDATED']) ? $row['name_updated'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['ID_MEMBER_UPDATED'] . '">' . $row['name_updated'] . '</a>')); $num_views += $row['numViews']; $boards[] = $row['ID_BOARD']; // If there's no poll, ID_POLL == 0... if ($row['ID_POLL'] > 0) { $polls[] = $row['ID_POLL']; } // Store the ID_TOPIC with the lowest ID_FIRST_MSG. if (empty($firstTopic)) { $firstTopic = $row['ID_TOPIC']; } $isSticky = max($isSticky, $row['isSticky']); } mysql_free_result($request); $boards = array_values(array_unique($boards)); // Get the boards a user is allowed to merge in. $merge_boards = boardsAllowedTo('merge_any'); if (empty($merge_boards)) { fatal_lang_error('cannot_merge_any'); } // Make sure they can see all boards.... $request = db_query("\n\t\tSELECT b.ID_BOARD\n\t\tFROM {$db_prefix}boards AS b\n\t\tWHERE b.ID_BOARD IN (" . implode(', ', $boards) . ")\n\t\t\tAND {$user_info['query_see_board']}" . (!in_array(0, $merge_boards) ? "\n\t\t\tAND b.ID_BOARD IN (" . implode(', ', $merge_boards) . ")" : '') . "\n\t\tLIMIT " . count($boards), __FILE__, __LINE__); // If the number of boards that's in the output isn't exactly the same as we've put in there, you're in trouble. if (mysql_num_rows($request) != count($boards)) { fatal_lang_error('smf232'); } mysql_free_result($request); if (empty($_REQUEST['sa']) || $_REQUEST['sa'] == 'options') { if (count($polls) > 1) { $request = db_query("\n\t\t\t\tSELECT t.ID_TOPIC, t.ID_POLL, m.subject, p.question\n\t\t\t\tFROM ({$db_prefix}polls AS p, {$db_prefix}topics AS t, {$db_prefix}messages AS m)\n\t\t\t\tWHERE p.ID_POLL IN (" . implode(', ', $polls) . ")\n\t\t\t\t\tAND t.ID_POLL = p.ID_POLL\n\t\t\t\t\tAND m.ID_MSG = t.ID_FIRST_MSG\n\t\t\t\tLIMIT " . count($polls), __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { $context['polls'][] = array('id' => $row['ID_POLL'], 'topic' => array('id' => $row['ID_TOPIC'], 'subject' => $row['subject']), 'question' => $row['question'], 'selected' => $row['ID_TOPIC'] == $firstTopic); } mysql_free_result($request); } if (count($boards) > 1) { $request = db_query("\n\t\t\t\tSELECT ID_BOARD, name\n\t\t\t\tFROM {$db_prefix}boards\n\t\t\t\tWHERE ID_BOARD IN (" . implode(', ', $boards) . ")\n\t\t\t\tORDER BY name\n\t\t\t\tLIMIT " . count($boards), __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { $context['boards'][] = array('id' => $row['ID_BOARD'], 'name' => $row['name'], 'selected' => $row['ID_BOARD'] == $topic_data[$firstTopic]['board']); } mysql_free_result($request); } $context['topics'] = $topic_data; foreach ($topic_data as $id => $topic) { $context['topics'][$id]['selected'] = $topic['id'] == $firstTopic; } $context['page_title'] = $txt['smf252']; $context['sub_template'] = 'merge_extra_options'; return; } // Determine target board. $target_board = count($boards) > 1 ? (int) $_REQUEST['board'] : $boards[0]; if (!in_array($target_board, $boards)) { fatal_lang_error('smf232'); } // Determine which poll will survive and which polls won't. $target_poll = count($polls) > 1 ? (int) $_POST['poll'] : (count($polls) == 1 ? $polls[0] : 0); if ($target_poll > 0 && !in_array($target_poll, $polls)) { fatal_lang_error(1, false); } $deleted_polls = empty($target_poll) ? $polls : array_diff($polls, array($target_poll)); // Determine the subject of the newly merged topic - was a custom subject specified? if (empty($_POST['subject']) && isset($_POST['custom_subject']) && $_POST['custom_subject'] != '') { $target_subject = $func['htmlspecialchars']($_POST['custom_subject']); } elseif (!empty($topic_data[(int) $_POST['subject']]['subject'])) { $target_subject = addslashes($topic_data[(int) $_POST['subject']]['subject']); } else { $target_subject = addslashes($topic_data[$firstTopic]['subject']); } // Get the first and last message and the number of messages.... $request = db_query("\n\t\tSELECT MIN(ID_MSG), MAX(ID_MSG), COUNT(ID_MSG) - 1\n\t\tFROM {$db_prefix}messages\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $topics) . ")", __FILE__, __LINE__); list($first_msg, $last_msg, $num_replies) = mysql_fetch_row($request); mysql_free_result($request); // Get the member ID of the first and last message. $request = db_query("\n\t\tSELECT ID_MEMBER\n\t\tFROM {$db_prefix}messages\n\t\tWHERE ID_MSG IN ({$first_msg}, {$last_msg})\n\t\tORDER BY ID_MSG\n\t\tLIMIT 2", __FILE__, __LINE__); list($member_started) = mysql_fetch_row($request); list($member_updated) = mysql_fetch_row($request); mysql_free_result($request); // Assign the first topic ID to be the merged topic. $ID_TOPIC = min($topics); // Delete the remaining topics. $deleted_topics = array_diff($topics, array($ID_TOPIC)); db_query("\n\t\tDELETE FROM {$db_prefix}topics\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleted_topics) . ")\n\t\tLIMIT " . count($deleted_topics), __FILE__, __LINE__); db_query("\n\t\tDELETE FROM {$db_prefix}log_search_subjects\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleted_topics) . ")", __FILE__, __LINE__); // Asssign the properties of the newly merged topic. db_query("\n\t\tUPDATE {$db_prefix}topics\n\t\tSET\n\t\t\tID_BOARD = {$target_board},\n\t\t\tID_MEMBER_STARTED = {$member_started},\n\t\t\tID_MEMBER_UPDATED = {$member_updated},\n\t\t\tID_FIRST_MSG = {$first_msg},\n\t\t\tID_LAST_MSG = {$last_msg},\n\t\t\tID_POLL = {$target_poll},\n\t\t\tnumReplies = {$num_replies},\n\t\t\tnumViews = {$num_views},\n\t\t\tisSticky = {$isSticky}\n\t\tWHERE ID_TOPIC = {$ID_TOPIC}\n\t\tLIMIT 1", __FILE__, __LINE__); // Grab the response prefix (like 'Re: ') in the default forum language. if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix'))) { if ($language === $user_info['language']) { $context['response_prefix'] = $txt['response_prefix']; } else { loadLanguage('index', $language, false); $context['response_prefix'] = $txt['response_prefix']; loadLanguage('index'); } cache_put_data('response_prefix', $context['response_prefix'], 600); } // Change the topic IDs of all messages that will be merged. Also adjust subjects if 'enforce subject' was checked. db_query("\n\t\tUPDATE {$db_prefix}messages\n\t\tSET\n\t\t\tID_TOPIC = {$ID_TOPIC},\n\t\t\tID_BOARD = {$target_board}" . (!empty($_POST['enforce_subject']) ? ",\n\t\t\tsubject = '{$context['response_prefix']}{$target_subject}'" : '') . "\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $topics) . ")", __FILE__, __LINE__); // Change the subject of the first message... db_query("\n\t\tUPDATE {$db_prefix}messages\n\t\tSET subject = '{$target_subject}'\n\t\tWHERE ID_MSG = {$first_msg}\n\t\tLIMIT 1", __FILE__, __LINE__); // Adjust all calendar events to point to the new topic. db_query("\n\t\tUPDATE {$db_prefix}calendar\n\t\tSET\n\t\t\tID_TOPIC = {$ID_TOPIC},\n\t\t\tID_BOARD = {$target_board}\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleted_topics) . ")", __FILE__, __LINE__); // Merge log topic entries. $request = db_query("\n\t\tSELECT ID_MEMBER, MIN(ID_MSG) AS new_ID_MSG\n\t\tFROM {$db_prefix}log_topics\n\t\tWHERE ID_TOPIC IN (" . implode(', ', $topics) . ")\n\t\tGROUP BY ID_MEMBER", __FILE__, __LINE__); if (mysql_num_rows($request) > 0) { $replaceEntries = array(); while ($row = mysql_fetch_assoc($request)) { $replaceEntries[] = "({$row['ID_MEMBER']}, {$ID_TOPIC}, {$row['new_ID_MSG']})"; } db_query("\n\t\t\tREPLACE INTO {$db_prefix}log_topics\n\t\t\t\t(ID_MEMBER, ID_TOPIC, ID_MSG)\n\t\t\tVALUES " . implode(', ', $replaceEntries), __FILE__, __LINE__); unset($replaceEntries); // Get rid of the old log entries. db_query("\n\t\t\tDELETE FROM {$db_prefix}log_topics\n\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleted_topics) . ")", __FILE__, __LINE__); } mysql_free_result($request); // Merge topic notifications. if (!empty($_POST['notifications']) && is_array($_POST['notifications'])) { // Check if the notification array contains valid topics. if (count(array_diff($_POST['notifications'], $topics)) > 0) { fatal_lang_error('smf232'); } $request = db_query("\n\t\t\tSELECT ID_MEMBER, MAX(sent) AS sent\n\t\t\tFROM {$db_prefix}log_notify\n\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $_POST['notifications']) . ")\n\t\t\tGROUP BY ID_MEMBER", __FILE__, __LINE__); if (mysql_num_rows($request) > 0) { $replaceEntries = array(); while ($row = mysql_fetch_assoc($request)) { $replaceEntries[] = "({$row['ID_MEMBER']}, {$ID_TOPIC}, 0, {$row['sent']})"; } db_query("\n\t\t\t\tREPLACE INTO {$db_prefix}log_notify\n\t\t\t\t\t(ID_MEMBER, ID_TOPIC, ID_BOARD, sent)\n\t\t\t\tVALUES " . implode(', ', $replaceEntries), __FILE__, __LINE__); unset($replaceEntries); db_query("\n\t\t\t\tDELETE FROM {$db_prefix}log_topics\n\t\t\t\tWHERE ID_TOPIC IN (" . implode(', ', $deleted_topics) . ")", __FILE__, __LINE__); } mysql_free_result($request); } // Get rid of the redundant polls. if (!empty($deleted_polls)) { db_query("\n\t\t\tDELETE FROM {$db_prefix}polls\n\t\t\tWHERE ID_POLL IN (" . implode(', ', $deleted_polls) . ")\n\t\t\tLIMIT 1", __FILE__, __LINE__); db_query("\n\t\t\tDELETE FROM {$db_prefix}poll_choices\n\t\t\tWHERE ID_POLL IN (" . implode(', ', $deleted_polls) . ")", __FILE__, __LINE__); db_query("\n\t\t\tDELETE FROM {$db_prefix}log_polls\n\t\t\tWHERE ID_POLL IN (" . implode(', ', $deleted_polls) . ")", __FILE__, __LINE__); } // Fix the board totals. if (count($boards) > 1) { $request = db_query("\n\t\t\tSELECT ID_BOARD, COUNT(*) AS numTopics, SUM(numReplies) + COUNT(*) AS numPosts\n\t\t\tFROM {$db_prefix}topics\n\t\t\tWHERE ID_BOARD IN (" . implode(', ', $boards) . ")\n\t\t\tGROUP BY ID_BOARD\n\t\t\tLIMIT " . count($boards), __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { db_query("\n\t\t\t\tUPDATE {$db_prefix}boards\n\t\t\t\tSET\n\t\t\t\t\tnumPosts = {$row['numPosts']},\n\t\t\t\t\tnumTopics = {$row['numTopics']}\n\t\t\t\tWHERE ID_BOARD = {$row['ID_BOARD']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); } mysql_free_result($request); } else { db_query("\n\t\t\tUPDATE {$db_prefix}boards\n\t\t\tSET numTopics = IF(" . (count($topics) - 1) . " > numTopics, 0, numTopics - " . (count($topics) - 1) . ")\n\t\t\tWHERE ID_BOARD = {$target_board}\n\t\t\tLIMIT 1", __FILE__, __LINE__); } require_once $sourcedir . '/Subs-Post.php'; // Update all the statistics. updateStats('topic'); updateStats('subject', $ID_TOPIC, $target_subject); updateLastMessages($boards); logAction('merge', array('topic' => $ID_TOPIC)); // Notify people that these topics have been merged? sendNotifications($ID_TOPIC, 'merge'); // Send them to the all done page. redirectexit('action=mergetopics;sa=done;to=' . $ID_TOPIC . ';targetboard=' . $target_board); }
function AdminBoardRecount() { global $txt, $context, $scripturl, $modSettings, $sourcedir; global $time_start, $smcFunc; isAllowedTo('admin_forum'); checkSession('request'); $context['page_title'] = $txt['not_done_title']; $context['continue_post_data'] = ''; $context['continue_countdown'] = '3'; $context['sub_template'] = 'not_done'; // Try for as much time as possible. @set_time_limit(600); // Step the number of topics at a time so things don't time out... $request = $smcFunc['db_query']('', ' SELECT MAX(id_topic) FROM {db_prefix}topics', array()); list($max_topics) = $smcFunc['db_fetch_row']($request); $smcFunc['db_free_result']($request); $increment = min(max(50, ceil($max_topics / 4)), 2000); if (empty($_REQUEST['start'])) { $_REQUEST['start'] = 0; } $total_steps = 8; // Get each topic with a wrong reply count and fix it - let's just do some at a time, though. if (empty($_REQUEST['step'])) { $_REQUEST['step'] = 0; while ($_REQUEST['start'] < $max_topics) { // Recount approved messages $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.num_replies) AS num_replies, CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END AS real_num_replies FROM {db_prefix}topics AS t LEFT JOIN {db_prefix}messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = {int:is_approved}) WHERE t.id_topic > {int:start} AND t.id_topic <= {int:max_id} GROUP BY t.id_topic HAVING CASE WHEN COUNT(ma.id_msg) >= 1 THEN COUNT(ma.id_msg) - 1 ELSE 0 END != MAX(t.num_replies)', array('is_approved' => 1, 'start' => $_REQUEST['start'], 'max_id' => $_REQUEST['start'] + $increment)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET num_replies = {int:num_replies} WHERE id_topic = {int:id_topic}', array('num_replies' => $row['real_num_replies'], 'id_topic' => $row['id_topic'])); } $smcFunc['db_free_result']($request); // Recount unapproved messages $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts, COUNT(mu.id_msg) AS real_unapproved_posts FROM {db_prefix}topics AS t LEFT JOIN {db_prefix}messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = {int:not_approved}) WHERE t.id_topic > {int:start} AND t.id_topic <= {int:max_id} GROUP BY t.id_topic HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)', array('not_approved' => 0, 'start' => $_REQUEST['start'], 'max_id' => $_REQUEST['start'] + $increment)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET unapproved_posts = {int:unapproved_posts} WHERE id_topic = {int:id_topic}', array('unapproved_posts' => $row['real_unapproved_posts'], 'id_topic' => $row['id_topic'])); } $smcFunc['db_free_result']($request); $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round(100 * $_REQUEST['start'] / $max_topics / $total_steps); return; } } $_REQUEST['start'] = 0; } // Update the post count of each board. if ($_REQUEST['step'] <= 1) { if (empty($_REQUEST['start'])) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_posts = {int:num_posts} WHERE redirect = {string:redirect}', array('num_posts' => 0, 'redirect' => '')); } while ($_REQUEST['start'] < $max_topics) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ m.id_board, COUNT(*) AS real_num_posts FROM {db_prefix}messages AS m WHERE m.id_topic > {int:id_topic_min} AND m.id_topic <= {int:id_topic_max} AND m.approved = {int:is_approved} GROUP BY m.id_board', array('id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, 'is_approved' => 1)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_posts = num_posts + {int:real_num_posts} WHERE id_board = {int:id_board}', array('id_board' => $row['id_board'], 'real_num_posts' => $row['real_num_posts'])); } $smcFunc['db_free_result']($request); $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); return; } } $_REQUEST['start'] = 0; } // Update the topic count of each board. if ($_REQUEST['step'] <= 2) { if (empty($_REQUEST['start'])) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_topics = {int:num_topics}', array('num_topics' => 0)); } while ($_REQUEST['start'] < $max_topics) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ t.id_board, COUNT(*) AS real_num_topics FROM {db_prefix}topics AS t WHERE t.approved = {int:is_approved} AND t.id_topic > {int:id_topic_min} AND t.id_topic <= {int:id_topic_max} GROUP BY t.id_board', array('is_approved' => 1, 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_topics = num_topics + {int:real_num_topics} WHERE id_board = {int:id_board}', array('id_board' => $row['id_board'], 'real_num_topics' => $row['real_num_topics'])); } $smcFunc['db_free_result']($request); $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); return; } } $_REQUEST['start'] = 0; } // Update the unapproved post count of each board. if ($_REQUEST['step'] <= 3) { if (empty($_REQUEST['start'])) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET unapproved_posts = {int:unapproved_posts}', array('unapproved_posts' => 0)); } while ($_REQUEST['start'] < $max_topics) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ m.id_board, COUNT(*) AS real_unapproved_posts FROM {db_prefix}messages AS m WHERE m.id_topic > {int:id_topic_min} AND m.id_topic <= {int:id_topic_max} AND m.approved = {int:is_approved} GROUP BY m.id_board', array('id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment, 'is_approved' => 0)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET unapproved_posts = unapproved_posts + {int:unapproved_posts} WHERE id_board = {int:id_board}', array('id_board' => $row['id_board'], 'unapproved_posts' => $row['real_unapproved_posts'])); } $smcFunc['db_free_result']($request); $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=3;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round((400 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); return; } } $_REQUEST['start'] = 0; } // Update the unapproved topic count of each board. if ($_REQUEST['step'] <= 4) { if (empty($_REQUEST['start'])) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET unapproved_topics = {int:unapproved_topics}', array('unapproved_topics' => 0)); } while ($_REQUEST['start'] < $max_topics) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ t.id_board, COUNT(*) AS real_unapproved_topics FROM {db_prefix}topics AS t WHERE t.approved = {int:is_approved} AND t.id_topic > {int:id_topic_min} AND t.id_topic <= {int:id_topic_max} GROUP BY t.id_board', array('is_approved' => 0, 'id_topic_min' => $_REQUEST['start'], 'id_topic_max' => $_REQUEST['start'] + $increment)); while ($row = $smcFunc['db_fetch_assoc']($request)) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET unapproved_topics = unapproved_topics + {int:real_unapproved_topics} WHERE id_board = {int:id_board}', array('id_board' => $row['id_board'], 'real_unapproved_topics' => $row['real_unapproved_topics'])); } $smcFunc['db_free_result']($request); $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=4;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round((500 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps); return; } } $_REQUEST['start'] = 0; } // Get all members with wrong number of personal messages. if ($_REQUEST['step'] <= 5) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ mem.id_member, COUNT(pmr.id_pm) AS real_num, MAX(mem.instant_messages) AS instant_messages FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted}) GROUP BY mem.id_member HAVING COUNT(pmr.id_pm) != MAX(mem.instant_messages)', array('is_not_deleted' => 0)); while ($row = $smcFunc['db_fetch_assoc']($request)) { updateMemberData($row['id_member'], array('instant_messages' => $row['real_num'])); } $smcFunc['db_free_result']($request); $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ mem.id_member, COUNT(pmr.id_pm) AS real_num, MAX(mem.unread_messages) AS unread_messages FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted} AND pmr.is_read = {int:is_not_read}) GROUP BY mem.id_member HAVING COUNT(pmr.id_pm) != MAX(mem.unread_messages)', array('is_not_deleted' => 0, 'is_not_read' => 0)); while ($row = $smcFunc['db_fetch_assoc']($request)) { updateMemberData($row['id_member'], array('unread_messages' => $row['real_num'])); } $smcFunc['db_free_result']($request); if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=0;' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round(700 / $total_steps); return; } } // Any messages pointing to the wrong board? if ($_REQUEST['step'] <= 6) { while ($_REQUEST['start'] < $modSettings['maxMsgID']) { $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ t.id_board, m.id_msg FROM {db_prefix}messages AS m INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_board != m.id_board) WHERE m.id_msg > {int:id_msg_min} AND m.id_msg <= {int:id_msg_max}', array('id_msg_min' => $_REQUEST['start'], 'id_msg_max' => $_REQUEST['start'] + $increment)); $boards = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $boards[$row['id_board']][] = $row['id_msg']; } $smcFunc['db_free_result']($request); foreach ($boards as $board_id => $messages) { $smcFunc['db_query']('', ' UPDATE {db_prefix}messages SET id_board = {int:id_board} WHERE id_msg IN ({array_int:id_msg_array})', array('id_msg_array' => $messages, 'id_board' => $board_id)); } $_REQUEST['start'] += $increment; if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)) > 3) { $context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id']; $context['continue_percent'] = round((700 + 100 * $_REQUEST['start'] / $modSettings['maxMsgID']) / $total_steps); return; } } $_REQUEST['start'] = 0; } // Update the latest message of each board. $request = $smcFunc['db_query']('', ' SELECT m.id_board, MAX(m.id_msg) AS local_last_msg FROM {db_prefix}messages AS m WHERE m.approved = {int:is_approved} GROUP BY m.id_board', array('is_approved' => 1)); $realBoardCounts = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $realBoardCounts[$row['id_board']] = $row['local_last_msg']; } $smcFunc['db_free_result']($request); $request = $smcFunc['db_query']('', ' SELECT /*!40001 SQL_NO_CACHE */ id_board, id_parent, id_last_msg, child_level, id_msg_updated FROM {db_prefix}boards', array()); $resort_me = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $row['local_last_msg'] = isset($realBoardCounts[$row['id_board']]) ? $realBoardCounts[$row['id_board']] : 0; $resort_me[$row['child_level']][] = $row; } $smcFunc['db_free_result']($request); krsort($resort_me); $lastModifiedMsg = array(); foreach ($resort_me as $rows) { foreach ($rows as $row) { // The latest message is the latest of the current board and its children. if (isset($lastModifiedMsg[$row['id_board']])) { $curLastModifiedMsg = max($row['local_last_msg'], $lastModifiedMsg[$row['id_board']]); } else { $curLastModifiedMsg = $row['local_last_msg']; } // If what is and what should be the latest message differ, an update is necessary. if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated']) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated} WHERE id_board = {int:id_board}', array('id_last_msg' => $row['local_last_msg'], 'id_msg_updated' => $curLastModifiedMsg, 'id_board' => $row['id_board'])); } // Parent boards inherit the latest modified message of their children. if (isset($lastModifiedMsg[$row['id_parent']])) { $lastModifiedMsg[$row['id_parent']] = max($row['local_last_msg'], $lastModifiedMsg[$row['id_parent']]); } else { $lastModifiedMsg[$row['id_parent']] = $row['local_last_msg']; } } } // Update all the basic statistics. updateStats('member'); updateStats('message'); updateStats('topic'); // Finally, update the latest event times. require_once $sourcedir . '/ScheduledTasks.php'; CalculateNextTrigger(); redirectexit('action=admin;area=maintain;sa=routine;done=recount'); }
function AdminApprove() { global $txt, $context, $db_prefix, $scripturl, $modSettings, $sourcedir, $language, $user_info; require_once $sourcedir . '/Subs-Post.php'; // We also need to the login languages here - for emails. loadLanguage('Login'); // Sort out where we are going... $browse_type = isset($_REQUEST['type']) ? $_REQUEST['type'] : (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1 ? 'activate' : 'approve'); $current_filter = (int) $_REQUEST['orig_filter']; // If we are applying a filter do just that - then redirect. if (isset($_REQUEST['filter']) && $_REQUEST['filter'] != $_REQUEST['orig_filter']) { redirectexit('action=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $_REQUEST['filter'] . ';start=' . $_REQUEST['start']); } // Nothing to do? if (!isset($_POST['todoAction']) && !isset($_POST['time_passed'])) { redirectexit('action=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); } // Are we dealing with members who have been waiting for > set amount of time? if (isset($_POST['time_passed'])) { $timeBefore = time() - 86400 * (int) $_POST['time_passed']; $condition = "\n\t\t\tAND dateRegistered < {$timeBefore}"; } else { $members = array(); foreach ($_POST['todoAction'] as $id) { $members[] = (int) $id; } $condition = "\n\t\t\tAND ID_MEMBER IN (" . implode(', ', $members) . ")"; } // Get information on each of the members, things that are important to us, like email address... $request = db_query("\n\t\tSELECT ID_MEMBER, memberName, realName, emailAddress, validation_code, lngfile\n\t\tFROM {$db_prefix}members\n\t\tWHERE is_activated = {$current_filter}{$condition}\n\t\tORDER BY lngfile", __FILE__, __LINE__); $member_count = mysql_num_rows($request); // If no results then just return! if ($member_count == 0) { redirectexit('action=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); } $member_info = array(); $members = array(); // Fill the info array. while ($row = mysql_fetch_assoc($request)) { $members[] = $row['ID_MEMBER']; $member_info[] = array('id' => $row['ID_MEMBER'], 'username' => $row['memberName'], 'name' => $row['realName'], 'email' => $row['emailAddress'], 'language' => empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'], 'code' => $row['validation_code']); } mysql_free_result($request); // Are we activating or approving the members? if ($_POST['todo'] == 'ok' || $_POST['todo'] == 'okemail') { // Approve/activate this member. db_query("\n\t\t\tUPDATE {$db_prefix}members\n\t\t\tSET validation_code = '', is_activated = 1\n\t\t\tWHERE is_activated = {$current_filter}{$condition}\n\t\t\tLIMIT {$member_count}", __FILE__, __LINE__); // Do we have to let the integration code know about the activations? if (isset($modSettings['integrate_activate']) && function_exists($modSettings['integrate_activate'])) { foreach ($member_info as $member) { call_user_func($modSettings['integrate_activate'], $member['username']); } } // Check for email. if ($_POST['todo'] == 'okemail') { foreach ($member_info as $member) { if (empty($current_language) || $current_language != $member['language']) { $current_language = loadLanguage('index', $member['language'], false); loadLanguage('ManageMembers', $member['language'], false); } sendmail($member['email'], $txt['register_subject'], "{$txt['hello_guest']} {$member['name']}!\n\n" . "{$txt['admin_approve_accept_desc']} {$txt['719']} {$member['username']}\n\n" . "{$txt['701']}\n" . "{$scripturl}?action=profile\n\n" . $txt[130]); } } } elseif ($_POST['todo'] == 'require_activation') { require_once $sourcedir . '/Subs-Members.php'; // We have to do this for each member I'm afraid. foreach ($member_info as $member) { // Generate a random activation code. $validation_code = generateValidationCode(); // Set these members for activation - I know this includes two ID_MEMBER checks but it's safer than bodging $condition ;). db_query("\n\t\t\t\tUPDATE {$db_prefix}members\n\t\t\t\tSET validation_code = '{$validation_code}', is_activated = 0\n\t\t\t\tWHERE is_activated = {$current_filter}\n\t\t\t\t\t{$condition}\n\t\t\t\t\tAND ID_MEMBER = {$member['id']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); if (empty($current_language) || $current_language != $member['language']) { $current_language = loadLanguage('index', $member['language'], false); loadLanguage('ManageMembers', $member['language'], false); } // Send out the activation email. sendmail($member['email'], $txt['register_subject'], "{$txt['hello_guest']} {$member['name']}!\n\n" . "{$txt['admin_approve_require_activation']} {$txt['admin_approve_remind_desc2']}\n" . "{$scripturl}?action=activate;u={$member['id']};code={$validation_code}\n\n" . $txt[130]); } } elseif ($_POST['todo'] == 'reject' || $_POST['todo'] == 'rejectemail') { require_once $sourcedir . '/Subs-Members.php'; deleteMembers($members); // Send email telling them they aren't welcome? if ($_POST['todo'] == 'rejectemail') { foreach ($member_info as $member) { if (empty($current_language) || $current_language != $member['language']) { $current_language = loadLanguage('ManageMembers', $member['language'], false); } sendmail($member['email'], $txt['admin_approve_reject'], "{$member['name']},\n\n" . "{$txt['admin_approve_reject_desc']}\n\n" . $txt[130]); } } } elseif ($_POST['todo'] == 'delete' || $_POST['todo'] == 'deleteemail') { require_once $sourcedir . '/Subs-Members.php'; deleteMembers($members); // Send email telling them they aren't welcome? if ($_POST['todo'] == 'deleteemail') { foreach ($member_info as $member) { if (empty($current_language) || $current_language != $member['language']) { $current_language = loadLanguage('ManageMembers', $member['language'], false); } sendmail($member['email'], $txt['admin_approve_delete'], "{$member['name']},\n\n" . "{$txt['admin_approve_delete_desc']}\n\n" . $txt[130]); } } } elseif ($_POST['todo'] == 'remind') { foreach ($member_info as $member) { if (empty($current_language) || $current_language != $member['language']) { $current_language = loadLanguage('ManageMembers', $member['language'], false); } sendmail($member['email'], $txt['admin_approve_remind'], "{$member['name']},\n\n" . "{$txt['admin_approve_remind_desc']} {$context['forum_name']}.\n\n{$txt['admin_approve_remind_desc2']}\n\n" . "{$scripturl}?action=activate;u={$member['id']};code={$member['code']}\n\n" . $txt[130]); } } // Back to the user's language! if (isset($current_language) && $current_language != $user_info['language']) { loadLanguage('index'); loadLanguage('ManageMembers'); } // Although updateStats *may* catch this, best to do it manually just incase (Doesn't always sort out unapprovedMembers). if (in_array($current_filter, array(3, 4))) { updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > $member_count ? $modSettings['unapprovedMembers'] - $member_count : 0)); } // Update the member's stats. (but, we know the member didn't change their name.) updateStats('member', false); // If they haven't been deleted, update the post group statistics on them... if (!in_array($_POST['todo'], array('delete', 'deleteemail', 'reject', 'rejectemail', 'remind'))) { updateStats('postgroups', 'ID_MEMBER IN (' . implode(', ', $members) . ')'); } redirectexit('action=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']); }
function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions) { global $db_prefix, $user_info, $ID_MEMBER, $modSettings; $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null; $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null; $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null; // This is longer than it has to be, but makes it so we only set/change what we have to. $messages_columns = array(); if (isset($posterOptions['name'])) { $messages_columns[] = "posterName = '{$posterOptions['name']}'"; } if (isset($posterOptions['email'])) { $messages_columns[] = "posterEmail = '{$posterOptions['email']}'"; } if (isset($msgOptions['icon'])) { $messages_columns[] = "icon = '{$msgOptions['icon']}'"; } if (isset($msgOptions['subject'])) { $messages_columns[] = "subject = '{$msgOptions['subject']}'"; } if (isset($msgOptions['body'])) { $messages_columns[] = "body = '{$msgOptions['body']}'"; if (!empty($modSettings['search_custom_index_config'])) { $request = db_query("\n\t\t\t\tSELECT body\n\t\t\t\tFROM {$db_prefix}messages\n\t\t\t\tWHERE ID_MSG = {$msgOptions['id']}", __FILE__, __LINE__); list($old_body) = mysql_fetch_row($request); mysql_free_result($request); } } if (!empty($msgOptions['modify_time'])) { $messages_columns[] = "modifiedTime = {$msgOptions['modify_time']}"; $messages_columns[] = "modifiedName = '{$msgOptions['modify_name']}'"; $messages_columns[] = "ID_MSG_MODIFIED = {$modSettings['maxMsgID']}"; } if (isset($msgOptions['smileys_enabled'])) { $messages_columns[] = "smileysEnabled = " . (empty($msgOptions['smileys_enabled']) ? '0' : '1'); } // Change the post. db_query("\n\t\tUPDATE {$db_prefix}messages\n\t\tSET " . implode(', ', $messages_columns) . "\n\t\tWHERE ID_MSG = {$msgOptions['id']}\n\t\tLIMIT 1", __FILE__, __LINE__); // Lock and or sticky the post. if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null) { db_query("\n\t\t\tUPDATE {$db_prefix}topics\n\t\t\tSET\n\t\t\t\tisSticky = " . ($topicOptions['sticky_mode'] === null ? 'isSticky' : $topicOptions['sticky_mode']) . ",\n\t\t\t\tlocked = " . ($topicOptions['lock_mode'] === null ? 'locked' : $topicOptions['lock_mode']) . ",\n\t\t\t\tID_POLL = " . ($topicOptions['poll'] === null ? 'ID_POLL' : $topicOptions['poll']) . "\n\t\t\tWHERE ID_TOPIC = {$topicOptions['id']}\n\t\t\tLIMIT 1", __FILE__, __LINE__); } // Mark inserted topic as read. if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest']) { db_query("\n\t\t\tREPLACE INTO {$db_prefix}log_topics\n\t\t\t\t(ID_TOPIC, ID_MEMBER, ID_MSG)\n\t\t\tVALUES ({$topicOptions['id']}, {$ID_MEMBER}, {$modSettings['maxMsgID']})", __FILE__, __LINE__); } // If there's a custom search index, it needs to be modified... if (isset($msgOptions['body']) && !empty($modSettings['search_custom_index_config'])) { $stopwords = empty($modSettings['search_stopwords']) ? array() : explode(',', addslashes($modSettings['search_stopwords'])); $old_index = text2words($old_body, 4, true); $new_index = text2words(stripslashes($msgOptions['body']), 4, true); // Calculate the words to remove from the index. $removed_words = array_diff(array_diff($old_index, $new_index), $stopwords); if (!empty($removed_words)) { db_query("\n\t\t\t\tDELETE FROM {$db_prefix}log_search_words\n\t\t\t\tWHERE ID_MSG = {$msgOptions['id']}\n\t\t\t\t\tAND ID_WORD IN (" . implode(", ", $removed_words) . ")\n\t\t\t\tLIMIT " . count($removed_words), __FILE__, __LINE__); } // Calculate the new words to be indexed. $inserted_words = array_diff(array_diff($new_index, $old_index), $stopwords); if (!empty($inserted_words)) { db_query("\n\t\t\t\tINSERT IGNORE INTO {$db_prefix}log_search_words\n\t\t\t\t\t(ID_WORD, ID_MSG)\n\t\t\t\tVALUES\n\t\t\t\t\t('" . implode("', {$msgOptions['id']}),\n\t\t\t\t\t('", $inserted_words) . "', {$msgOptions['id']})", __FILE__, __LINE__); } } if (isset($msgOptions['subject'])) { // Only update the subject if this was the first message in the topic. $request = db_query("\n\t\t\tSELECT ID_TOPIC\n\t\t\tFROM {$db_prefix}topics\n\t\t\tWHERE ID_FIRST_MSG = {$msgOptions['id']}\n\t\t\tLIMIT 1", __FILE__, __LINE__); if (mysql_num_rows($request) == 1) { updateStats('subject', $topicOptions['id'], $msgOptions['subject']); } mysql_free_result($request); } return true; }
public function update() { global $settings, $db_type; global $time_start, $maintenance, $msubject, $mmessage, $mbname, $language; global $boardurl, $webmaster_email, $cookiename; global $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error; global $modSettings, $context, $sc, $user_info, $topic, $board, $txt; global $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd; global $sourcedir, $boarddir; define('SUBSDIR', BOARDDIR . '/sources/subs'); require BOARDDIR . '/Settings.php'; require BOARDDIR . '/sources/Subs.php'; require BOARDDIR . '/sources/Load.php'; require_once SUBSDIR . '/Util.class.php'; $settings['theme_dir'] = $settings['default_theme_dir'] = BOARDDIR . '/Themes/default'; $settings['theme_url'] = $settings['default_theme_url'] = $boardurl . '/themes/default'; // Create a member $db = database(); $request = $db->insert('', '{db_prefix}members', array('member_name' => 'string-25', 'real_name' => 'string-25', 'passwd' => 'string', 'email_address' => 'string', 'id_group' => 'int', 'posts' => 'int', 'date_registered' => 'int', 'hide_email' => 'int', 'password_salt' => 'string', 'lngfile' => 'string', 'personal_text' => 'string', 'avatar' => 'string', 'member_ip' => 'string', 'member_ip2' => 'string', 'buddy_list' => 'string', 'pm_ignore_list' => 'string', 'message_labels' => 'string', 'website_title' => 'string', 'website_url' => 'string', 'location' => 'string', 'signature' => 'string', 'usertitle' => 'string', 'secret_question' => 'string', 'additional_groups' => 'string', 'ignore_boards' => 'string', 'openid_uri' => 'string'), array('test_admin', 'test_admin', sha1(strtolower(stripslashes('test_admin')) . stripslashes('test_admin_pwd')), '*****@*****.**', 1, 0, time(), 0, substr(md5(mt_rand()), 0, 4), '', '', '', '123.123.123.123', '123.123.123.123', '', '', '', '', '', '', '', '', '', '', '', ''), array('id_member')); $server_offset = @mktime(0, 0, 0, 1, 1, 1970); $timezone_id = 'Etc/GMT' . ($server_offset > 0 ? '+' : '') . $server_offset / 3600; if (date_default_timezone_set($timezone_id)) { $db->insert('', $db_prefix . 'settings', array('variable' => 'string-255', 'value' => 'string-65534'), array('default_timezone', $timezone_id), array('variable')); } updateStats('member'); updateStats('message'); updateStats('topic'); loadLanguage('Install'); updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject'])); }
function moveTopics($topics, $toBoard) { global $sourcedir, $user_info, $modSettings, $smcFunc; // Empty array? if (empty($topics)) { return; } elseif (is_numeric($topics)) { $topics = array($topics); } $num_topics = count($topics); $fromBoards = array(); // Destination board empty or equal to 0? if (empty($toBoard)) { return; } // Are we moving to the recycle board? $isRecycleDest = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $toBoard; // Determine the source boards... $request = $smcFunc['db_query']('', ' SELECT id_board, approved, COUNT(*) AS num_topics, SUM(unapproved_posts) AS unapproved_posts, SUM(num_replies) AS num_replies FROM {db_prefix}topics WHERE id_topic IN ({array_int:topics}) GROUP BY id_board, approved', array('topics' => $topics)); // Num of rows = 0 -> no topics found. Num of rows > 1 -> topics are on multiple boards. if ($smcFunc['db_num_rows']($request) == 0) { return; } while ($row = $smcFunc['db_fetch_assoc']($request)) { if (!isset($fromBoards[$row['id_board']]['num_posts'])) { $fromBoards[$row['id_board']] = array('num_posts' => 0, 'num_topics' => 0, 'unapproved_posts' => 0, 'unapproved_topics' => 0, 'id_board' => $row['id_board']); } // Posts = (num_replies + 1) for each approved topic. $fromBoards[$row['id_board']]['num_posts'] += $row['num_replies'] + ($row['approved'] ? $row['num_topics'] : 0); $fromBoards[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts']; // Add the topics to the right type. if ($row['approved']) { $fromBoards[$row['id_board']]['num_topics'] += $row['num_topics']; } else { $fromBoards[$row['id_board']]['unapproved_topics'] += $row['num_topics']; } } $smcFunc['db_free_result']($request); // Move over the mark_read data. (because it may be read and now not by some!) $SaveAServer = max(0, $modSettings['maxMsgID'] - 50000); $request = $smcFunc['db_query']('', ' SELECT lmr.id_member, lmr.id_msg, t.id_topic FROM {db_prefix}topics AS t INNER JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_msg > t.id_first_msg AND lmr.id_msg > {int:protect_lmr_msg}) LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = lmr.id_member) WHERE t.id_topic IN ({array_int:topics}) AND lmr.id_msg > IFNULL(lt.id_msg, 0)', array('protect_lmr_msg' => $SaveAServer, 'topics' => $topics)); $log_topics = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $log_topics[] = array($row['id_topic'], $row['id_member'], $row['id_msg']); // Prevent queries from getting too big. Taking some steam off. if (count($log_topics) > 500) { $smcFunc['db_insert']('replace', '{db_prefix}log_topics', array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), $log_topics, array('id_topic', 'id_member')); $log_topics = array(); } } $smcFunc['db_free_result']($request); // Now that we have all the topics that *should* be marked read, and by which members... if (!empty($log_topics)) { // Insert that information into the database! $smcFunc['db_insert']('replace', '{db_prefix}log_topics', array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), $log_topics, array('id_topic', 'id_member')); } // Update the number of posts on each board. $totalTopics = 0; $totalPosts = 0; $totalUnapprovedTopics = 0; $totalUnapprovedPosts = 0; foreach ($fromBoards as $stats) { $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_posts = CASE WHEN {int:num_posts} > num_posts THEN 0 ELSE num_posts - {int:num_posts} END, num_topics = CASE WHEN {int:num_topics} > num_topics THEN 0 ELSE num_topics - {int:num_topics} END, unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END, unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END WHERE id_board = {int:id_board}', array('id_board' => $stats['id_board'], 'num_posts' => $stats['num_posts'], 'num_topics' => $stats['num_topics'], 'unapproved_posts' => $stats['unapproved_posts'], 'unapproved_topics' => $stats['unapproved_topics'])); $totalTopics += $stats['num_topics']; $totalPosts += $stats['num_posts']; $totalUnapprovedTopics += $stats['unapproved_topics']; $totalUnapprovedPosts += $stats['unapproved_posts']; } $smcFunc['db_query']('', ' UPDATE {db_prefix}boards SET num_topics = num_topics + {int:total_topics}, num_posts = num_posts + {int:total_posts},' . ($isRecycleDest ? ' unapproved_posts = {int:no_unapproved}, unapproved_topics = {int:no_unapproved}' : ' unapproved_posts = unapproved_posts + {int:total_unapproved_posts}, unapproved_topics = unapproved_topics + {int:total_unapproved_topics}') . ' WHERE id_board = {int:id_board}', array('id_board' => $toBoard, 'total_topics' => $totalTopics, 'total_posts' => $totalPosts, 'total_unapproved_topics' => $totalUnapprovedTopics, 'total_unapproved_posts' => $totalUnapprovedPosts, 'no_unapproved' => 0)); // Move the topic. Done. :P $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET id_board = {int:id_board}' . ($isRecycleDest ? ', unapproved_posts = {int:no_unapproved}, approved = {int:is_approved}' : '') . ' WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics, 'is_approved' => 1, 'no_unapproved' => 0)); // If this was going to the recycle bin, check what messages are being recycled, and remove them from the queue. if ($isRecycleDest && ($totalUnapprovedTopics || $totalUnapprovedPosts)) { $request = $smcFunc['db_query']('', ' SELECT id_msg FROM {db_prefix}messages WHERE id_topic IN ({array_int:topics}) and approved = {int:not_approved}', array('topics' => $topics, 'not_approved' => 0)); $approval_msgs = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $approval_msgs[] = $row['id_msg']; } $smcFunc['db_free_result']($request); // Empty the approval queue for these, as we're going to approve them next. if (!empty($approval_msgs)) { $smcFunc['db_query']('', ' DELETE FROM {db_prefix}approval_queue WHERE id_msg IN ({array_int:message_list}) AND id_attach = {int:id_attach}', array('message_list' => $approval_msgs, 'id_attach' => 0)); } // Get all the current max and mins. $request = $smcFunc['db_query']('', ' SELECT id_topic, id_first_msg, id_last_msg FROM {db_prefix}topics WHERE id_topic IN ({array_int:topics})', array('topics' => $topics)); $topicMaxMin = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { $topicMaxMin[$row['id_topic']] = array('min' => $row['id_first_msg'], 'max' => $row['id_last_msg']); } $smcFunc['db_free_result']($request); // Check the MAX and MIN are correct. $request = $smcFunc['db_query']('', ' SELECT id_topic, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg FROM {db_prefix}messages WHERE id_topic IN ({array_int:topics}) GROUP BY id_topic', array('topics' => $topics)); while ($row = $smcFunc['db_fetch_assoc']($request)) { // If not, update. if ($row['first_msg'] != $topicMaxMin[$row['id_topic']]['min'] || $row['last_msg'] != $topicMaxMin[$row['id_topic']]['max']) { $smcFunc['db_query']('', ' UPDATE {db_prefix}topics SET id_first_msg = {int:first_msg}, id_last_msg = {int:last_msg} WHERE id_topic = {int:selected_topic}', array('first_msg' => $row['first_msg'], 'last_msg' => $row['last_msg'], 'selected_topic' => $row['id_topic'])); } } $smcFunc['db_free_result']($request); } $smcFunc['db_query']('', ' UPDATE {db_prefix}messages SET id_board = {int:id_board}' . ($isRecycleDest ? ',approved = {int:is_approved}' : '') . ' WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics, 'is_approved' => 1)); $smcFunc['db_query']('', ' UPDATE {db_prefix}log_reported SET id_board = {int:id_board} WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics)); $smcFunc['db_query']('', ' UPDATE {db_prefix}calendar SET id_board = {int:id_board} WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics)); // Mark target board as seen, if it was already marked as seen before. $request = $smcFunc['db_query']('', ' SELECT (IFNULL(lb.id_msg, 0) >= b.id_msg_updated) AS isSeen FROM {db_prefix}boards AS b LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member}) WHERE b.id_board = {int:id_board}', array('current_member' => $user_info['id'], 'id_board' => $toBoard)); list($isSeen) = $smcFunc['db_fetch_row']($request); $smcFunc['db_free_result']($request); if (!empty($isSeen) && !$user_info['is_guest']) { $smcFunc['db_insert']('replace', '{db_prefix}log_boards', array('id_board' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), array($toBoard, $user_info['id'], $modSettings['maxMsgID']), array('id_board', 'id_member')); } // Update 'em pesky stats. updateStats('topic'); updateStats('message'); updateSettings(array('calendar_updated' => time())); // Update the cache? if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3) { foreach ($topics as $topic_id) { cache_put_data('topic_board-' . $topic_id, null, 120); } } require_once $sourcedir . '/Subs-Post.php'; $updates = array_keys($fromBoards); $updates[] = $toBoard; updateLastMessages(array_unique($updates)); }
function updateBanMembers() { global $smcFunc; $updates = array(); $allMembers = array(); $newMembers = array(); // Start by getting all active bans - it's quicker doing this in parts... $request = $smcFunc['db_query']('', ' SELECT bi.id_member, bi.email_address FROM {db_prefix}ban_items AS bi INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group) WHERE (bi.id_member > {int:no_member} OR bi.email_address != {string:blank_string}) AND bg.cannot_access = {int:cannot_access_on} AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})', array('no_member' => 0, 'cannot_access_on' => 1, 'current_time' => time(), 'blank_string' => '')); $memberIDs = array(); $memberEmails = array(); $memberEmailWild = array(); while ($row = $smcFunc['db_fetch_assoc']($request)) { if ($row['id_member']) { $memberIDs[$row['id_member']] = $row['id_member']; } if ($row['email_address']) { // Does it have a wildcard - if so we can't do a IN on it. if (strpos($row['email_address'], '%') !== false) { $memberEmailWild[$row['email_address']] = $row['email_address']; } else { $memberEmails[$row['email_address']] = $row['email_address']; } } } $smcFunc['db_free_result']($request); // Build up the query. $queryPart = array(); $queryValues = array(); if (!empty($memberIDs)) { $queryPart[] = 'mem.id_member IN ({array_string:member_ids})'; $queryValues['member_ids'] = $memberIDs; } if (!empty($memberEmails)) { $queryPart[] = 'mem.email_address IN ({array_string:member_emails})'; $queryValues['member_emails'] = $memberEmails; } $count = 0; foreach ($memberEmailWild as $email) { $queryPart[] = 'mem.email_address LIKE {string:wild_' . $count . '}'; $queryValues['wild_' . $count++] = $email; } // Find all banned members. if (!empty($queryPart)) { $request = $smcFunc['db_query']('', ' SELECT mem.id_member, mem.is_activated FROM {db_prefix}members AS mem WHERE ' . implode(' OR ', $queryPart), $queryValues); while ($row = $smcFunc['db_fetch_assoc']($request)) { if (!in_array($row['id_member'], $allMembers)) { $allMembers[] = $row['id_member']; // Do they need an update? if ($row['is_activated'] < 10) { $updates[$row['is_activated'] + 10][] = $row['id_member']; $newMembers[] = $row['id_member']; } } } $smcFunc['db_free_result']($request); } // We welcome our new members in the realm of the banned. if (!empty($newMembers)) { $smcFunc['db_query']('', ' DELETE FROM {db_prefix}log_online WHERE id_member IN ({array_int:new_banned_members})', array('new_banned_members' => $newMembers)); } // Find members that are wrongfully marked as banned. $request = $smcFunc['db_query']('', ' SELECT mem.id_member, mem.is_activated - 10 AS new_value FROM {db_prefix}members AS mem LEFT JOIN {db_prefix}ban_items AS bi ON (bi.id_member = mem.id_member OR mem.email_address LIKE bi.email_address) LEFT JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND bg.cannot_access = {int:cannot_access_activated} AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})) WHERE (bi.id_ban IS NULL OR bg.id_ban_group IS NULL) AND mem.is_activated >= {int:ban_flag}', array('cannot_access_activated' => 1, 'current_time' => time(), 'ban_flag' => 10)); while ($row = $smcFunc['db_fetch_assoc']($request)) { // Don't do this twice! if (!in_array($row['id_member'], $allMembers)) { $updates[$row['new_value']][] = $row['id_member']; $allMembers[] = $row['id_member']; } } $smcFunc['db_free_result']($request); if (!empty($updates)) { foreach ($updates as $newStatus => $members) { updateMemberData($members, array('is_activated' => $newStatus)); } } // Update the latest member and our total members as banning may change them. updateStats('member'); }
function CalendarPost() { global $context, $txt, $db_prefix, $user_info, $sourcedir, $scripturl; global $modSettings, $topic, $ID_MEMBER, $func; // Well - can they? isAllowedTo('calendar_post'); // Cast this for safety... if (isset($_REQUEST['eventid'])) { $_REQUEST['eventid'] = (int) $_REQUEST['eventid']; } // Submitting? if (isset($_POST['sc'], $_REQUEST['eventid'])) { checkSession(); // Validate the post... if (!isset($_POST['link_to_board'])) { require_once $sourcedir . '/Subs-Post.php'; calendarValidatePost(); } // If you're not allowed to edit any events, you have to be the poster. if ($_REQUEST['eventid'] > 0 && !allowedTo('calendar_edit_any')) { // Get the event's poster. $request = db_query("\n\t\t\t\tSELECT ID_MEMBER\n\t\t\t\tFROM {$db_prefix}calendar\n\t\t\t\tWHERE ID_EVENT = {$_REQUEST['eventid']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); list($poster) = mysql_fetch_row($request); mysql_free_result($request); // Finally, test if they can either edit ANY, or just their own... if (!allowedTo('calendar_edit_any')) { isAllowedTo('calendar_edit_' . ($poster == $ID_MEMBER ? 'own' : 'any')); } } // New - and directing? if ($_REQUEST['eventid'] == -1 && isset($_POST['link_to_board'])) { $_REQUEST['calendar'] = 1; require_once $sourcedir . '/Post.php'; return Post(); } elseif ($_REQUEST['eventid'] == -1) { calendarInsertEvent(0, 0, $_POST['evtitle'], $ID_MEMBER, $_POST['month'], $_POST['day'], $_POST['year'], isset($_POST['span']) ? $_POST['span'] : null); } elseif (isset($_REQUEST['deleteevent'])) { db_query("\n\t\t\t\tDELETE FROM {$db_prefix}calendar\n\t\t\t\tWHERE ID_EVENT = {$_REQUEST['eventid']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); } else { // Calculate the eventDate depending on span. $span = empty($modSettings['cal_allowspan']) || empty($_POST['span']) || $_POST['span'] == 1 || empty($modSettings['cal_maxspan']) || $_POST['span'] > $modSettings['cal_maxspan'] ? 0 : min((int) $modSettings['cal_maxspan'], (int) $_POST['span'] - 1); $start_time = mktime(0, 0, 0, (int) $_REQUEST['month'], (int) $_REQUEST['day'], (int) $_REQUEST['year']); db_query("\n\t\t\t\tUPDATE {$db_prefix}calendar\n\t\t\t\tSET \n\t\t\t\t\tstartDate = '" . strftime('%Y-%m-%d', $start_time) . "',\n\t\t\t\t\tendDate = '" . strftime('%Y-%m-%d', $start_time + $span * 86400) . "', \n\t\t\t\t\ttitle = '" . $func['htmlspecialchars']($_REQUEST['evtitle'], ENT_QUOTES) . "'\n\t\t\t\tWHERE ID_EVENT = {$_REQUEST['eventid']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__); } updateStats('calendar'); // No point hanging around here now... redirectexit($scripturl . '?action=calendar;month=' . $_POST['month'] . ';year=' . $_POST['year']); } // If we are not enabled... we are not enabled. if (empty($modSettings['cal_allow_unlinked']) && empty($_REQUEST['eventid'])) { $_REQUEST['calendar'] = 1; require_once $sourcedir . '/Post.php'; return Post(); } // New? if (!isset($_REQUEST['eventid'])) { $today = getdate(); $context['event'] = array('boards' => array(), 'board' => !empty($modSettings['cal_defaultboard']) ? $modSettings['cal_defaultboard'] : 0, 'new' => 1, 'eventid' => -1, 'year' => isset($_REQUEST['year']) ? $_REQUEST['year'] : $today['year'], 'month' => isset($_REQUEST['month']) ? $_REQUEST['month'] : $today['mon'], 'day' => isset($_REQUEST['day']) ? $_REQUEST['day'] : $today['mday'], 'title' => '', 'span' => 1); // Get list of boards that can be posted in. $boards = boardsAllowedTo('post_new'); if (empty($boards)) { fatal_lang_error('cannot_post_new'); } $request = db_query("\n\t\t\tSELECT c.name AS catName, c.ID_CAT, b.ID_BOARD, b.name AS boardName, b.childLevel\n\t\t\tFROM {$db_prefix}boards AS b\n\t\t\t\tLEFT JOIN {$db_prefix}categories AS c ON (c.ID_CAT = b.ID_CAT)\n\t\t\tWHERE {$user_info['query_see_board']}" . (in_array(0, $boards) ? '' : "\n\t\t\t\tAND b.ID_BOARD IN (" . implode(', ', $boards) . ")"), __FILE__, __LINE__); while ($row = mysql_fetch_assoc($request)) { $context['event']['boards'][] = array('id' => $row['ID_BOARD'], 'name' => $row['boardName'], 'childLevel' => $row['childLevel'], 'prefix' => str_repeat(' ', $row['childLevel'] * 3), 'cat' => array('id' => $row['ID_CAT'], 'name' => $row['catName'])); } mysql_free_result($request); } else { $request = db_query("\n\t\t\tSELECT\n\t\t\t\tc.ID_EVENT, c.ID_BOARD, c.ID_TOPIC, MONTH(c.startDate) AS month,\n\t\t\t\tDAYOFMONTH(c.startDate) AS day, YEAR(c.startDate) AS year,\n\t\t\t\t(TO_DAYS(c.endDate) - TO_DAYS(c.startDate)) AS span, c.ID_MEMBER, c.title,\n\t\t\t\tt.ID_FIRST_MSG, t.ID_MEMBER_STARTED\n\t\t\tFROM {$db_prefix}calendar AS c\n\t\t\t\tLEFT JOIN {$db_prefix}topics AS t ON (t.ID_TOPIC = c.ID_TOPIC)\n\t\t\tWHERE c.ID_EVENT = {$_REQUEST['eventid']}", __FILE__, __LINE__); // If nothing returned, we are in poo, poo. if (mysql_num_rows($request) == 0) { fatal_lang_error(1); } $row = mysql_fetch_assoc($request); mysql_free_result($request); // If it has a board, then they should be editing it within the topic. if ($row['ID_TOPIC'] && $row['ID_FIRST_MSG']) { // We load the board up, for a check on the board access rights... $topic = $row['ID_TOPIC']; loadBoard(); } // Make sure the user is allowed to edit this event. if ($row['ID_MEMBER'] != $ID_MEMBER) { isAllowedTo('calendar_edit_any'); } elseif (!allowedTo('calendar_edit_any')) { isAllowedTo('calendar_edit_own'); } $context['event'] = array('boards' => array(), 'board' => $row['ID_BOARD'], 'new' => 0, 'eventid' => $_REQUEST['eventid'], 'year' => $row['year'], 'month' => $row['month'], 'day' => $row['day'], 'title' => $row['title'], 'span' => 1 + $row['span']); } $context['event']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['event']['month'] == 12 ? 1 : $context['event']['month'] + 1, 0, $context['event']['month'] == 12 ? $context['event']['year'] + 1 : $context['event']['year'])); // Template, sub template, etc. loadTemplate('Calendar'); $context['sub_template'] = 'event_post'; $context['page_title'] = isset($_REQUEST['eventid']) ? $txt['calendar20'] : $txt['calendar23']; $context['linktree'][] = array('name' => $context['page_title']); }
function modifyPost(&$msgOptions, &$topicOptions, &$posterOptions) { global $user_info, $modSettings, $context, $sourcedir; $topicOptions['poll'] = isset($topicOptions['poll']) ? (int) $topicOptions['poll'] : null; $topicOptions['lock_mode'] = isset($topicOptions['lock_mode']) ? $topicOptions['lock_mode'] : null; $topicOptions['sticky_mode'] = isset($topicOptions['sticky_mode']) ? $topicOptions['sticky_mode'] : null; $tagged_users = array(); $context['can_tag_users'] = allowedTo('tag_users'); if (isset($msgOptions['body'])) { $tagged_users = handleUserTags($msgOptions['body']); } // This is longer than it has to be, but makes it so we only set/change what we have to. $messages_columns = array(); if (isset($posterOptions['name'])) { $messages_columns['poster_name'] = $posterOptions['name']; } if (isset($posterOptions['email'])) { $messages_columns['poster_email'] = $posterOptions['email']; } if (isset($msgOptions['icon'])) { $messages_columns['icon'] = $msgOptions['icon']; } if (isset($msgOptions['subject'])) { $messages_columns['subject'] = $msgOptions['subject']; } if (isset($msgOptions['body'])) { $messages_columns['body'] = $msgOptions['body']; if (!empty($modSettings['search_custom_index_config'])) { $request = smf_db_query(' SELECT body, smileys_enabled FROM {db_prefix}messages WHERE id_msg = {int:id_msg}', array('id_msg' => $msgOptions['id'])); list($old_body, $old_smileys_enabled) = mysql_fetch_row($request); mysql_free_result($request); } } if (isset($msgOptions['locked'])) { $messages_columns['locked'] = $msgOptions['locked']; } if (!empty($msgOptions['modify_time'])) { $messages_columns['modified_time'] = $msgOptions['modify_time']; $messages_columns['modified_name'] = $msgOptions['modify_name']; $messages_columns['id_msg_modified'] = $modSettings['maxMsgID']; } if (isset($msgOptions['smileys_enabled'])) { $messages_columns['smileys_enabled'] = empty($msgOptions['smileys_enabled']) ? 0 : 1; $smileys_enabled = $msgOptions['smileys_enabled']; } else { if (isset($msgOptions['body'])) { $smileys_enabled = $old_smileys_enabled; } } // Which columns need to be ints? $messageInts = array('modified_time', 'id_msg_modified', 'smileys_enabled'); $update_parameters = array('id_msg' => $msgOptions['id']); foreach ($messages_columns as $var => $val) { $messages_columns[$var] = $var . ' = {' . (in_array($var, $messageInts) ? 'int' : 'string') . ':var_' . $var . '}'; $update_parameters['var_' . $var] = $val; } // Nothing to do? if (empty($messages_columns)) { return true; } // Change the post. smf_db_query(' UPDATE {db_prefix}messages SET ' . implode(', ', $messages_columns) . ' WHERE id_msg = {int:id_msg}', $update_parameters); /* * delete cached posts (they will update at the next view) */ if (isset($msgOptions['body'])) { smf_db_query('DELETE FROM {db_prefix}messages_cache WHERE id_msg = {int:id_msg}', array('id_msg' => $msgOptions['id'])); CacheAPI::clearCacheByPrefix('parse:' . trim($msgOptions['id']) . '-'); } else { $context['no_astream'] = true; } $context['no_astream'] = isset($context['no_astream']) ? $context['no_astream'] : 0; // Lock and or sticky the post. if ($topicOptions['sticky_mode'] !== null || $topicOptions['lock_mode'] !== null || $topicOptions['poll'] !== null) { smf_db_query(' UPDATE {db_prefix}topics SET is_sticky = {raw:is_sticky}, locked = {raw:locked}, id_poll = {raw:id_poll} WHERE id_topic = {int:id_topic}', array('is_sticky' => $topicOptions['sticky_mode'] === null ? 'is_sticky' : (int) $topicOptions['sticky_mode'], 'locked' => $topicOptions['lock_mode'] === null ? 'locked' : (int) $topicOptions['lock_mode'], 'id_poll' => $topicOptions['poll'] === null ? 'id_poll' : (int) $topicOptions['poll'], 'id_topic' => $topicOptions['id'])); } if (isset($topicOptions['id_first_msg']) && $msgOptions['id'] == $topicOptions['id_first_msg']) { if (isset($topicOptions['topic_prefix'])) { smf_db_query(' UPDATE {db_prefix}topics SET id_prefix = {int:id_prefix} WHERE id_topic = {int:id_topic}', array('id_prefix' => $topicOptions['topic_prefix'], 'id_topic' => $topicOptions['id'])); } if (isset($topicOptions['topic_layout'])) { smf_db_query(' UPDATE {db_prefix}topics SET id_layout = {int:id_layout} WHERE id_topic = {int:id_topic}', array('id_layout' => $topicOptions['topic_layout'], 'id_topic' => $topicOptions['id'])); } } // Mark the edited post as read. if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest']) { // Since it's likely they *read* it before editing, let's try an UPDATE first. smf_db_query(' UPDATE {db_prefix}log_topics SET id_msg = {int:id_msg} WHERE id_member = {int:current_member} AND id_topic = {int:id_topic}', array('current_member' => $user_info['id'], 'id_msg' => $modSettings['maxMsgID'], 'id_topic' => $topicOptions['id'])); $flag = smf_db_affected_rows() != 0; if (empty($flag)) { smf_db_insert('ignore', '{db_prefix}log_topics', array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), array($topicOptions['id'], $user_info['id'], $modSettings['maxMsgID']), array('id_topic', 'id_member')); } } if (count($tagged_users) > 0) { notifyTaggedUsers($tagged_users, array('id_topic' => $topicOptions['id'], 'id_message' => $msgOptions['id'])); } // If there's a custom search index, it needs to be modified... if (isset($msgOptions['body']) && !empty($modSettings['search_custom_index_config'])) { $customIndexSettings = unserialize($modSettings['search_custom_index_config']); $stopwords = empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']); $old_index = text2words($old_body, $customIndexSettings['bytes_per_word'], true); $new_index = text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true); // Calculate the words to be added and removed from the index. $removed_words = array_diff(array_diff($old_index, $new_index), $stopwords); $inserted_words = array_diff(array_diff($new_index, $old_index), $stopwords); // Delete the removed words AND the added ones to avoid key constraints. if (!empty($removed_words)) { $removed_words = array_merge($removed_words, $inserted_words); smf_db_query(' DELETE FROM {db_prefix}log_search_words WHERE id_msg = {int:id_msg} AND id_word IN ({array_int:removed_words})', array('removed_words' => $removed_words, 'id_msg' => $msgOptions['id'])); } // Add the new words to be indexed. if (!empty($inserted_words)) { $inserts = array(); foreach ($inserted_words as $word) { $inserts[] = array($word, $msgOptions['id']); } smf_db_insert('insert', '{db_prefix}log_search_words', array('id_word' => 'string', 'id_msg' => 'int'), $inserts, array('id_word', 'id_msg')); } } if (isset($msgOptions['subject'])) { // Only update the subject if this was the first message in the topic. $request = smf_db_query(' SELECT id_topic FROM {db_prefix}topics WHERE id_first_msg = {int:id_first_msg} LIMIT 1', array('id_first_msg' => $msgOptions['id'])); if (mysql_num_rows($request) == 1) { updateStats('subject', $topicOptions['id'], $msgOptions['subject']); // Added by Related Topics if (isset($modSettings['have_related_topics']) && $modSettings['have_related_topics']) { require_once $sourcedir . '/lib/Subs-Related.php'; relatedUpdateTopics($topicOptions['id']); } // Related Topics END } mysql_free_result($request); } // Finally, if we are setting the approved state we need to do much more work :( if ($modSettings['postmod_active'] && isset($msgOptions['approved'])) { approvePosts($msgOptions['id'], $msgOptions['approved']); } // record in activity stream if ($modSettings['astream_active'] && !$context['no_astream']) { require_once $sourcedir . '/lib/Subs-Activities.php'; aStreamAdd($user_info['id'], ACT_MODIFY_POST, array('member_name' => $user_info['name'], 'topic_title' => $msgOptions['subject']), $topicOptions['board'], $topicOptions['id'], $msgOptions['id'], $msgOptions['id_owner']); } return true; }