Esempio n. 1
0
 function onUse()
 {
     global $db_prefix, $context, $item_info;
     updateMemberData($context['user']['id'], array('totalTimeLoggedIn' => 'totalTimeLoggedIn + ' . (int) $item_info[1]));
     $time_hours = (int) $item_info[1] / 3600;
     return 'Successfully added ' . $item_info[1] . ' seconds (' . $time_hours . ' hours) to total logged in time.';
 }
Esempio n. 2
0
 function onUse()
 {
     global $db_prefix, $context, $item_info;
     // If an amount was not defined by the admin, assume defaults
     if (!isset($item_info[1]) || $item_info[1] == '') {
         $item_info[1] = -190;
     }
     if (!isset($item_info[2]) || $item_info[2] == '') {
         $item_info[2] = 190;
     }
     $amount = mt_rand($item_info[1], $item_info[2]);
     // Did we lose money?
     if ($amount < 0) {
         $result = db_query("\n\t\t\t\tSELECT money\n\t\t\t\tFROM {$db_prefix}members\n\t\t\t\tWHERE ID_MEMBER = {$context[user][id]}", __FILE__, __LINE__);
         $row = mysql_fetch_assoc($result);
         $amountLoss = abs($amount);
         // If the user has enough money to pay for it out of his/her pocket
         if ($row['money'] > $amountLoss) {
             updateMemberData($context['user']['id'], array('money' => 'money - ' . $amountLoss));
             return 'You lost ' . formatMoney($amountLoss) . '!';
         } else {
             updateMemberData($context['user']['id'], array('memberBank' => 'moneyBank - ' . $amountLoss));
             return 'You lost ' . formatMoney($amountLoss) . '!<br /><br />You didn\'t have enough money in your pocket, so the money was taken from your bank! :(';
         }
     } else {
         updateMemberData($context['user']['id'], array('money' => 'money + ' . $amount));
         return 'You got ' . formatMoney($amount) . '!';
     }
 }
Esempio n. 3
0
 function onUse()
 {
     global $context, $smcFunc;
     if (!isset($_POST['newtitle']) || $_POST['newtitle'] == '') {
         die('ERROR: Please enter a new user title!');
     }
     $_POST['newtitle'] = $smcFunc['htmlspecialchars']($_POST['newtitle'], ENT_QUOTES);
     updateMemberData($context['user']['id'], array('usertitle' => $_POST['newtitle']));
     return 'Successfully changed your user title to ' . $_POST['newtitle'];
 }
Esempio n. 4
0
function twit_integrate_login($user, $hashPasswd, $cookieTime)
{
    global $user_settings;
    if (isset($_GET['synctw'])) {
        $twitter_profile = '' . $_SESSION['twit_name'] . '';
        updateMemberData($user_settings['id_member'], array('twitname' => $_SESSION['twit_name'], 'twitid' => $_SESSION['twit_id'], 'twitrn' => $_SESSION['twit_sn']));
        update_themes_twitter($user_settings['id_member'], 'twit_pro', $twitter_profile);
        unset($_SESSION['twit_name']);
        unset($_SESSION['twit_id']);
        unset($_SESSION['twit_sn']);
    } else {
        return;
    }
}
Esempio n. 5
0
 function onUse()
 {
     global $context, $item_info, $smcFunc;
     // Use a length of 5 as default
     if (!isset($item_info[1]) || $item_info[1] == 0) {
         $item_info[1] = 5;
     }
     if (strlen($_POST['newDisplayName']) < $item_info[1]) {
         die('ERROR: The name you chose was not long enough! Please go back and choose a name which is at least ' . $item_info[1] . ' characters long.');
     }
     $_POST['newDisplayName'] = $smcFunc['htmlspecialchars']($_POST['newDisplayName'], ENT_QUOTES);
     updateMemberData($context['user']['id'], array('real_name' => $_POST['newDisplayName']));
     return 'Successfully changed your display name to ' . $_POST['newDisplayName'];
 }
Esempio n. 6
0
function gplus_integrate_login($user, $hashPasswd, $cookieTime)
{
    global $user_settings;
    if (isset($_GET['syncgp'])) {
        $gdata = $_SESSION['gplusdata'];
        $_SESSION['gplus']['id'] = $gdata['id'];
        $_SESSION['gplus']['name'] = $gdata['name'];
        updateMemberData($user_settings['id_member'], array('gpid' => $_SESSION['gplus']['id'], 'gpname' => $_SESSION['gplus']['name']));
        unset($_SESSION['gplus']['id']);
        unset($_SESSION['gplus']['name']);
        unset($_SESSION['gplusdata']);
    } else {
        return;
    }
}
Esempio n. 7
0
 function onUse()
 {
     global $context, $func;
     if (!isset($_POST['newusername']) || $_POST['newusername'] == '') {
         die('ERROR: Please enter a new username!');
     }
     $_POST['newusername'] = $func['htmlspecialchars']($_POST['newusername'], ENT_QUOTES);
     // Check if username is in use
     $result = db_query("\n\t\tSELECT \n\t\t\tmemberName\n\t\tFROM {$db_prefix}members\n\t\tWHER memberName = '" . $_POST['newusername'] . "' LIMIT 1", __FILE__, __LINE__);
     $memCount = mysql_num_rows($result);
     if ($memCount > 0) {
         die('ERROR: Username is already in use!');
     }
     updateMemberData($context['user']['id'], array('memberName' => '"' . $_POST['newusername'] . '"'));
     return 'Successfully changed your username to ' . $_POST['newusername'];
 }
Esempio n. 8
0
 public function createUserHandle($email, $username, $password, $verified, $custom_register_fields, $profile, &$errors)
 {
     global $sourcedir, $context, $modSettings, $maintenance, $mmessage, $scripturl;
     checkSession();
     $_POST['emailActivate'] = true;
     if (empty($password)) {
         get_error('password cannot be empty');
     }
     if (!($maintenance == 0)) {
         get_error('Forum is in maintenance model or Tapatalk is disabled by forum administrator.');
     }
     if ($modSettings['registration_method'] == 0) {
         $register_mode = 'nothing';
     } else {
         if ($modSettings['registration_method'] == 1) {
             $register_mode = $verified ? 'nothing' : 'activation';
         } else {
             $register_mode = isset($modSettings['auto_approval_tp_user']) && $modSettings['auto_approval_tp_user'] && $verified ? 'nothing' : 'approval';
         }
     }
     $email = htmltrim__recursive(str_replace(array("\n", "\r"), '', $email));
     $username = htmltrim__recursive(str_replace(array("\n", "\r"), '', $username));
     $password = htmltrim__recursive(str_replace(array("\n", "\r"), '', $password));
     $group = 0;
     if ($register_mode == 'nothing' && isset($modSettings['tp_iar_usergroup_assignment'])) {
         $group = $modSettings['tp_iar_usergroup_assignment'];
     }
     $regOptions = array('interface' => $register_mode == 'approval' ? 'guest' : 'admin', 'username' => $username, 'email' => $email, 'password' => $password, 'password_check' => $password, 'check_reserved_name' => true, 'check_password_strength' => true, 'check_email_ban' => false, 'send_welcome_email' => isset($_POST['emailPassword']) || empty($password), 'require' => $register_mode, 'memberGroup' => (int) $group);
     define('mobi_register', 1);
     require_once $sourcedir . '/Subs-Members.php';
     $memberID = registerMember($regOptions);
     if (!empty($memberID)) {
         $context['new_member'] = array('id' => $memberID, 'name' => $username, 'href' => $scripturl . '?action=profile;u=' . $memberID, 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $memberID . '">' . $username . '</a>');
         $context['registration_done'] = sprintf($txt['admin_register_done'], $context['new_member']['link']);
         //update profile
         if (isset($profile) && !empty($profile) && is_array($profile)) {
             $profile_vars = array('avatar' => $profile['avatar_url']);
             updateMemberData($memberID, $profile_vars);
         }
         return get_user_by_name_or_email($username, false);
     }
     return null;
 }
Esempio n. 9
0
/**
 * Count the mentions of the current user
 * callback for createList in action_list of Mentions_Controller
 *
 * @package Mentions
 * @param bool $all : if true counts all the mentions, otherwise only the unread
 * @param string[]|string $type : the type of the mention can be a string or an array of strings.
 * @param string|null $id_member : the id of the member the counts are for, defaults to user_info['id']
 */
function countUserMentions($all = false, $type = '', $id_member = null)
{
    global $user_info;
    static $counts;
    $db = database();
    $id_member = $id_member === null ? $user_info['id'] : (int) $id_member;
    if (isset($counts[$id_member])) {
        return $counts[$id_member];
    }
    $request = $db->query('', '
		SELECT COUNT(*)
		FROM {db_prefix}log_mentions as mtn
		WHERE mtn.id_member = {int:current_user}
			AND mtn.status IN ({array_int:status})' . (empty($type) ? '' : (is_array($type) ? '
			AND mtn.mention_type IN ({array_string:current_type})' : '
			AND mtn.mention_type = {string:current_type}')), array('current_user' => $id_member, 'current_type' => $type, 'status' => $all ? array(0, 1) : array(0)));
    list($counts[$id_member]) = $db->fetch_row($request);
    $db->free_result($request);
    // Counts as maintenance! :P
    if ($all === false && empty($type)) {
        updateMemberData($id_member, array('mentions' => $counts[$id_member]));
    }
    return $counts[$id_member];
}
Esempio n. 10
0
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');
}
Esempio n. 11
0
/**
 * 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);
}
Esempio n. 12
0
/**
 * 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('~&amp;#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', htmlspecialchars($moderator_string), ENT_QUOTES), array('&quot;' => '"'));
                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']) ? '' : '&quot;' . implode('&quot;, &quot;', $context['group']['moderators']) . '&quot;';
    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');
}
Esempio n. 13
0
function writeLog($force = false)
{
    global $user_info, $user_settings, $context, $modSettings, $settings, $topic, $board, $smcFunc, $sourcedir;
    // If we are showing who is viewing a topic, let's see if we are, and force an update if so - to make it accurate.
    if (!empty($settings['display_who_viewing']) && ($topic || $board)) {
        // Take the opposite approach!
        $force = true;
        // Don't update for every page - this isn't wholly accurate but who cares.
        if ($topic) {
            if (isset($_SESSION['last_topic_id']) && $_SESSION['last_topic_id'] == $topic) {
                $force = false;
            }
            $_SESSION['last_topic_id'] = $topic;
        }
    }
    // Are they a spider we should be tracking? Mode = 1 gets tracked on its spider check...
    if (!empty($user_info['possibly_robot']) && !empty($modSettings['spider_mode']) && $modSettings['spider_mode'] > 1) {
        require_once $sourcedir . '/ManageSearchEngines.php';
        logSpider();
    }
    // Don't mark them as online more than every so often.
    if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - 8 && !$force) {
        return;
    }
    if (!empty($modSettings['who_enabled'])) {
        $serialized = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
        // In the case of a dlattach action, session_var may not be set.
        if (!isset($context['session_var'])) {
            $context['session_var'] = $_SESSION['session_var'];
        }
        unset($serialized['sesc'], $serialized[$context['session_var']]);
        $serialized = serialize($serialized);
    } else {
        $serialized = '';
    }
    // Guests use 0, members use their session ID.
    $session_id = $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id();
    // Grab the last all-of-SMF-specific log_online deletion time.
    $do_delete = cache_get_data('log_online-update', 30) < time() - 30;
    // If the last click wasn't a long time ago, and there was a last click...
    if (!empty($_SESSION['log_time']) && $_SESSION['log_time'] >= time() - $modSettings['lastActive'] * 20) {
        if ($do_delete) {
            $smcFunc['db_query']('delete_log_online_interval', '
				DELETE FROM {db_prefix}log_online
				WHERE log_time < {int:log_time}
					AND session != {string:session}', array('log_time' => time() - $modSettings['lastActive'] * 60, 'session' => $session_id));
            // Cache when we did it last.
            cache_put_data('log_online-update', time(), 30);
        }
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}log_online
			SET log_time = {int:log_time}, ip = IFNULL(INET_ATON({string:ip}), 0), url = {string:url}
			WHERE session = {string:session}', array('log_time' => time(), 'ip' => $user_info['ip'], 'url' => $serialized, 'session' => $session_id));
        // Guess it got deleted.
        if ($smcFunc['db_affected_rows']() == 0) {
            $_SESSION['log_time'] = 0;
        }
    } else {
        $_SESSION['log_time'] = 0;
    }
    // Otherwise, we have to delete and insert.
    if (empty($_SESSION['log_time'])) {
        if ($do_delete || !empty($user_info['id'])) {
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}log_online
				WHERE ' . ($do_delete ? 'log_time < {int:log_time}' : '') . ($do_delete && !empty($user_info['id']) ? ' OR ' : '') . (empty($user_info['id']) ? '' : 'id_member = {int:current_member}'), array('current_member' => $user_info['id'], 'log_time' => time() - $modSettings['lastActive'] * 60));
        }
        $smcFunc['db_insert']($do_delete ? 'ignore' : 'replace', '{db_prefix}log_online', array('session' => 'string', 'id_member' => 'int', 'id_spider' => 'int', 'log_time' => 'int', 'ip' => 'raw', 'url' => 'string'), array($session_id, $user_info['id'], empty($_SESSION['id_robot']) ? 0 : $_SESSION['id_robot'], time(), 'IFNULL(INET_ATON(\'' . $user_info['ip'] . '\'), 0)', $serialized), array('session'));
    }
    // Mark your session as being logged.
    $_SESSION['log_time'] = time();
    // Well, they are online now.
    if (empty($_SESSION['timeOnlineUpdated'])) {
        $_SESSION['timeOnlineUpdated'] = time();
    }
    // Set their login time, if not already done within the last minute.
    if (SMF != 'SSI' && !empty($user_info['last_login']) && $user_info['last_login'] < time() - 60) {
        // Don't count longer than 15 minutes.
        if (time() - $_SESSION['timeOnlineUpdated'] > 60 * 15) {
            $_SESSION['timeOnlineUpdated'] = time();
        }
        $user_settings['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
        updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP'], 'total_time_logged_in' => $user_settings['total_time_logged_in']));
        if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
            cache_put_data('user_settings-' . $user_info['id'], $user_settings, 60);
        }
        $user_info['total_time_logged_in'] += time() - $_SESSION['timeOnlineUpdated'];
        $_SESSION['timeOnlineUpdated'] = time();
    }
}
Esempio n. 14
0
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');
}
 /**
  * Actually delete an account.
  */
 public function action_deleteaccount2()
 {
     global $user_info, $context, $cur_profile, $user_profile, $modSettings;
     // Try get more time...
     @set_time_limit(600);
     // @todo Add a way to delete pms as well?
     if (!$context['user']['is_owner']) {
         isAllowedTo('profile_remove_any');
     } elseif (!allowedTo('profile_remove_any')) {
         isAllowedTo('profile_remove_own');
     }
     checkSession();
     $memID = currentMemberID();
     // Check we got here as we should have!
     if ($cur_profile != $user_profile[$memID]) {
         fatal_lang_error('no_access', false);
     }
     $old_profile =& $cur_profile;
     // This file is needed for our utility functions.
     require_once SUBSDIR . '/Members.subs.php';
     // Too often, people remove/delete their own only administrative account.
     if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1) {
         // Are you allowed to administrate the forum, as they are?
         isAllowedTo('admin_forum');
         $another = isAnotherAdmin($memID);
         if (empty($another)) {
             fatal_lang_error('at_least_one_admin', 'critical');
         }
     }
     // Do you have permission to delete others profiles, or is that your profile you wanna delete?
     if ($memID != $user_info['id']) {
         isAllowedTo('profile_remove_any');
         // Now, have you been naughty and need your posts deleting?
         // @todo Should this check board permissions?
         if ($_POST['remove_type'] != 'none' && allowedTo('moderate_forum')) {
             // Include subs/Topic.subs.php - essential for this type of work!
             require_once SUBSDIR . '/Topic.subs.php';
             require_once SUBSDIR . '/Messages.subs.php';
             // First off we delete any topics the member has started - if they wanted topics being done.
             if ($_POST['remove_type'] == 'topics') {
                 // Fetch all topics started by this user.
                 $topicIDs = topicsStartedBy($memID);
                 // Actually remove the topics.
                 // @todo This needs to check permissions, but we'll let it slide for now because of moderate_forum already being had.
                 removeTopics($topicIDs);
             }
             // Now delete the remaining messages.
             removeNonTopicMessages($memID);
         }
         // Only delete this poor member's account if they are actually being booted out of camp.
         if (isset($_POST['deleteAccount'])) {
             deleteMembers($memID);
         }
     } elseif (!empty($modSettings['approveAccountDeletion']) && !allowedTo('moderate_forum')) {
         // Setup their account for deletion ;)
         updateMemberData($memID, array('is_activated' => 4));
         // Another account needs approval...
         updateSettings(array('unapprovedMembers' => true), true);
     } else {
         deleteMembers($memID);
         require_once CONTROLLERDIR . '/Auth.controller.php';
         $controller = new Auth_Controller();
         $controller->action_logout(true);
         redirectexit();
     }
 }
Esempio n. 16
0
/**
 * Generates a random password for a user and emails it to them.
 * - called by Profile.php when changing someone's username.
 * - checks the validity of the new username.
 * - generates and sets a new password for the given user.
 * - mails the new password to the email address of the user.
 * - if username is not set, only a new password is generated and sent.
 *
 * @param int $memID
 * @param string $username = null
 */
function resetPassword($memID, $username = null)
{
    global $scripturl, $context, $txt, $sourcedir, $modSettings, $smcFunc, $language;
    // Language... and a required file.
    loadLanguage('Login');
    require_once $sourcedir . '/Subs-Post.php';
    // Get some important details.
    $request = $smcFunc['db_query']('', '
		SELECT member_name, email_address, lngfile
		FROM {db_prefix}members
		WHERE id_member = {int:id_member}', array('id_member' => $memID));
    list($user, $email, $lngfile) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    if ($username !== null) {
        $old_user = $user;
        $user = trim($username);
    }
    // Generate a random password.
    $newPassword = substr(preg_replace('/\\W/', '', md5(mt_rand())), 0, 10);
    $newPassword_sha1 = sha1(strtolower($user) . $newPassword);
    // Do some checks on the username if needed.
    if ($username !== null) {
        validateUsername($memID, $user);
        // Update the database...
        updateMemberData($memID, array('member_name' => $user, 'passwd' => $newPassword_sha1));
    } else {
        updateMemberData($memID, array('passwd' => $newPassword_sha1));
    }
    call_integration_hook('integrate_reset_pass', array($old_user, $user, $newPassword));
    $replacements = array('USERNAME' => $user, 'PASSWORD' => $newPassword);
    $emaildata = loadEmailTemplate('change_password', $replacements, empty($lngfile) || empty($modSettings['userLanguage']) ? $language : $lngfile);
    // Send them the email informing them of the change - then we're done!
    sendmail($email, $emaildata['subject'], $emaildata['body'], null, null, false, 0);
}
Esempio n. 17
0
/**
 * @param $memID	int member ID
 * 
 * show the settings to customize opt-outs for activity entries and notifications
 * to receive.
 * 
 * todo: we need to find a way to filter out notifications that are for
 * admins/mods only. probably needs a db scheme change...
 */
function showActivitiesProfileSettings($memID)
{
    global $modSettings, $context, $user_info, $txt, $user_profile, $scripturl;
    loadLanguage('Activities-Profile');
    if (empty($modSettings['astream_active']) || $user_info['id'] != $memID && !$user_info['is_admin']) {
        fatal_lang_error('no_access');
    }
    Eos_Smarty::getConfigInstance()->registerHookTemplate('profile_content_area', 'profile/astream_settings');
    $context['submiturl'] = $scripturl . '?action=profile;area=activities;sa=settings;save;u=' . $memID;
    $context['page_title'] = $txt['showActivities'] . ' - ' . $user_profile[$memID]['real_name'];
    $context[$context['profile_menu_name']]['tab_data'] = array('title' => $txt['showActivitiesSettings'], 'description' => $txt['showActivitiesSettings_desc'], 'tabs' => array());
    $result = smf_db_query('SELECT * FROM {db_prefix}activity_types ORDER BY id_type ASC');
    if ($user_info['id'] == $memID) {
        $my_act_optout = empty($user_info['act_optout']) ? array(0) : explode(',', $user_info['act_optout']);
        $my_notify_optout = empty($user_info['notify_optout']) ? array(0) : explode(',', $user_info['notify_optout']);
    } else {
        loadMemberData($memID, false, 'minimal');
        $my_act_optout = empty($user_profile[$memID]['act_optout']) ? array(0) : explode(',', $user_profile[$memID]['act_optout']);
        $my_notify_optout = empty($user_profile[$memID]['notify_optout']) ? array(0) : explode(',', $user_profile[$memID]['notify_optout']);
    }
    $context['activity_types'] = array();
    while ($row = mysql_fetch_assoc($result)) {
        $context['activity_types'][] = array('id' => $row['id_type'], 'shortdesc' => $row['id_desc'], 'longdesc_act' => $txt['actdesc_' . trim($row['id_desc'])], 'longdesc_not' => isset($txt['ndesc_' . trim($row['id_desc'])]) ? $txt['ndesc_' . trim($row['id_desc'])] : '', 'act_optout' => in_array($row['id_type'], $my_act_optout), 'notify_optout' => in_array($row['id_type'], $my_notify_optout));
    }
    mysql_free_result($result);
    if (isset($_GET['save'])) {
        $new_not_optout = array();
        $new_act_optout = array();
        $update_array = array();
        foreach ($context['activity_types'] as $t) {
            $_id = trim($t['id']);
            if (!empty($t['longdesc_act']) && (!isset($_REQUEST['act_check_' . $_id]) || empty($_REQUEST['act_check_' . $_id]))) {
                $new_act_optout[] = $_id;
            }
            if (!empty($t['longdesc_not']) && (!isset($_REQUEST['not_check_' . $_id]) || empty($_REQUEST['not_check_' . $_id]))) {
                $new_not_optout[] = $_id;
            }
        }
        //if(count(array_unique($new_act_optout)) > 0)
        $update_array['act_optout'] = implode(',', array_unique($new_act_optout));
        //if(count(array_unique($new_not_optout)) > 0)
        $update_array['notify_optout'] = implode(',', array_unique($new_not_optout));
        if (count($update_array)) {
            updateMemberData($memID, $update_array);
        }
        redirectexit($scripturl . '?action=profile;area=activities;sa=settings;u=' . $memID);
    }
}
Esempio n. 18
0
function BuddyListToggle()
{
    global $user_info;
    checkSession('get');
    isAllowedTo('profile_identity_own');
    is_not_guest();
    if (empty($_REQUEST['u'])) {
        fatal_lang_error('no_access', false);
    }
    $_REQUEST['u'] = (int) $_REQUEST['u'];
    // Remove if it's already there...
    if (in_array($_REQUEST['u'], $user_info['buddies'])) {
        $user_info['buddies'] = array_diff($user_info['buddies'], array($_REQUEST['u']));
    } elseif ($user_info['id'] != $_REQUEST['u']) {
        $user_info['buddies'][] = (int) $_REQUEST['u'];
    }
    // Update the settings.
    updateMemberData($user_info['id'], array('buddy_list' => implode(',', $user_info['buddies'])));
    // Redirect back to the profile
    redirectexit('action=profile;u=' . $_REQUEST['u']);
}
Esempio n. 19
0
function loadUserSettings()
{
    global $modSettings, $user_settings, $sourcedir, $smcFunc;
    global $cookiename, $user_info, $language;
    // Check first the integration, then the cookie, and last the session.
    if (count($integration_ids = call_integration_hook('integrate_verify_user')) > 0) {
        $id_member = 0;
        foreach ($integration_ids as $integration_id) {
            $integration_id = (int) $integration_id;
            if ($integration_id > 0) {
                $id_member = $integration_id;
                $already_verified = true;
                break;
            }
        }
    } else {
        $id_member = 0;
    }
    if (empty($id_member) && isset($_COOKIE[$cookiename])) {
        // Fix a security hole in PHP 4.3.9 and below...
        if (preg_match('~^a:[34]:\\{i:0;(i:\\d{1,6}|s:[1-8]:"\\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\\d{1,14};(i:3;i:\\d;)?\\}$~i', $_COOKIE[$cookiename]) == 1) {
            list($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
            $id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
        } else {
            $id_member = 0;
        }
    } elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA']))) {
        // !!! Perhaps we can do some more checking on this, such as on the first octet of the IP?
        list($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
        $id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
    }
    // Only load this stuff if the user isn't a guest.
    if ($id_member != 0) {
        // Is the member data cached?
        if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $id_member, 60)) == null) {
            $request = $smcFunc['db_query']('', '
				SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
				FROM {db_prefix}members AS mem
					LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
				WHERE mem.id_member = {int:id_member}
				LIMIT 1', array('id_member' => $id_member));
            $user_settings = $smcFunc['db_fetch_assoc']($request);
            $smcFunc['db_free_result']($request);
            if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
                cache_put_data('user_settings-' . $id_member, $user_settings, 60);
            }
        }
        // Did we find 'im?  If not, junk it.
        if (!empty($user_settings)) {
            // As much as the password should be right, we can assume the integration set things up.
            if (!empty($already_verified) && $already_verified === true) {
                $check = true;
            } elseif (strlen($password) == 40) {
                $check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
            } else {
                $check = false;
            }
            // Wrong password or not activated - either way, you're going nowhere.
            $id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
        } else {
            $id_member = 0;
        }
        // If we no longer have the member maybe they're being all hackey, stop brute force!
        if (!$id_member) {
            require_once $sourcedir . '/LogInOut.php';
            validatePasswordFlood(!empty($user_settings['id_member']) ? $user_settings['id_member'] : $id_member, !empty($user_settings['passwd_flood']) ? $user_settings['passwd_flood'] : false, $id_member != 0);
        }
    }
    // Found 'im, let's set up the variables.
    if ($id_member != 0) {
        // Let's not update the last visit time in these cases...
        // 1. SSI doesn't count as visiting the forum.
        // 2. RSS feeds and XMLHTTP requests don't count either.
        // 3. If it was set within this session, no need to set it again.
        // 4. New session, yet updated < five hours ago? Maybe cache can help.
        if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['id_msg_last_visit']) && (empty($modSettings['cache_enable']) || ($_SESSION['id_msg_last_visit'] = cache_get_data('user_last_visit-' . $id_member, 5 * 3600)) === null)) {
            // Do a quick query to make sure this isn't a mistake.
            $result = $smcFunc['db_query']('', '
				SELECT poster_time
				FROM {db_prefix}messages
				WHERE id_msg = {int:id_msg}
				LIMIT 1', array('id_msg' => $user_settings['id_msg_last_visit']));
            list($visitTime) = $smcFunc['db_fetch_row']($result);
            $smcFunc['db_free_result']($result);
            $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
            // If it was *at least* five hours ago...
            if ($visitTime < time() - 5 * 3600) {
                updateMemberData($id_member, array('id_msg_last_visit' => (int) $modSettings['maxMsgID'], 'last_login' => time(), 'member_ip' => $_SERVER['REMOTE_ADDR'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
                $user_settings['last_login'] = time();
                if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
                    cache_put_data('user_settings-' . $id_member, $user_settings, 60);
                }
                if (!empty($modSettings['cache_enable'])) {
                    cache_put_data('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
                }
            }
        } elseif (empty($_SESSION['id_msg_last_visit'])) {
            $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
        }
        $username = $user_settings['member_name'];
        if (empty($user_settings['additional_groups'])) {
            $user_info = array('groups' => array($user_settings['id_group'], $user_settings['id_post_group']));
        } else {
            $user_info = array('groups' => array_merge(array($user_settings['id_group'], $user_settings['id_post_group']), explode(',', $user_settings['additional_groups'])));
        }
        // Because history has proven that it is possible for groups to go bad - clean up in case.
        foreach ($user_info['groups'] as $k => $v) {
            $user_info['groups'][$k] = (int) $v;
        }
        // This is a logged in user, so definitely not a spider.
        $user_info['possibly_robot'] = false;
    } else {
        // This is what a guest's variables should be.
        $username = '';
        $user_info = array('groups' => array(-1));
        $user_settings = array();
        if (isset($_COOKIE[$cookiename])) {
            $_COOKIE[$cookiename] = '';
        }
        // Do we perhaps think this is a search robot? Check every five minutes just in case...
        if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300)) {
            require_once $sourcedir . '/ManageSearchEngines.php';
            $user_info['possibly_robot'] = SpiderCheck();
        } elseif (!empty($modSettings['spider_mode'])) {
            $user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
        } else {
            $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
            $user_info['possibly_robot'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === false || strpos($ci_user_agent, 'googlebot') !== false || strpos($ci_user_agent, 'slurp') !== false || strpos($ci_user_agent, 'crawl') !== false;
        }
    }
    // Set up the $user_info array.
    $user_info += array('id' => $id_member, 'username' => $username, 'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '', 'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '', 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '', 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'], 'is_guest' => $id_member == 0, 'is_admin' => in_array(1, $user_info['groups']), 'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'], 'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'], 'ip' => $_SERVER['REMOTE_ADDR'], 'ip2' => $_SERVER['BAN_CHECK_IP'], 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'], 'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'], 'time_offset' => empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'], 'avatar' => array('url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '', 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'], 'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1, 'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0), 'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '', 'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'], 'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'], 'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'], 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(), 'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(), 'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(), 'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0, 'permissions' => array());
    $user_info['groups'] = array_unique($user_info['groups']);
    // Make sure that the last item in the ignore boards array is valid.  If the list was too long it could have an ending comma that could cause problems.
    if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1])) {
        unset($user_info['ignoreboards'][$tmp]);
    }
    // Do we have any languages to validate this?
    if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language']))) {
        $languages = getLanguages();
    }
    // Allow the user to change their language if its valid.
    if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')])) {
        $user_info['language'] = strtr($_GET['language'], './\\:', '____');
        $_SESSION['language'] = $user_info['language'];
    } elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')])) {
        $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
    }
    // Just build this here, it makes it easier to change/use - administrators can see all boards.
    if ($user_info['is_admin']) {
        $user_info['query_see_board'] = '1=1';
    } else {
        $user_info['query_see_board'] = '(FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0' . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
    }
    // Build the list of boards they WANT to see.
    // This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
    // If they aren't ignoring any boards then they want to see all the boards they can see
    if (empty($user_info['ignoreboards'])) {
        $user_info['query_wanna_see_board'] = $user_info['query_see_board'];
    } else {
        $user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
    }
}
function ModerationSettings()
{
    global $context, $smcFunc, $txt, $sourcedir, $scripturl, $user_settings, $user_info;
    // Some useful context stuff.
    loadTemplate('ModerationCenter');
    $context['page_title'] = $txt['mc_settings'];
    $context['sub_template'] = 'moderation_settings';
    // What blocks can this user see?
    $context['homepage_blocks'] = array('n' => $txt['mc_prefs_latest_news'], 'p' => $txt['mc_notes']);
    if ($context['can_moderate_groups']) {
        $context['homepage_blocks']['g'] = $txt['mc_group_requests'];
    }
    if ($context['can_moderate_boards']) {
        $context['homepage_blocks']['r'] = $txt['mc_reported_posts'];
        $context['homepage_blocks']['w'] = $txt['mc_watched_users'];
    }
    // Does the user have any settings yet?
    if (empty($user_settings['mod_prefs'])) {
        $mod_blocks = 'n' . ($context['can_moderate_boards'] ? 'wr' : '') . ($context['can_moderate_groups'] ? 'g' : '');
        $pref_binary = 5;
        $show_reports = 1;
    } else {
        list($show_reports, $mod_blocks, $pref_binary) = explode('|', $user_settings['mod_prefs']);
    }
    // Are we saving?
    if (isset($_POST['save'])) {
        checkSession('post');
        /* Current format of mod_prefs is:
        			x|ABCD|yyy
        
        			WHERE:
        				x = Show report count on forum header.
        				ABCD = Block indexes to show on moderation main page.
        				yyy = Integer with the following bit status:
        					- yyy & 1 = Always notify on reports.
        					- yyy & 2 = Notify on reports for moderators only.
        					- yyy & 4 = Notify about posts awaiting approval.
        		*/
        // Do blocks first!
        $mod_blocks = '';
        if (!empty($_POST['mod_homepage'])) {
            foreach ($_POST['mod_homepage'] as $k => $v) {
                // Make sure they can add this...
                if (isset($context['homepage_blocks'][$k])) {
                    $mod_blocks .= $k;
                }
            }
        }
        // Now check other options!
        $pref_binary = 0;
        if ($context['can_moderate_approvals'] && !empty($_POST['mod_notify_approval'])) {
            $pref_binary |= 4;
        }
        if ($context['can_moderate_boards']) {
            if (!empty($_POST['mod_notify_report'])) {
                $pref_binary |= $_POST['mod_notify_report'] == 2 ? 1 : 2;
            }
            $show_reports = !empty($_POST['mod_show_reports']) ? 1 : 0;
        }
        // Put it all together.
        $mod_prefs = $show_reports . '|' . $mod_blocks . '|' . $pref_binary;
        updateMemberData($user_info['id'], array('mod_prefs' => $mod_prefs));
    }
    // What blocks does the user currently have selected?
    $context['mod_settings'] = array('show_reports' => $show_reports, 'notify_report' => $pref_binary & 2 ? 1 : ($pref_binary & 1 ? 2 : 0), 'notify_approval' => $pref_binary & 4, 'user_blocks' => str_split($mod_blocks));
}
Esempio n. 21
0
function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
{
    global $smcFunc, $cookiename, $sourcedir;
    // As this is only brute protection, we allow 5 attempts every 10 seconds.
    // Destroy any session or cookie data about this member, as they validated wrong.
    require_once $sourcedir . '/Subs-Auth.php';
    setLoginCookie(-3600, 0);
    if (isset($_SESSION['login_' . $cookiename])) {
        unset($_SESSION['login_' . $cookiename]);
    }
    // We need a member!
    if (!$id_member) {
        // Redirect back!
        redirectexit();
        // Probably not needed, but still make sure...
        fatal_lang_error('no_access', false);
    }
    // Right, have we got a flood value?
    if ($password_flood_value !== false) {
        @(list($time_stamp, $number_tries) = explode('|', $password_flood_value));
    }
    // Timestamp or number of tries invalid?
    if (empty($number_tries) || empty($time_stamp)) {
        $number_tries = 0;
        $time_stamp = time();
    }
    // They've failed logging in already
    if (!empty($number_tries)) {
        // Give them less chances if they failed before
        $number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;
        // They are trying too fast, make them wait longer
        if ($time_stamp < time() - 10) {
            $time_stamp = time();
        }
    }
    $number_tries++;
    // Broken the law?
    if ($number_tries > 5) {
        fatal_lang_error('login_threshold_brute_fail', 'critical');
    }
    // Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
    updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
}
Esempio n. 22
0
function ModifyKarma()
{
    global $modSettings, $txt, $user_info, $topic, $smcFunc, $context;
    // If the mod is disabled, show an error.
    if (empty($modSettings['karmaMode'])) {
        fatal_lang_error('feature_disabled', true);
    }
    // If you're a guest or can't do this, blow you off...
    is_not_guest();
    isAllowedTo('karma_edit');
    checkSession('get');
    // If you don't have enough posts, tough luck.
    // !!! Should this be dropped in favor of post group permissions?  Should this apply to the member you are smiting/applauding?
    if (!$user_info['is_admin'] && $user_info['posts'] < $modSettings['karmaMinPosts']) {
        fatal_lang_error('not_enough_posts_karma', true, array($modSettings['karmaMinPosts']));
    }
    // And you can't modify your own, punk! (use the profile if you need to.)
    if (empty($_REQUEST['uid']) || (int) $_REQUEST['uid'] == $user_info['id']) {
        fatal_lang_error('cant_change_own_karma', false);
    }
    // The user ID _must_ be a number, no matter what.
    $_REQUEST['uid'] = (int) $_REQUEST['uid'];
    // Applauding or smiting?
    $dir = $_REQUEST['sa'] != 'applaud' ? -1 : 1;
    // Delete any older items from the log. (karmaWaitTime is by hour.)
    smf_db_query('
		DELETE FROM {db_prefix}log_karma
		WHERE {int:current_time} - log_time > {int:wait_time}', array('wait_time' => (int) ($modSettings['karmaWaitTime'] * 3600), 'current_time' => time()));
    // Start off with no change in karma.
    $action = 0;
    // Not an administrator... or one who is restricted as well.
    if (!empty($modSettings['karmaTimeRestrictAdmins']) || !allowedTo('moderate_forum')) {
        // Find out if this user has done this recently...
        $request = smf_db_query('
			SELECT action
			FROM {db_prefix}log_karma
			WHERE id_target = {int:id_target}
				AND id_executor = {int:current_member}
			LIMIT 1', array('current_member' => $user_info['id'], 'id_target' => $_REQUEST['uid']));
        if (mysql_num_rows($request) > 0) {
            list($action) = mysql_fetch_row($request);
        }
        mysql_free_result($request);
    }
    // They haven't, not before now, anyhow.
    if (empty($action) || empty($modSettings['karmaWaitTime'])) {
        // Put it in the log.
        smf_db_insert('replace', '{db_prefix}log_karma', array('action' => 'int', 'id_target' => 'int', 'id_executor' => 'int', 'log_time' => 'int'), array($dir, $_REQUEST['uid'], $user_info['id'], time()), array('id_target', 'id_executor'));
        // Change by one.
        updateMemberData($_REQUEST['uid'], array($dir == 1 ? 'karma_good' : 'karma_bad' => '+'));
    } else {
        // If you are gonna try to repeat.... don't allow it.
        if ($action == $dir) {
            fatal_lang_error('karma_wait_time', false, array($modSettings['karmaWaitTime'], $txt['hours']));
        }
        // You decided to go back on your previous choice?
        smf_db_query('
			UPDATE {db_prefix}log_karma
			SET action = {int:action}, log_time = {int:current_time}
			WHERE id_target = {int:id_target}
				AND id_executor = {int:current_member}', array('current_member' => $user_info['id'], 'action' => $dir, 'current_time' => time(), 'id_target' => $_REQUEST['uid']));
        // It was recently changed the OTHER way... so... reverse it!
        if ($dir == 1) {
            updateMemberData($_REQUEST['uid'], array('karma_good' => '+', 'karma_bad' => '-'));
        } else {
            updateMemberData($_REQUEST['uid'], array('karma_bad' => '+', 'karma_good' => '-'));
        }
    }
    // Figure out where to go back to.... the topic?
    if (!empty($topic)) {
        redirectexit('topic=' . $topic . '.' . $_REQUEST['start'] . '#msg' . (int) $_REQUEST['m']);
    } elseif (isset($_REQUEST['f'])) {
        redirectexit('action=pm;f=' . $_REQUEST['f'] . ';start=' . $_REQUEST['start'] . (isset($_REQUEST['l']) ? ';l=' . (int) $_REQUEST['l'] : '') . (isset($_REQUEST['pm']) ? '#' . (int) $_REQUEST['pm'] : ''));
    } else {
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"', $context['right_to_left'] ? ' dir="rtl"' : '', '>
	<head>
		<title>...</title>
		<script type="text/javascript"><!-- // --><![CDATA[
			history.go(-1);
		// ]]></script>
	</head>
	<body>&laquo;</body>
</html>';
        obExit(false);
    }
}
Esempio n. 23
0
function createPost(&$msgOptions, &$topicOptions, &$posterOptions)
{
    global $db_prefix, $user_info, $ID_MEMBER, $txt, $modSettings;
    // Set optional parameters to the default value.
    $msgOptions['icon'] = empty($msgOptions['icon']) ? 'xx' : $msgOptions['icon'];
    $msgOptions['smileys_enabled'] = !empty($msgOptions['smileys_enabled']);
    $msgOptions['attachments'] = empty($msgOptions['attachments']) ? array() : $msgOptions['attachments'];
    $topicOptions['id'] = empty($topicOptions['id']) ? 0 : (int) $topicOptions['id'];
    $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;
    $posterOptions['id'] = empty($posterOptions['id']) ? 0 : (int) $posterOptions['id'];
    $posterOptions['ip'] = empty($posterOptions['ip']) ? $user_info['ip2'] : $posterOptions['ip'];
    // If nothing was filled in as name/e-mail address, try the member table.
    if (!isset($posterOptions['name']) || $posterOptions['name'] == '' || empty($posterOptions['email']) && !empty($posterOptions['id'])) {
        if (empty($posterOptions['id'])) {
            $posterOptions['id'] = 0;
            $posterOptions['name'] = $txt[28];
            $posterOptions['email'] = '';
        } elseif ($posterOptions['id'] != $ID_MEMBER) {
            $request = db_query("\n\t\t\t\tSELECT memberName, emailAddress\n\t\t\t\tFROM {$db_prefix}members\n\t\t\t\tWHERE ID_MEMBER = {$posterOptions['id']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            // Couldn't find the current poster?
            if (mysql_num_rows($request) == 0) {
                trigger_error('createPost(): Invalid member id ' . $posterOptions['id'], E_USER_NOTICE);
                $posterOptions['id'] = 0;
                $posterOptions['name'] = $txt[28];
                $posterOptions['email'] = '';
            } else {
                list($posterOptions['name'], $posterOptions['email']) = mysql_fetch_row($request);
            }
            mysql_free_result($request);
        } else {
            $posterOptions['name'] = $user_info['name'];
            $posterOptions['email'] = $user_info['email'];
        }
        $posterOptions['email'] = addslashes($posterOptions['email']);
    }
    // It's do or die time: forget any user aborts!
    $previous_ignore_user_abort = ignore_user_abort(true);
    $new_topic = empty($topicOptions['id']);
    // Insert the post.
    db_query("\n\t\tINSERT INTO {$db_prefix}messages\n\t\t\t(ID_BOARD, ID_TOPIC, ID_MEMBER, subject, body, posterName, posterEmail, posterTime,\n\t\t\tposterIP, smileysEnabled, modifiedName, icon)\n\t\tVALUES ({$topicOptions['board']}, {$topicOptions['id']}, {$posterOptions['id']}, SUBSTRING('{$msgOptions['subject']}', 1, 255), SUBSTRING('{$msgOptions['body']}', 1, 65534), SUBSTRING('{$posterOptions['name']}', 1, 255), SUBSTRING('{$posterOptions['email']}', 1, 255), " . time() . ",\n\t\t\tSUBSTRING('{$posterOptions['ip']}', 1, 255), " . ($msgOptions['smileys_enabled'] ? '1' : '0') . ", '', SUBSTRING('{$msgOptions['icon']}', 1, 16))", __FILE__, __LINE__);
    $msgOptions['id'] = db_insert_id();
    // Something went wrong creating the message...
    if (empty($msgOptions['id'])) {
        return false;
    }
    // Fix the attachments.
    if (!empty($msgOptions['attachments'])) {
        db_query("\n\t\t\tUPDATE {$db_prefix}attachments\n\t\t\tSET ID_MSG = {$msgOptions['id']}\n\t\t\tWHERE ID_ATTACH IN (" . implode(', ', $msgOptions['attachments']) . ')', __FILE__, __LINE__);
    }
    // Insert a new topic (if the topicID was left empty.
    if ($new_topic) {
        db_query("\n\t\t\tINSERT INTO {$db_prefix}topics\n\t\t\t\t(ID_BOARD, ID_MEMBER_STARTED, ID_MEMBER_UPDATED, ID_FIRST_MSG, ID_LAST_MSG, locked, isSticky, numViews, ID_POLL)\n\t\t\tVALUES ({$topicOptions['board']}, {$posterOptions['id']}, {$posterOptions['id']}, {$msgOptions['id']}, {$msgOptions['id']},\n\t\t\t\t" . ($topicOptions['lock_mode'] === null ? '0' : $topicOptions['lock_mode']) . ', ' . ($topicOptions['sticky_mode'] === null ? '0' : $topicOptions['sticky_mode']) . ", 0, " . ($topicOptions['poll'] === null ? '0' : $topicOptions['poll']) . ')', __FILE__, __LINE__);
        $topicOptions['id'] = db_insert_id();
        // The topic couldn't be created for some reason.
        if (empty($topicOptions['id'])) {
            // We should delete the post that did work, though...
            db_query("\n\t\t\t\tDELETE FROM {$db_prefix}messages\n\t\t\t\tWHERE ID_MSG = {$msgOptions['id']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            return false;
        }
        // Fix the message with the topic.
        db_query("\n\t\t\tUPDATE {$db_prefix}messages\n\t\t\tSET ID_TOPIC = {$topicOptions['id']}\n\t\t\tWHERE ID_MSG = {$msgOptions['id']}\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        // There's been a new topic AND a new post today.
        trackStats(array('topics' => '+', 'posts' => '+'));
        updateStats('topic', true);
        updateStats('subject', $topicOptions['id'], $msgOptions['subject']);
    } else {
        // Update the number of replies and the lock/sticky status.
        db_query("\n\t\t\tUPDATE {$db_prefix}topics\n\t\t\tSET\n\t\t\t\tID_MEMBER_UPDATED = {$posterOptions['id']}, ID_LAST_MSG = {$msgOptions['id']},\n\t\t\t\tnumReplies = numReplies + 1" . ($topicOptions['lock_mode'] === null ? '' : ",\n\t\t\t\tlocked = {$topicOptions['lock_mode']}") . ($topicOptions['sticky_mode'] === null ? '' : ",\n\t\t\t\tisSticky = {$topicOptions['sticky_mode']}") . "\n\t\t\tWHERE ID_TOPIC = {$topicOptions['id']}\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        // One new post has been added today.
        trackStats(array('posts' => '+'));
    }
    // Creating is modifying...in a way.
    db_query("\n\t\tUPDATE {$db_prefix}messages\n\t\tSET ID_MSG_MODIFIED = {$msgOptions['id']}\n\t\tWHERE ID_MSG = {$msgOptions['id']}", __FILE__, __LINE__);
    // Increase the number of posts and topics on the board.
    db_query("\n\t\tUPDATE {$db_prefix}boards\n\t\tSET numPosts = numPosts + 1" . ($new_topic ? ', numTopics = numTopics + 1' : '') . "\n\t\tWHERE ID_BOARD = {$topicOptions['board']}\n\t\tLIMIT 1", __FILE__, __LINE__);
    // Mark inserted topic as read (only for the user calling this function).
    if (!empty($topicOptions['mark_as_read']) && !$user_info['is_guest']) {
        // Since it's likely they *read* it before replying, let's try an UPDATE first.
        if (!$new_topic) {
            db_query("\n\t\t\t\tUPDATE {$db_prefix}log_topics\n\t\t\t\tSET ID_MSG = {$msgOptions['id']} + 1\n\t\t\t\tWHERE ID_MEMBER = {$ID_MEMBER}\n\t\t\t\t\tAND ID_TOPIC = {$topicOptions['id']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            $flag = db_affected_rows() != 0;
        }
        if (empty($flag)) {
            db_query("\n\t\t\t\tREPLACE INTO {$db_prefix}log_topics\n\t\t\t\t\t(ID_TOPIC, ID_MEMBER, ID_MSG)\n\t\t\t\tVALUES ({$topicOptions['id']}, {$ID_MEMBER}, {$msgOptions['id']} + 1)", __FILE__, __LINE__);
        }
    }
    // If there's a custom search index, it needs updating...
    if (!empty($modSettings['search_custom_index_config'])) {
        //$index_settings = unserialize($modSettings['search_custom_index_config']);
        $inserts = '';
        foreach (text2words(stripslashes($msgOptions['body']), 4, true) as $word) {
            $inserts .= "({$word}, {$msgOptions['id']}),\n";
        }
        if (!empty($inserts)) {
            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" . substr($inserts, 0, -2), __FILE__, __LINE__);
        }
    }
    // Increase the post counter for the user that created the post.
    if (!empty($posterOptions['update_post_count']) && !empty($posterOptions['id'])) {
        // Are you the one that happened to create this post?
        if ($ID_MEMBER == $posterOptions['id']) {
            $user_info['posts']++;
        }
        updateMemberData($posterOptions['id'], array('posts' => '+'));
    }
    // They've posted, so they can make the view count go up one if they really want. (this is to keep views >= replies...)
    $_SESSION['last_read_topic'] = 0;
    // Better safe than sorry.
    if (isset($_SESSION['topicseen_cache'][$topicOptions['board']])) {
        $_SESSION['topicseen_cache'][$topicOptions['board']]--;
    }
    // Update all the stats so everyone knows about this new topic and message.
    updateStats('message', true, $msgOptions['id']);
    updateLastMessages($topicOptions['board'], $msgOptions['id']);
    // Alright, done now... we can abort now, I guess... at least this much is done.
    ignore_user_abort($previous_ignore_user_abort);
    // Success.
    return true;
}
Esempio n. 24
0
function loadUserSettings()
{
    global $modSettings, $user_settings, $sourcedir;
    global $cookiename, $user_info, $language, $context;
    // Check first the integration, then the cookie, and last the session.
    if (count($integration_ids = HookAPI::callHook('integrate_verify_user')) > 0) {
        $id_member = 0;
        foreach ($integration_ids as $integration_id) {
            $integration_id = (int) $integration_id;
            if ($integration_id > 0) {
                $id_member = $integration_id;
                $already_verified = true;
                break;
            }
        }
    } else {
        $id_member = 0;
    }
    if (empty($id_member) && isset($_COOKIE[$cookiename])) {
        // Fix a security hole in PHP 4.3.9 and below...
        if (preg_match('~^a:[34]:\\{i:0;(i:\\d{1,6}|s:[1-8]:"\\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\\d{1,14};(i:3;i:\\d;)?\\}$~i', $_COOKIE[$cookiename]) == 1) {
            list($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
            $id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
        } else {
            $id_member = 0;
        }
    } elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA']))) {
        // !!! Perhaps we can do some more checking on this, such as on the first octet of the IP?
        list($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
        $id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
    }
    // Only load this stuff if the user isn't a guest.
    $_reload = $_to_cache = false;
    if ($id_member != 0) {
        // do we have a notification to dismiss (mark as seen) with this request? (we can only mark one per request, but that should be sufficient)
        if (isset($_REQUEST['nmdismiss']) && (int) $_REQUEST['nmdismiss'] > 0) {
            smf_db_query('UPDATE {db_prefix}log_notifications SET unread = 0 WHERE id_member = {int:id_user} AND id_act = {int:idact}', array('id_user' => $id_member, 'idact' => (int) $_REQUEST['nmdismiss']));
            $_reload = $_to_cache = true;
        }
        // Is the member data cached?
        if ($modSettings['cache_enable'] < 2 || ($user_settings = CacheAPI::getCache('user_settings-' . $id_member, 600)) == null) {
            $request = smf_db_query('
				SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
				FROM {db_prefix}members AS mem
					LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
				WHERE mem.id_member = {int:id_member}
				LIMIT 1', array('id_member' => $id_member));
            $user_settings = mysql_fetch_assoc($request);
            mysql_free_result($request);
        }
        // Did we find 'im?  If not, junk it.
        if (!empty($user_settings)) {
            // As much as the password should be right, we can assume the integration set things up.
            if (!empty($already_verified) && $already_verified === true) {
                $check = true;
            } elseif (strlen($password) == 40) {
                $check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
            } else {
                $check = false;
            }
            // Wrong password or not activated - either way, you're going nowhere.
            $id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
        } else {
            $id_member = 0;
        }
        // If we no longer have the member maybe they're being all hackey, stop brute force!
        if (!$id_member) {
            require_once $sourcedir . '/LogInOut.php';
            validatePasswordFlood(!empty($user_settings['id_member']) ? $user_settings['id_member'] : $id_member, !empty($user_settings['passwd_flood']) ? $user_settings['passwd_flood'] : false, $id_member != 0);
        }
    }
    // Found 'im, let's set up the variables.
    if ($id_member != 0) {
        // Let's not update the last visit time in these cases...
        // 1. SSI doesn't count as visiting the forum.
        // 2. RSS feeds and XMLHTTP requests don't count either.
        // 3. If it was set within this session, no need to set it again.
        // 4. New session, yet updated < five hours ago? Maybe cache can help.
        if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['id_msg_last_visit']) && (empty($modSettings['cache_enable']) || ($_SESSION['id_msg_last_visit'] = CacheAPI::getCache('user_last_visit-' . $id_member, 5 * 3600)) === null)) {
            // Do a quick query to make sure this isn't a mistake.
            $result = smf_db_query('
				SELECT poster_time
				FROM {db_prefix}messages
				WHERE id_msg = {int:id_msg}
				LIMIT 1', array('id_msg' => $user_settings['id_msg_last_visit']));
            list($visitTime) = mysql_fetch_row($result);
            mysql_free_result($result);
            $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
            // If it was *at least* five hours ago...
            if ($visitTime < time() - 5 * 3600) {
                updateMemberData($id_member, array('id_msg_last_visit' => (int) $modSettings['maxMsgID'], 'last_login' => time(), 'member_ip' => $_SERVER['REMOTE_ADDR'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
                $user_settings['last_login'] = time();
                if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
                    CacheAPI::putCache('user_settings-' . $id_member, $user_settings, 60);
                }
                if (!empty($modSettings['cache_enable'])) {
                    CacheAPI::putCache('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
                }
            }
        } elseif (empty($_SESSION['id_msg_last_visit'])) {
            $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
        }
        $username = $user_settings['member_name'];
        if (empty($user_settings['additional_groups'])) {
            $user_info = array('groups' => array($user_settings['id_group'], $user_settings['id_post_group']));
        } else {
            $user_info = array('groups' => array_merge(array($user_settings['id_group'], $user_settings['id_post_group']), explode(',', $user_settings['additional_groups'])));
        }
        // Because history has proven that it is possible for groups to go bad - clean up in case.
        foreach ($user_info['groups'] as $k => $v) {
            $user_info['groups'][$k] = (int) $v;
        }
        // This is a logged in user, so definitely not a spider.
        $user_info['possibly_robot'] = false;
        $user_info['show_online'] = $user_settings['show_online'];
        $user_info['time_offset'] = empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'];
    } else {
        // This is what a guest's variables should be.
        $username = '';
        $user_info = array('groups' => array(-1));
        $user_settings = array();
        if (isset($_COOKIE[$cookiename])) {
            $_COOKIE[$cookiename] = '';
        }
        // Do we perhaps think this is a search robot? Check every five minutes just in case...
        if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300)) {
            $user_info['possibly_robot'] = SpiderCheck();
        } elseif (!empty($modSettings['spider_mode'])) {
            $user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
        } else {
            $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
            $user_info['possibly_robot'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === false || strpos($ci_user_agent, 'googlebot') !== false || strpos($ci_user_agent, 'slurp') !== false || strpos($ci_user_agent, 'crawl') !== false;
        }
        $user_info['time_offset'] = isset($_SESSION['tzoffset']) ? $_SESSION['tzoffset'] : 0;
        $user_info['guest_need_tzoffset'] = !isset($_SESSION['tzoffset']);
        // don't have it yet, embed the js to determine tz offset for *guests only*
    }
    // Set up the $user_info array.
    $user_info += array('id' => $id_member, 'username' => $username, 'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '', 'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '', 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '', 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'], 'is_guest' => $id_member == 0, 'is_admin' => in_array(1, $user_info['groups']), 'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'], 'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'], 'ip' => $_SERVER['REMOTE_ADDR'], 'ip2' => $_SERVER['BAN_CHECK_IP'], 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'], 'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'], 'avatar' => array('url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '', 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'], 'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1, 'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0), 'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '', 'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'], 'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'], 'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'], 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(), 'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(), 'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(), 'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0, 'likesgiven' => isset($user_settings['likes_given']) ? $user_settings['likes_given'] : 0, 'likesreceived' => isset($user_settings['likes_received']) ? $user_settings['likes_received'] : 0, 'permissions' => array(), 'act_optout' => isset($user_settings['act_optout']) ? $user_settings['act_optout'] : '', 'notify_optout' => isset($user_settings['notify_optout']) ? $user_settings['notify_optout'] : '', 'meta' => !empty($user_settings['meta']) ? @unserialize($user_settings['meta']) : array());
    $user_info['smf_sidebar_disabled'] = 0;
    $user_info['groups'] = array_unique($user_info['groups']);
    // Make sure that the last item in the ignore boards array is valid.  If the list was too long it could have an ending comma that could cause problems.
    if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1])) {
        unset($user_info['ignoreboards'][$tmp]);
    }
    // Do we have any languages to validate this?
    if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language']))) {
        $languages = getLanguages();
    }
    // Allow the user to change their language if its valid.
    if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')])) {
        $user_info['language'] = strtr($_GET['language'], './\\:', '____');
        $_SESSION['language'] = $user_info['language'];
    } elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')])) {
        $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
    }
    // map language to a numeric id
    $n = 0;
    if (isset($context['languages'])) {
        foreach ($context['languages'] as $key => $lang) {
            if ($key == $user_info['language']) {
                break;
            }
            $n++;
        }
    }
    $user_info['language_id'] = $n + 1;
    // Just build this here, it makes it easier to change/use - administrators can see all boards.
    if ($user_info['is_admin']) {
        $user_info['query_see_board'] = '1=1';
    } else {
        $user_info['query_see_board'] = '(FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0' . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
    }
    // Build the list of boards they WANT to see.
    // This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
    // If they aren't ignoring any boards then they want to see all the boards they can see
    if (empty($user_info['ignoreboards'])) {
        $user_info['query_wanna_see_board'] = $user_info['query_see_board'];
    } else {
        $user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
    }
    /*
     * figure out unread notifications
     * 
     * the reason why this is here in an extra query is that we need query_see_board.
     * e.g. when a user gets a notification for a topic that has been moved to a board he
     * is not permitted to access, we want to filter out the notifications.
     */
    if ($id_member != 0 && (!isset($user_settings['notify_count']) || $_reload)) {
        // this is actually cached, unless $user_settings was re-fetched from the db.
        $_to_cache = true;
        $request = smf_db_query('
					SELECT COUNT(n.id_act) AS notify_count FROM {db_prefix}log_notifications AS n
						LEFT JOIN {db_prefix}log_activities AS a ON (a.id_act = n.id_act)
						LEFT JOIN {db_prefix}boards AS b ON(b.id_board = a.id_board)
						WHERE n.id_member = {int:id_member} AND n.unread = 1 AND ' . (!empty($user_info['ignoreusers']) ? 'a.id_member NOT IN({array_int:ignoredusers}) AND ' : '') . ' ({query_wanna_see_board} OR a.id_board = 0)', array('id_member' => $id_member, 'ignoredusers' => $user_info['ignoreusers']));
        if (mysql_num_rows($request) > 0) {
            list($unread) = mysql_fetch_row($request);
            $user_settings['notify_count'] = $unread;
        } else {
            $user_settings['notify_count'] = 0;
        }
        mysql_free_result($request);
    }
    if ($modSettings['cache_enable'] >= 2 && $id_member != 0 && $_to_cache) {
        CacheAPI::putCache('user_settings-' . $id_member, $user_settings, 600);
    }
    $user_info['notify_count'] = isset($user_settings['notify_count']) ? $user_settings['notify_count'] : 0;
    if ($user_info['unread_messages'] && $user_info['notify_count'] == 0) {
        $user_info['notify_count']++;
    }
    // record the user in the list of users who were online today. todo: there should be an option for this feature.
    if (!empty($modSettings['who_track_daily_visitors']) && $user_info['id'] > 0 && !isset($modSettings['online_today'][$user_info['id']])) {
        $modSettings['online_today'][$user_info['id']] = array('name' => $user_info['name'], 'show_online' => $user_info['show_online'], 'link' => '<a class="member group_' . (empty($user_settings['id_group']) ? $user_settings['id_post_group'] : $user_settings['id_group']) . '" href="' . URL::user($user_info['id'], $user_info['name']) . '">' . $user_info['name'] . '</a>');
        updateSettings(array('log_online_today' => @serialize($modSettings['online_today'])));
    }
    $user_info['font_class'] = isset($_COOKIE['EOS_Fontstyle']) ? $_COOKIE['EOS_Fontstyle'] : '0';
    HookAPI::callHook('load_userdata', array(&$user_info, &$user_settings));
}
Esempio n. 25
0
function MoveTopic2()
{
    global $txt, $board, $topic, $scripturl, $sourcedir, $modSettings, $context;
    global $board, $language, $user_info, $smcFunc;
    if (empty($topic)) {
        fatal_lang_error('no_access', false);
    }
    // You can't choose to have a redirection topic and use an empty reason.
    if (isset($_POST['postRedirect']) && (!isset($_POST['reason']) || trim($_POST['reason']) == '')) {
        fatal_lang_error('movetopic_no_reason', false);
    }
    // Make sure this form hasn't been submitted before.
    checkSubmitOnce('check');
    $request = $smcFunc['db_query']('', '
		SELECT id_member_started, id_first_msg, approved
		FROM {db_prefix}topics
		WHERE id_topic = {int:current_topic}
		LIMIT 1', array('current_topic' => $topic));
    list($id_member_started, $id_first_msg, $context['is_approved']) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    // Can they see it?
    if (!$context['is_approved']) {
        isAllowedTo('approve_posts');
    }
    // Can they move topics on this board?
    if (!allowedTo('move_any')) {
        if ($id_member_started == $user_info['id']) {
            isAllowedTo('move_own');
            $boards = array_merge(boardsAllowedTo('move_own'), boardsAllowedTo('move_any'));
        } else {
            isAllowedTo('move_any');
        }
    } else {
        $boards = boardsAllowedTo('move_any');
    }
    // If this topic isn't approved don't let them move it if they can't approve it!
    if ($modSettings['postmod_active'] && !$context['is_approved'] && !allowedTo('approve_posts')) {
        // Only allow them to move it to other boards they can't approve it in.
        $can_approve = boardsAllowedTo('approve_posts');
        $boards = array_intersect($boards, $can_approve);
    }
    checkSession();
    require_once $sourcedir . '/Subs-Post.php';
    // The destination board must be numeric.
    $_POST['toboard'] = (int) $_POST['toboard'];
    // Make sure they can see the board they are trying to move to (and get whether posts count in the target board).
    $request = $smcFunc['db_query']('', '
		SELECT b.count_posts, b.name, m.subject
		FROM {db_prefix}boards AS b
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
		WHERE {query_see_board}
			AND b.id_board = {int:to_board}
			AND b.redirect = {string:blank_redirect}
		LIMIT 1', array('current_topic' => $topic, 'to_board' => $_POST['toboard'], 'blank_redirect' => ''));
    if ($smcFunc['db_num_rows']($request) == 0) {
        fatal_lang_error('no_board');
    }
    list($pcounter, $board_name, $subject) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    // Remember this for later.
    $_SESSION['move_to_topic'] = $_POST['toboard'];
    // Rename the topic...
    if (isset($_POST['reset_subject'], $_POST['custom_subject']) && $_POST['custom_subject'] != '') {
        $_POST['custom_subject'] = strtr($smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['custom_subject'])), array("\r" => '', "\n" => '', "\t" => ''));
        // Keep checking the length.
        if ($smcFunc['strlen']($_POST['custom_subject']) > 100) {
            $_POST['custom_subject'] = $smcFunc['substr']($_POST['custom_subject'], 0, 100);
        }
        // If it's still valid move onwards and upwards.
        if ($_POST['custom_subject'] != '') {
            if (isset($_POST['enforce_subject'])) {
                // Get a response prefix, but in the forum's default 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);
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}messages
					SET subject = {string:subject}
					WHERE id_topic = {int:current_topic}', array('current_topic' => $topic, 'subject' => $context['response_prefix'] . $_POST['custom_subject']));
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}messages
				SET subject = {string:custom_subject}
				WHERE id_msg = {int:id_first_msg}', array('id_first_msg' => $id_first_msg, 'custom_subject' => $_POST['custom_subject']));
            // Fix the subject cache.
            updateStats('subject', $topic, $_POST['custom_subject']);
        }
    }
    // Create a link to this in the old board.
    //!!! Does this make sense if the topic was unapproved before? I'd just about say so.
    if (isset($_POST['postRedirect'])) {
        // Should be in the boardwide language.
        if ($user_info['language'] != $language) {
            loadLanguage('index', $language);
        }
        $_POST['reason'] = $smcFunc['htmlspecialchars']($_POST['reason'], ENT_QUOTES);
        preparsecode($_POST['reason']);
        // Add a URL onto the message.
        $_POST['reason'] = strtr($_POST['reason'], array($txt['movetopic_auto_board'] => '[url=' . $scripturl . '?board=' . $_POST['toboard'] . '.0]' . $board_name . '[/url]', $txt['movetopic_auto_topic'] => '[iurl]' . $scripturl . '?topic=' . $topic . '.0[/iurl]'));
        $msgOptions = array('subject' => $txt['moved'] . ': ' . $subject, 'body' => $_POST['reason'], 'icon' => 'moved', 'smileys_enabled' => 1);
        $topicOptions = array('board' => $board, 'lock_mode' => 1, 'mark_as_read' => true);
        $posterOptions = array('id' => $user_info['id'], 'update_post_count' => empty($pcounter));
        createPost($msgOptions, $topicOptions, $posterOptions);
    }
    $request = $smcFunc['db_query']('', '
		SELECT count_posts
		FROM {db_prefix}boards
		WHERE id_board = {int:current_board}
		LIMIT 1', array('current_board' => $board));
    list($pcounter_from) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    if ($pcounter_from != $pcounter) {
        $request = $smcFunc['db_query']('', '
			SELECT id_member
			FROM {db_prefix}messages
			WHERE id_topic = {int:current_topic}
				AND approved = {int:is_approved}', array('current_topic' => $topic, 'is_approved' => 1));
        $posters = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            if (!isset($posters[$row['id_member']])) {
                $posters[$row['id_member']] = 0;
            }
            $posters[$row['id_member']]++;
        }
        $smcFunc['db_free_result']($request);
        foreach ($posters as $id_member => $posts) {
            // The board we're moving from counted posts, but not to.
            if (empty($pcounter_from)) {
                updateMemberData($id_member, array('posts' => 'posts - ' . $posts));
            } else {
                updateMemberData($id_member, array('posts' => 'posts + ' . $posts));
            }
        }
    }
    // Do the move (includes statistics update needed for the redirect topic).
    moveTopics($topic, $_POST['toboard']);
    // Log that they moved this topic.
    if (!allowedTo('move_own') || $id_member_started != $user_info['id']) {
        logAction('move', array('topic' => $topic, 'board_from' => $board, 'board_to' => $_POST['toboard']));
    }
    // Notify people that this topic has been moved?
    sendNotifications($topic, 'move');
    // Why not go back to the original board in case they want to keep moving?
    if (!isset($_REQUEST['goback'])) {
        redirectexit('board=' . $board . '.0');
    } else {
        redirectexit('topic=' . $topic . '.0');
    }
}
Esempio n. 26
0
function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
{
    global $smcFunc, $cookiename, $sourcedir;
    // As this is only brute protection, we allow 5 attempts every 10 seconds.
    // Destroy any session or cookie data about this member, as they validated wrong.
    require_once $sourcedir . '/Subs-Auth.php';
    setLoginCookie(-3600, 0);
    if (isset($_SESSION['login_' . $cookiename])) {
        unset($_SESSION['login_' . $cookiename]);
    }
    // We need a member!
    if (!$id_member) {
        fatal_lang_error('no_access', false);
    }
    // Right, have we got a flood value?
    if ($password_flood_value !== false) {
        @(list($time_stamp, $number_tries) = explode('|', $password_flood_value));
    }
    // Timestamp invalid or non-existent?
    if (empty($number_tries) || $time_stamp < time() - 10) {
        // If it wasn't *that* long ago, don't give them another five goes.
        $number_tries = !empty($number_tries) && $time_stamp < time() - 20 ? 2 : 0;
        $time_stamp = time();
    }
    $number_tries++;
    // Broken the law?
    if ($number_tries > 5) {
        fatal_lang_error('login_threshold_brute_fail', 'critical');
    }
    // Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
    updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));
}
Esempio n. 27
0
/**
 * Allows to edit Personal Message Settings.
 *
 * @uses Profile.php
 * @uses Profile-Modify.php
 * @uses Profile template.
 * @uses Profile language file.
 */
function MessageSettings()
{
    global $txt, $user_settings, $user_info, $context, $sourcedir, $smcFunc;
    global $scripturl, $profile_vars, $cur_profile, $user_profile;
    // Need this for the display.
    require_once $sourcedir . '/Profile.php';
    require_once $sourcedir . '/Profile-Modify.php';
    // We want them to submit back to here.
    $context['profile_custom_submit_url'] = $scripturl . '?action=pm;sa=settings;save';
    loadMemberData($user_info['id'], false, 'profile');
    $cur_profile = $user_profile[$user_info['id']];
    loadLanguage('Profile');
    loadTemplate('Profile');
    $context['page_title'] = $txt['pm_settings'];
    $context['user']['is_owner'] = true;
    $context['id_member'] = $user_info['id'];
    $context['require_password'] = false;
    $context['menu_item_selected'] = 'settings';
    $context['submit_button_text'] = $txt['pm_settings'];
    $context['profile_header_text'] = $txt['personal_messages'];
    // Add our position to the linktree.
    $context['linktree'][] = array('url' => $scripturl . '?action=pm;sa=settings', 'name' => $txt['pm_settings']);
    // Are they saving?
    if (isset($_REQUEST['save'])) {
        checkSession('post');
        // Mimic what profile would do.
        $_POST = htmltrim__recursive($_POST);
        $_POST = htmlspecialchars__recursive($_POST);
        // Save the fields.
        saveProfileFields();
        if (!empty($profile_vars)) {
            updateMemberData($user_info['id'], $profile_vars);
        }
    }
    // Load up the fields.
    pmprefs($user_info['id']);
}
Esempio n. 28
0
/**
 * Approve (or not) some posts... without permission checks...
 *
 * @package Posts
 * @param int[] $msgs - array of message ids
 * @param bool $approve = true
 */
function approvePosts($msgs, $approve = true)
{
    global $modSettings;
    $db = database();
    if (!is_array($msgs)) {
        $msgs = array($msgs);
    }
    if (empty($msgs)) {
        return false;
    }
    // May as well start at the beginning, working out *what* we need to change.
    $request = $db->query('', '
		SELECT m.id_msg, m.approved, m.id_topic, m.id_board, t.id_first_msg, t.id_last_msg,
			m.body, m.subject, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_member,
			t.approved AS topic_approved, b.count_posts
		FROM {db_prefix}messages AS m
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
		WHERE m.id_msg IN ({array_int:message_list})
			AND m.approved = {int:approved_state}', array('message_list' => $msgs, 'approved_state' => $approve ? 0 : 1));
    $msgs = array();
    $topics = array();
    $topic_changes = array();
    $board_changes = array();
    $notification_topics = array();
    $notification_posts = array();
    $member_post_changes = array();
    while ($row = $db->fetch_assoc($request)) {
        // Easy...
        $msgs[] = $row['id_msg'];
        $topics[] = $row['id_topic'];
        // Ensure our change array exists already.
        if (!isset($topic_changes[$row['id_topic']])) {
            $topic_changes[$row['id_topic']] = array('id_last_msg' => $row['id_last_msg'], 'approved' => $row['topic_approved'], 'replies' => 0, 'unapproved_posts' => 0);
        }
        if (!isset($board_changes[$row['id_board']])) {
            $board_changes[$row['id_board']] = array('posts' => 0, 'topics' => 0, 'unapproved_posts' => 0, 'unapproved_topics' => 0);
        }
        // If it's the first message then the topic state changes!
        if ($row['id_msg'] == $row['id_first_msg']) {
            $topic_changes[$row['id_topic']]['approved'] = $approve ? 1 : 0;
            $board_changes[$row['id_board']]['unapproved_topics'] += $approve ? -1 : 1;
            $board_changes[$row['id_board']]['topics'] += $approve ? 1 : -1;
            // Note we need to ensure we announce this topic!
            $notification_topics[] = array('body' => $row['body'], 'subject' => $row['subject'], 'name' => $row['poster_name'], 'board' => $row['id_board'], 'topic' => $row['id_topic'], 'msg' => $row['id_first_msg'], 'poster' => $row['id_member']);
        } else {
            $topic_changes[$row['id_topic']]['replies'] += $approve ? 1 : -1;
            // This will be a post... but don't notify unless it's not followed by approved ones.
            if ($row['id_msg'] > $row['id_last_msg']) {
                $notification_posts[$row['id_topic']][] = array('id' => $row['id_msg'], 'body' => $row['body'], 'subject' => $row['subject'], 'name' => $row['poster_name'], 'topic' => $row['id_topic']);
            }
        }
        // If this is being approved and id_msg is higher than the current id_last_msg then it changes.
        if ($approve && $row['id_msg'] > $topic_changes[$row['id_topic']]['id_last_msg']) {
            $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_msg'];
        } elseif (!$approve) {
            // Default to the first message and then we'll override in a bit ;)
            $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_first_msg'];
        }
        $topic_changes[$row['id_topic']]['unapproved_posts'] += $approve ? -1 : 1;
        $board_changes[$row['id_board']]['unapproved_posts'] += $approve ? -1 : 1;
        $board_changes[$row['id_board']]['posts'] += $approve ? 1 : -1;
        // Post count for the user?
        if ($row['id_member'] && empty($row['count_posts'])) {
            $member_post_changes[$row['id_member']] = isset($member_post_changes[$row['id_member']]) ? $member_post_changes[$row['id_member']] + 1 : 1;
        }
    }
    $db->free_result($request);
    if (empty($msgs)) {
        return;
    }
    // Now we have the differences make the changes, first the easy one.
    $db->query('', '
		UPDATE {db_prefix}messages
		SET approved = {int:approved_state}
		WHERE id_msg IN ({array_int:message_list})', array('message_list' => $msgs, 'approved_state' => $approve ? 1 : 0));
    // If we were unapproving find the last msg in the topics...
    if (!$approve) {
        $request = $db->query('', '
			SELECT id_topic, MAX(id_msg) AS id_last_msg
			FROM {db_prefix}messages
			WHERE id_topic IN ({array_int:topic_list})
				AND approved = {int:approved}
			GROUP BY id_topic', array('topic_list' => $topics, 'approved' => 1));
        while ($row = $db->fetch_assoc($request)) {
            $topic_changes[$row['id_topic']]['id_last_msg'] = $row['id_last_msg'];
        }
        $db->free_result($request);
    }
    // ... next the topics...
    foreach ($topic_changes as $id => $changes) {
        $db->query('', '
			UPDATE {db_prefix}topics
			SET
				approved = {int:approved},
				unapproved_posts = CASE WHEN unapproved_posts + {int:unapproved_posts} < 0 THEN 0 ELSE unapproved_posts + {int:unapproved_posts} END,
				num_replies = CASE WHEN num_replies + {int:num_replies} < 0 THEN 0 ELSE num_replies + {int:num_replies} END,
				id_last_msg = {int:id_last_msg}
			WHERE id_topic = {int:id_topic}', array('approved' => $changes['approved'], 'unapproved_posts' => $changes['unapproved_posts'], 'num_replies' => $changes['replies'], 'id_last_msg' => $changes['id_last_msg'], 'id_topic' => $id));
    }
    // ... finally the boards...
    foreach ($board_changes as $id => $changes) {
        $db->query('', '
			UPDATE {db_prefix}boards
			SET
				num_posts = num_posts + {int:num_posts},
				unapproved_posts = CASE WHEN unapproved_posts + {int:unapproved_posts} < 0 THEN 0 ELSE unapproved_posts + {int:unapproved_posts} END,
				num_topics = CASE WHEN num_topics + {int:num_topics} < 0 THEN 0 ELSE num_topics + {int:num_topics} END,
				unapproved_topics = CASE WHEN unapproved_topics + {int:unapproved_topics} < 0 THEN 0 ELSE unapproved_topics + {int:unapproved_topics} END
			WHERE id_board = {int:id_board}', array('num_posts' => $changes['posts'], 'unapproved_posts' => $changes['unapproved_posts'], 'num_topics' => $changes['topics'], 'unapproved_topics' => $changes['unapproved_topics'], 'id_board' => $id));
    }
    // Finally, least importantly, notifications!
    if ($approve) {
        require_once SUBSDIR . '/Notification.subs.php';
        if (!empty($notification_topics)) {
            sendBoardNotifications($notification_topics);
        }
        if (!empty($notification_posts)) {
            sendApprovalNotifications($notification_posts);
        }
        $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' => $msgs, 'id_attach' => 0));
    } else {
        $msgInserts = array();
        foreach ($msgs as $msg) {
            $msgInserts[] = array($msg);
        }
        $db->insert('ignore', '{db_prefix}approval_queue', array('id_msg' => 'int'), $msgInserts, array('id_msg'));
    }
    if (!empty($modSettings['mentions_enabled'])) {
        require_once SUBSDIR . '/Mentions.subs.php';
        toggleMentionsApproval($msgs, $approve);
    }
    // Update the last messages on the boards...
    updateLastMessages(array_keys($board_changes));
    // Post count for the members?
    if (!empty($member_post_changes)) {
        foreach ($member_post_changes as $id_member => $count_change) {
            updateMemberData($id_member, array('posts' => 'posts ' . ($approve ? '+' : '-') . ' ' . $count_change));
        }
    }
    return true;
}
Esempio n. 29
0
function loadUserSettings()
{
    global $modSettings, $user_settings;
    global $ID_MEMBER, $db_prefix, $cookiename, $user_info, $language;
    // Check first the integration, then the cookie, and last the session.
    if (isset($modSettings['integrate_verify_user']) && function_exists($modSettings['integrate_verify_user'])) {
        $ID_MEMBER = (int) call_user_func($modSettings['integrate_verify_user']);
        $already_verified = $ID_MEMBER > 0;
    } else {
        $ID_MEMBER = 0;
    }
    if (empty($ID_MEMBER) && isset($_COOKIE[$cookiename])) {
        $_COOKIE[$cookiename] = stripslashes($_COOKIE[$cookiename]);
        // Fix a security hole in PHP 4.3.9 and below...
        if (preg_match('~^a:[34]:\\{i:0;(i:\\d{1,6}|s:[1-8]:"\\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\\d{1,14};(i:3;i:\\d;)?\\}$~', $_COOKIE[$cookiename]) == 1) {
            list($ID_MEMBER, $password) = @unserialize($_COOKIE[$cookiename]);
            $ID_MEMBER = !empty($ID_MEMBER) && strlen($password) > 0 ? (int) $ID_MEMBER : 0;
        } else {
            $ID_MEMBER = 0;
        }
    } elseif (empty($ID_MEMBER) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA']))) {
        // !!! Perhaps we can do some more checking on this, such as on the first octet of the IP?
        list($ID_MEMBER, $password, $login_span) = @unserialize(stripslashes($_SESSION['login_' . $cookiename]));
        $ID_MEMBER = !empty($ID_MEMBER) && strlen($password) == 40 && $login_span > time() ? (int) $ID_MEMBER : 0;
    }
    // Only load this stuff if the user isn't a guest.
    if ($ID_MEMBER != 0) {
        // Is the member data cached?
        if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $ID_MEMBER, 60)) == null) {
            $request = db_query("\n\t\t\t\tSELECT mem.*, IFNULL(a.ID_ATTACH, 0) AS ID_ATTACH, a.filename, a.attachmentType\n\t\t\t\tFROM {$db_prefix}members AS mem\n\t\t\t\t\tLEFT JOIN {$db_prefix}attachments AS a ON (a.ID_MEMBER = {$ID_MEMBER})\n\t\t\t\tWHERE mem.ID_MEMBER = {$ID_MEMBER}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            $user_settings = mysql_fetch_assoc($request);
            mysql_free_result($request);
            if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
                cache_put_data('user_settings-' . $ID_MEMBER, $user_settings, 60);
            }
        }
        // Did we find 'im?  If not, junk it.
        if (!empty($user_settings)) {
            // As much as the password should be right, we can assume the integration set things up.
            if (!empty($already_verified) && $already_verified === true) {
                $check = true;
            } elseif (strlen($password) == 40) {
                $check = sha1($user_settings['passwd'] . $user_settings['passwordSalt']) == $password;
            } else {
                $check = false;
            }
            // Wrong password or not activated - either way, you're going nowhere.
            $ID_MEMBER = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['ID_MEMBER'] : 0;
        } else {
            $ID_MEMBER = 0;
        }
    }
    // Found 'im, let's set up the variables.
    if ($ID_MEMBER != 0) {
        // Let's not update the last visit time in these cases...
        // 1. SSI doesn't count as visiting the forum.
        // 2. RSS feeds and XMLHTTP requests don't count either.
        // 3. If it was set within this session, no need to set it again.
        // 4. New session, yet updated < five hours ago? Maybe cache can help.
        if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['ID_MSG_LAST_VISIT']) && (empty($modSettings['cache_enable']) || ($_SESSION['ID_MSG_LAST_VISIT'] = cache_get_data('user_last_visit-' . $ID_MEMBER, 5 * 3600)) === null)) {
            // Do a quick query to make sure this isn't a mistake.
            $result = db_query("\n\t\t\t\tSELECT posterTime\n\t\t\t\tFROM {$db_prefix}messages\n\t\t\t\tWHERE ID_MSG = {$user_settings['ID_MSG_LAST_VISIT']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
            list($visitTime) = mysql_fetch_row($result);
            mysql_free_result($result);
            $_SESSION['ID_MSG_LAST_VISIT'] = $user_settings['ID_MSG_LAST_VISIT'];
            // If it was *at least* five hours ago...
            if ($visitTime < time() - 5 * 3600) {
                updateMemberData($ID_MEMBER, array('ID_MSG_LAST_VISIT' => (int) $modSettings['maxMsgID'], 'lastLogin' => time(), 'memberIP' => '\'' . $_SERVER['REMOTE_ADDR'] . '\'', 'memberIP2' => '\'' . $_SERVER['BAN_CHECK_IP'] . '\''));
                $user_settings['lastLogin'] = time();
                if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2) {
                    cache_put_data('user_settings-' . $ID_MEMBER, $user_settings, 60);
                }
                if (!empty($modSettings['cache_enable'])) {
                    cache_put_data('user_last_visit-' . $ID_MEMBER, $_SESSION['ID_MSG_LAST_VISIT'], 5 * 3600);
                }
            }
        } elseif (empty($_SESSION['ID_MSG_LAST_VISIT'])) {
            $_SESSION['ID_MSG_LAST_VISIT'] = $user_settings['ID_MSG_LAST_VISIT'];
        }
        $username = $user_settings['memberName'];
        if (empty($user_settings['additionalGroups'])) {
            $user_info = array('groups' => array($user_settings['ID_GROUP'], $user_settings['ID_POST_GROUP']));
        } else {
            $user_info = array('groups' => array_merge(array($user_settings['ID_GROUP'], $user_settings['ID_POST_GROUP']), explode(',', $user_settings['additionalGroups'])));
        }
    } else {
        // This is what a guest's variables should be.
        $username = '';
        $user_info = array('groups' => array(-1));
        $user_settings = array();
        if (isset($_COOKIE[$cookiename])) {
            $_COOKIE[$cookiename] = '';
        }
    }
    // Set up the $user_info array.
    $user_info += array('username' => $username, 'name' => isset($user_settings['realName']) ? $user_settings['realName'] : '', 'email' => isset($user_settings['emailAddress']) ? $user_settings['emailAddress'] : '', 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '', 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'], 'is_guest' => $ID_MEMBER == 0, 'is_admin' => in_array(1, $user_info['groups']), 'theme' => empty($user_settings['ID_THEME']) ? 0 : $user_settings['ID_THEME'], 'last_login' => empty($user_settings['lastLogin']) ? 0 : $user_settings['lastLogin'], 'ip' => $_SERVER['REMOTE_ADDR'], 'ip2' => $_SERVER['BAN_CHECK_IP'], 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'], 'time_format' => empty($user_settings['timeFormat']) ? $modSettings['time_format'] : $user_settings['timeFormat'], 'time_offset' => empty($user_settings['timeOffset']) ? 0 : $user_settings['timeOffset'], 'avatar' => array('url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '', 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'], 'custom_dir' => !empty($user_settings['attachmentType']) && $user_settings['attachmentType'] == 1, 'ID_ATTACH' => isset($user_settings['ID_ATTACH']) ? $user_settings['ID_ATTACH'] : 0), 'smiley_set' => isset($user_settings['smileySet']) ? $user_settings['smileySet'] : '', 'messages' => empty($user_settings['instantMessages']) ? 0 : $user_settings['instantMessages'], 'unread_messages' => empty($user_settings['unreadMessages']) ? 0 : $user_settings['unreadMessages'], 'total_time_logged_in' => empty($user_settings['totalTimeLoggedIn']) ? 0 : $user_settings['totalTimeLoggedIn'], 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(), 'permissions' => array());
    $user_info['groups'] = array_unique($user_info['groups']);
    if (!empty($modSettings['userLanguage']) && !empty($_REQUEST['language'])) {
        $user_info['language'] = strtr($_REQUEST['language'], './\\:', '____');
        $_SESSION['language'] = $user_info['language'];
    } elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language'])) {
        $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
    }
    // Just build this here, it makes it easier to change/use.
    if ($user_info['is_guest']) {
        $user_info['query_see_board'] = 'FIND_IN_SET(-1, b.memberGroups)';
    } elseif ($user_info['is_admin']) {
        $user_info['query_see_board'] = '1';
    } else {
        $user_info['query_see_board'] = '(FIND_IN_SET(' . implode(', b.memberGroups) OR FIND_IN_SET(', $user_info['groups']) . ', b.memberGroups))';
    }
}
Esempio n. 30
0
function notasparacambiar()
{
    global $user_info, $smcFunc, $txt, $adkFolder;
    $notes = '';
    if (isset($_POST['notes_save']) && isset($_POST['notes_txt'])) {
        $notes = CleanAdkStrings($_POST['notes_txt']);
        if ($user_info['is_guest']) {
            $_SESSION['adk_notes'] = $notes;
        } else {
            updateMemberData($user_info['id'], array('adk_notes' => $notes));
        }
    } else {
        $notes = $user_info['adk_notes'];
        //If this user is guest, He can add notes too ;)
        if (isset($_SESSION['adk_notes']) && $user_info['is_guest']) {
            $notes = $_SESSION['adk_notes'];
        }
    }
    echo '
	<script type="text/javascript">
		function ChangeContent(id, id2) {
		if(document.getElementById(id).style.display == "none"){
			document.getElementById(id).style.display = "block";
		}
		else{
			document.getElementById(id).style.display = "none";
		}
		
		if(document.getElementById(id2).style.display == "none"){
			document.getElementById(id2).style.display = "block";
		}
		else{
			document.getElementById(id2).style.display = "none";
		}
	}
	</script>';
    echo '
	<div class="smalltext" align="center" id="note" style="display: none;">
		<form action="" method="post">
			<textarea rows="3" cols="15" name="notes_txt">', $notes, '</textarea>
			<br />
			<br /><input class="button_submit" type="submit" name="notes_save" value="' . $txt['save'] . '" />
		</form>
	</div>';
    echo '
	<div id="note2" align="center" class="smalltext" style="display: block;">
		', empty($notes) ? $txt['adkmod_block_reminder'] : parse_bbc($notes), '
	</div>
	<div align="right">
		<a href="javascript:ChangeContent(\'note\',\'note2\')" title="' . $txt['adkmod_block_editar'] . '">
			<img alt="" src="' . $adkFolder['images'] . '/email_edit.png" />
		</a>
	</div>
	';
    /* rows="10" cols="10" onkeyup="if(this.value.length > 140){this.value=this.value.substring(0,140);alert(\'no puede poner más de 140 caracteres\')}"*/
}