Exemplo n.º 1
0
/**
 * Shows an interface to set and test censored words.
 * It uses the censor_vulgar, censor_proper, censorWholeWord, and censorIgnoreCase
 * settings.
 * Requires the admin_forum permission.
 * Accessed from ?action=admin;area=postsettings;sa=censor.
 *
 * @uses the Admin template and the edit_censored sub template.
 */
function SetCensor()
{
    global $txt, $modSettings, $context, $smcFunc, $sourcedir;
    if (!empty($_POST['save_censor'])) {
        // Make sure censoring is something they can do.
        checkSession();
        validateToken('admin-censor');
        $censored_vulgar = array();
        $censored_proper = array();
        // Rip it apart, then split it into two arrays.
        if (isset($_POST['censortext'])) {
            $_POST['censortext'] = explode("\n", strtr($_POST['censortext'], array("\r" => '')));
            foreach ($_POST['censortext'] as $c) {
                list($censored_vulgar[], $censored_proper[]) = array_pad(explode('=', trim($c)), 2, '');
            }
        } elseif (isset($_POST['censor_vulgar'], $_POST['censor_proper'])) {
            if (is_array($_POST['censor_vulgar'])) {
                foreach ($_POST['censor_vulgar'] as $i => $value) {
                    if (trim(strtr($value, '*', ' ')) == '') {
                        unset($_POST['censor_vulgar'][$i], $_POST['censor_proper'][$i]);
                    }
                }
                $censored_vulgar = $_POST['censor_vulgar'];
                $censored_proper = $_POST['censor_proper'];
            } else {
                $censored_vulgar = explode("\n", strtr($_POST['censor_vulgar'], array("\r" => '')));
                $censored_proper = explode("\n", strtr($_POST['censor_proper'], array("\r" => '')));
            }
        }
        // Set the new arrays and settings in the database.
        $updates = array('censor_vulgar' => implode("\n", $censored_vulgar), 'censor_proper' => implode("\n", $censored_proper), 'censorWholeWord' => empty($_POST['censorWholeWord']) ? '0' : '1', 'censorIgnoreCase' => empty($_POST['censorIgnoreCase']) ? '0' : '1');
        call_integration_hook('integrate_save_censors', array(&$updates));
        updateSettings($updates);
    }
    if (isset($_POST['censortest'])) {
        require_once $sourcedir . '/Subs-Post.php';
        $censorText = htmlspecialchars($_POST['censortest'], ENT_QUOTES);
        preparsecode($censorText);
        $context['censor_test'] = strtr(censorText($censorText), array('"' => '"'));
    }
    // Set everything up for the template to do its thang.
    $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
    $censor_proper = explode("\n", $modSettings['censor_proper']);
    $context['censored_words'] = array();
    for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++) {
        if (empty($censor_vulgar[$i])) {
            continue;
        }
        // Skip it, it's either spaces or stars only.
        if (trim(strtr($censor_vulgar[$i], '*', ' ')) == '') {
            continue;
        }
        $context['censored_words'][htmlspecialchars(trim($censor_vulgar[$i]))] = isset($censor_proper[$i]) ? htmlspecialchars($censor_proper[$i]) : '';
    }
    call_integration_hook('integrate_censors');
    $context['sub_template'] = 'edit_censored';
    $context['page_title'] = $txt['admin_censored_words'];
    createToken('admin-censor');
}
Exemplo n.º 2
0
function SaveNote()
{
    global $smcFunc;
    // Check if they are allowed to admin forum.
    isAllowedTo('admin_forum');
    // Make the html safe if used so it does not mess up the page
    $anotes = htmlspecialchars($_POST['txtnotes'], ENT_QUOTES);
    // Insert the admin notes into the database
    updateSettings(array('adminnotes' => $anotes));
    // Redirect to the main admin page to see the changed notes
    redirectexit('action=admin');
}
Exemplo n.º 3
0
 public function settings()
 {
     if ($_POST) {
         $settings = $this->input->post('settings');
         updateSettings($settings);
         showMessage(lang('Settings was successfully updated', 'translator', FALSE));
         if ($this->input->post('action') == 'exit') {
             pjax(site_url('admin/components/init_window/translator'));
         }
     } else {
         \CMSFactory\assetManager::create()->registerScript('admin')->registerStyle('admin')->setData('settings', getSettings())->setData('languages_names', get_language_names())->renderAdmin('settings');
     }
 }
Exemplo n.º 4
0
/**
 * Finds or repairs errors in the database to fix possible problems.
 * Requires the admin_forum permission.
 * Calls createSalvageArea() to create a new board, if necesary.
 * Accessed by ?action=admin;area=repairboards.
 *
 * @uses raw_data sub-template.
 */
function RepairBoards()
{
    global $txt, $context, $sourcedir, $salvageBoardID;
    isAllowedTo('admin_forum');
    // Try secure more memory.
    setMemoryLimit('128M');
    // Print out the top of the webpage.
    $context['page_title'] = $txt['admin_repair'];
    $context['sub_template'] = 'repair_boards';
    $context[$context['admin_menu_name']]['current_subsection'] = 'general';
    // Load the language file.
    loadLanguage('ManageMaintenance');
    // Make sure the tabs stay nice.
    $context[$context['admin_menu_name']]['tab_data'] = array('title' => $txt['maintain_title'], 'help' => '', 'description' => $txt['maintain_info'], 'tabs' => array());
    // Start displaying errors without fixing them.
    if (isset($_GET['fixErrors'])) {
        checkSession('get');
    }
    // Will want this.
    loadForumTests();
    // Giant if/else. The first displays the forum errors if a variable is not set and asks
    // if you would like to continue, the other fixes the errors.
    if (!isset($_GET['fixErrors'])) {
        $context['error_search'] = true;
        $context['repair_errors'] = array();
        $context['to_fix'] = findForumErrors();
        if (!empty($context['to_fix'])) {
            $_SESSION['repairboards_to_fix'] = $context['to_fix'];
            $_SESSION['repairboards_to_fix2'] = null;
            if (empty($context['repair_errors'])) {
                $context['repair_errors'][] = '???';
            }
        }
    } else {
        $context['error_search'] = false;
        $context['to_fix'] = isset($_SESSION['repairboards_to_fix']) ? $_SESSION['repairboards_to_fix'] : array();
        require_once $sourcedir . '/Subs-Boards.php';
        // Actually do the fix.
        findForumErrors(true);
        // Note that we've changed everything possible ;)
        updateSettings(array('settings_updated' => time()));
        updateStats('message');
        updateStats('topic');
        updateSettings(array('calendar_updated' => time()));
        if (!empty($salvageBoardID)) {
            $context['redirect_to_recount'] = true;
        }
        $_SESSION['repairboards_to_fix'] = null;
        $_SESSION['repairboards_to_fix2'] = null;
    }
}
Exemplo n.º 5
0
function fix_serialized_columns()
{
    global $db_prefix;
    $request = db_query("\n\t\tSELECT ID_ACTION, extra\n\t\tFROM {$db_prefix}log_actions\n\t\tWHERE action IN ('remove', 'delete')", __FILE__, __LINE__);
    while ($row = mysql_fetch_assoc($request)) {
        if (@unserialize($row['extra']) === false && preg_match('~^(a:3:{s:5:"topic";i:\\d+;s:7:"subject";s:)(\\d+):"(.+)"(;s:6:"member";s:5:"\\d+";})$~', $row['extra'], $matches) === 1) {
            db_query("\n\t\t\t\tUPDATE {$db_prefix}log_actions\n\t\t\t\tSET extra = '{$matches['1']}" . strlen($matches[3]) . ":\"{$matches['3']}\"{$matches['4']}'\n\t\t\t\tWHERE ID_ACTION = {$row['ID_ACTION']}\n\t\t\t\tLIMIT 1", __FILE__, __LINE__);
        }
    }
    mysql_free_result($request);
    // Refresh some serialized strings stored in the settings table.
    updateStats('calendar');
    // The memberlist cache needs to be recalculated too.
    updateSettings(array('memberlist_updated' => time()));
}
Exemplo n.º 6
0
 public static function uninstall($product)
 {
     global $modSettings;
     $pluginMain = HookAPI::getAddonsDir() . $product . '/main.php';
     require_once $pluginMain;
     $autoloader = $product . '_autoloader';
     $pluginInstance = $autoloader();
     if (is_callable($autoloader)) {
         $installedPlugins = @unserialize($modSettings['plugins']);
         $pluginInstance->removeHooks();
         unset($installedPlugins[$product]);
         updateSettings(array('plugins' => @serialize($installedPlugins)));
         return true;
     } else {
         // todo error handling
     }
 }
Exemplo n.º 7
0
function AdminNotepad()
{
    loadLanguage('smfhacks_languages/admin-notepad');
    loadTemplate('smfhacks_templates/admin-notepad', array('smfhacks_css/admin-notepad'));
    if (allowedTo('admin_forum')) {
        global $modSettings, $smcFunc;
        if (isset($_POST['admin_notes'])) {
            if (!empty($modSettings['admin_notes']) && $_POST['admin_notes'] == $modSettings['admin_notes']) {
                return;
            } elseif (empty($modSettings['admin_notes']) && empty($_POST['admin_notes'])) {
                return;
            } else {
                updateSettings(array('admin_notes' => $smcFunc['htmlspecialchars']($_POST['admin_notes'], ENT_QUOTES)));
                redirectexit('action=admin;notes_saved');
            }
        }
    }
}
Exemplo n.º 8
0
function AdminNotepad()
{
    if (allowedTo('admin_forum')) {
        global $context, $modSettings, $settings;
        loadLanguage('smfhacks_languages/admin-notepad');
        loadTemplate('smfhacks_templates/admin-notepad');
        $context['html_headers'] .= "\n" . '<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] . '/smfhacks_css/admin-notepad.css" />';
        if (isset($_POST['admin_notes'])) {
            if (!empty($modSettings['admin_notes']) && $_POST['admin_notes'] == $modSettings['admin_notes']) {
                return;
            } elseif (empty($modSettings['admin_notes']) && empty($_POST['admin_notes'])) {
                return;
            } else {
                updateSettings(array('admin_notes' => htmlspecialchars($_POST['admin_notes'], ENT_QUOTES)));
                redirectexit('action=admin;notes_saved');
            }
        }
    }
}
Exemplo n.º 9
0
/**
 * Fixes corrupted serialized strings after a character set conversion.
 */
function fix_serialized_columns()
{
    $db = database();
    $request = $db->query('', '
		SELECT id_action, extra
		FROM {db_prefix}log_actions
		WHERE action IN ({string:remove}, {string:delete})', array('remove' => 'remove', 'delete' => 'delete'));
    while ($row = $db->fetch_assoc($request)) {
        if (@unserialize($row['extra']) === false && preg_match('~^(a:3:{s:5:"topic";i:\\d+;s:7:"subject";s:)(\\d+):"(.+)"(;s:6:"member";s:5:"\\d+";})$~', $row['extra'], $matches) === 1) {
            $db->query('', '
				UPDATE {db_prefix}log_actions
				SET extra = {string:extra}
				WHERE id_action = {int:current_action}', array('current_action' => $row['id_action'], 'extra' => $matches[1] . strlen($matches[3]) . ':"' . $matches[3] . '"' . $matches[4]));
        }
    }
    $db->free_result($request);
    // Refresh some cached data.
    updateSettings(array('memberlist_updated' => time()));
}
Exemplo n.º 10
0
function WelcomeTopicSettings2()
{
    global $smcFunc;
    $boardselect = (int) $_REQUEST['boardselect'];
    $welcome_postername = str_replace('"', '', $_REQUEST['welcome_postername']);
    $welcome_postername = str_replace("'", '', $welcome_postername);
    $welcome_postername = str_replace('\\', '', $welcome_postername);
    $welcome_postername = htmlspecialchars($welcome_postername, ENT_QUOTES);
    // Get the topic name
    // Lookup the Memeber ID of the postername
    $memid = 0;
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT \n\t\treal_name, ID_MEMBER \n\tFROM {db_prefix}members \n\tWHERE real_name = '{$welcome_postername}' OR member_name = '{$welcome_postername}'  LIMIT 1");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if ($smcFunc['db_affected_rows']() != 0) {
        $memid = $row['ID_MEMBER'];
    }
    // Save the setting information
    updateSettings(array('welcome_boardid' => $boardselect, 'welcome_membername' => $welcome_postername, 'welcome_memberid' => $memid));
    // Redirect to Welcome Topic settings page
    redirectexit('action=admin;area=welcome;sa=admin');
}
Exemplo n.º 11
0
function ShopGeneral()
{
    global $context, $modSettings, $txt;
    // The admin menu on the side, and other stuff
    adminIndex('shop_general');
    // We haven't saved yet (this is for the 'Settings Saved' message' on the admin page)
    $context['shop_saved'] = false;
    // If they've pressed the 'Save' button
    if (isset($_GET['save'])) {
        // Put all the settings into an array, to save
        $newSettings['shopCurrencyPrefix'] = $_POST['prefix'];
        $newSettings['shopCurrencySuffix'] = $_POST['suffix'];
        $newSettings['shopPointsPerTopic'] = (double) $_POST['pertopic'];
        $newSettings['shopPointsPerPost'] = (double) $_POST['perpost'];
        $newSettings['shopImageWidth'] = (int) $_POST['image_width'];
        $newSettings['shopImageHeight'] = (int) $_POST['image_height'];
        $newSettings['shopInterest'] = (double) $_POST['interest'];
        $newSettings['shopItemsPerPage'] = (int) $_POST['itemspage'];
        $newSettings['shopMinDeposit'] = (double) $_POST['minDeposit'];
        $newSettings['shopMinWithdraw'] = (double) $_POST['minWithdraw'];
        $newSettings['shopFeeDeposit'] = (double) $_POST['feeDeposit'];
        $newSettings['shopFeeWithdraw'] = (double) $_POST['feeWithdraw'];
        $newSettings['shopRegAmount'] = (int) $_POST['regamount'];
        $newSettings['shopBankEnabled'] = isset($_POST['bankenabled']) ? '1' : '0';
        $newSettings['shopTradeEnabled'] = isset($_POST['tradeenabled']) ? '1' : '0';
        // Bonuses
        $newSettings['shopPointsPerChar'] = (double) $_POST['perchar'];
        $newSettings['shopPointsPerWord'] = (double) $_POST['perword'];
        $newSettings['shopPointsLimit'] = (double) $_POST['limit'];
        // Save all these settings
        updateSettings($newSettings);
        // We've saved, tell the user that it was successful
        $context['shop_saved'] = true;
    }
    // Set the page title
    $context['page_title'] = $txt['shop'] . ' - ' . $txt['shop_admin_general'];
    // Load the template
    loadTemplate('ShopAdmin');
}
Exemplo n.º 12
0
function ajaxFunc()
{
    global $db_name;
    if (!isset($_REQUEST['type'])) {
        return;
    }
    $db_names = array('videos' => 'sponsoredvideo', 'skins' => 'sponsoredskin', 'channels' => 'sponsoredchannel', 'settings' => 'settings');
    $db_name = $db_names[$_REQUEST['type']];
    $funcs = array('videos', 'skins', 'channels', 'settings');
    if (!in_array($_REQUEST['type'], $funcs)) {
        jsonError('Invalid action.');
    }
    if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get') {
        jsonQuery();
    } else {
        checkCsrfToken();
        if ($_REQUEST['type'] == 'settings') {
            updateSettings();
        } else {
            addEdit();
        }
    }
}
Exemplo n.º 13
0
function GlobalHFCheckSaving()
{
    if (isset($_POST['global_head'])) {
        checkSession();
        global $smcFunc, $boarddir;
        $file_fields = array('global_head', 'global_header', 'global_footer');
        foreach ($file_fields as $key => $value) {
            if (isset($_POST[$value])) {
                $_POST[$value] = $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST[$value], ENT_QUOTES));
                file_put_contents($boarddir . '/smfhacks_resources/global-hf-' . str_replace('global_', '', $value) . '.txt', $_POST[$value]);
            }
        }
        $bbc_fields = array('global_header_bbc', 'global_footer_bbc');
        foreach ($bbc_fields as $key => $value) {
            if (isset($_POST[$value])) {
                $_POST[$value] = (int) $_POST[$value];
                $final_arr[$value] = $_POST[$value];
            }
        }
        updateSettings($final_arr);
        redirectexit('action=admin;area=globalhf;success=saved');
    }
}
Exemplo n.º 14
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));
}
Exemplo n.º 15
0
function ModifySettings()
{
    global $modSettings, $context, $settings, $db_prefix, $txt, $boarddir, $sourcedir;
    loadTemplate('ManageCalendar');
    $context['page_title'] = $txt['calendar_settings'];
    $context['sub_template'] = 'modify_settings';
    // A file we need to show permissions inline.
    require_once $sourcedir . '/ManagePermissions.php';
    $calendarPermissions = array('calendar_view', 'calendar_post', 'calendar_edit_own', 'calendar_edit_any');
    // A form was submitted.
    if (isset($_POST['sc'], $_POST['cal_days_for_index'])) {
        checkSession();
        // Although the display settings are combined to the user, they are seperate to the database.
        $toSet['cal_showholidaysonindex'] = $_POST['cal_showholidays'] == 'index' || $_POST['cal_showholidays'] == 'all' ? '1' : '0';
        $toSet['cal_showbdaysonindex'] = $_POST['cal_showbdays'] == 'index' || $_POST['cal_showbdays'] == 'all' ? '1' : '0';
        $toSet['cal_showeventsonindex'] = $_POST['cal_showevents'] == 'index' || $_POST['cal_showevents'] == 'all' ? '1' : '0';
        $toSet['cal_showholidaysoncalendar'] = $_POST['cal_showholidays'] == 'cal' || $_POST['cal_showholidays'] == 'all' ? '1' : '0';
        $toSet['cal_showbdaysoncalendar'] = $_POST['cal_showbdays'] == 'cal' || $_POST['cal_showbdays'] == 'all' ? '1' : '0';
        $toSet['cal_showeventsoncalendar'] = $_POST['cal_showevents'] == 'cal' || $_POST['cal_showevents'] == 'all' ? '1' : '0';
        updateSettings(array('cal_enabled' => isset($_POST['cal_enabled']) ? '1' : '0', 'cal_daysaslink' => isset($_POST['cal_daysaslink']) ? '1' : '0', 'cal_showweeknum' => isset($_POST['cal_showweeknum']) ? '1' : '0', 'cal_days_for_index' => (int) $_POST['cal_days_for_index'], 'cal_showholidaysonindex' => $toSet['cal_showholidaysonindex'], 'cal_showbdaysonindex' => $toSet['cal_showbdaysonindex'], 'cal_showeventsonindex' => $toSet['cal_showeventsonindex'], 'cal_showholidaysoncalendar' => $toSet['cal_showholidaysoncalendar'], 'cal_showbdaysoncalendar' => $toSet['cal_showbdaysoncalendar'], 'cal_showeventsoncalendar' => $toSet['cal_showeventsoncalendar'], 'cal_defaultboard' => (int) $_POST['cal_defaultboard'], 'cal_allow_unlinked' => isset($_POST['cal_allow_unlinked']) ? '1' : '0', 'cal_minyear' => (int) $_POST['cal_minyear'], 'cal_maxyear' => (int) $_POST['cal_maxyear'], 'cal_bdaycolor' => $_POST['cal_bdaycolor'], 'cal_eventcolor' => $_POST['cal_eventcolor'], 'cal_holidaycolor' => $_POST['cal_holidaycolor'], 'cal_allowspan' => isset($_POST['cal_allowspan']) ? '1' : '0', 'cal_maxspan' => (int) $_POST['cal_maxspan'], 'cal_showInTopic' => isset($_POST['cal_showInTopic']) ? '1' : '0'));
        save_inline_permissions($calendarPermissions);
        updateStats('calendar');
        // Ensure we redirect incase the change in settings means the tabs are outdated.
        redirectexit('action=managecalendar;sa=settings');
    }
    // Load the boards list.
    $context['cal_boards'] = array('');
    $request = db_query("\n\t\tSELECT b.ID_BOARD, b.name AS bName, c.name AS cName\n\t\tFROM {$db_prefix}boards AS b\n\t\t\tLEFT JOIN {$db_prefix}categories AS c ON (c.ID_CAT = b.ID_CAT)", __FILE__, __LINE__);
    while ($row = mysql_fetch_assoc($request)) {
        $context['cal_boards'][$row['ID_BOARD']] = $row['cName'] . ' - ' . $row['bName'];
    }
    mysql_free_result($request);
    // Initialize the inline permission settings.
    init_inline_permissions($calendarPermissions);
    // Setup the display settings, just for better UI ;)
    $context['cal_showholidays'] = empty($modSettings['cal_showholidaysonindex']) ? empty($modSettings['cal_showholidaysoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showholidaysoncalendar']) ? 'index' : 'all');
    $context['cal_showbdays'] = empty($modSettings['cal_showbdaysonindex']) ? empty($modSettings['cal_showbdaysoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showbdaysoncalendar']) ? 'index' : 'all');
    $context['cal_showevents'] = empty($modSettings['cal_showeventsonindex']) ? empty($modSettings['cal_showeventsoncalendar']) ? 'never' : 'cal' : (empty($modSettings['cal_showeventsoncalendar']) ? 'index' : 'all');
}
Exemplo n.º 16
0
function GroupRequests()
{
    global $txt, $context, $scripturl, $user_info, $sourcedir, $smcFunc, $modSettings, $language;
    // Set up the template stuff...
    $context['page_title'] = $txt['mc_group_requests'];
    $context['sub_template'] = 'show_list';
    // Verify we can be here.
    if ($user_info['mod_cache']['gq'] == '0=1') {
        isAllowedTo('manage_membergroups');
    }
    // Normally, we act normally...
    $where = $user_info['mod_cache']['gq'] == '1=1' || $user_info['mod_cache']['gq'] == '0=1' ? $user_info['mod_cache']['gq'] : 'lgr.' . $user_info['mod_cache']['gq'];
    $where_parameters = array();
    // We've submitted?
    if (isset($_POST[$context['session_var']]) && !empty($_POST['groupr']) && !empty($_POST['req_action'])) {
        checkSession('post');
        // Clean the values.
        foreach ($_POST['groupr'] as $k => $request) {
            $_POST['groupr'][$k] = (int) $request;
        }
        // If we are giving a reason (And why shouldn't we?), then we don't actually do much.
        if ($_POST['req_action'] == 'reason') {
            // Different sub template...
            $context['sub_template'] = 'group_request_reason';
            // And a limitation. We don't care that the page number bit makes no sense, as we don't need it!
            $where .= ' AND lgr.id_request IN ({array_int:request_ids})';
            $where_parameters['request_ids'] = $_POST['groupr'];
            $context['group_requests'] = list_getGroupRequests(0, $modSettings['defaultMaxMessages'], 'lgr.id_request', $where, $where_parameters);
            // Let obExit etc sort things out.
            obExit();
        } else {
            // Get the details of all the members concerned...
            $request = $smcFunc['db_query']('', '
				SELECT lgr.id_request, lgr.id_member, lgr.id_group, mem.email_address, mem.id_group AS primary_group,
					mem.additional_groups AS additional_groups, mem.lngfile, mem.member_name, mem.notify_types,
					mg.hidden, mg.group_name
				FROM {db_prefix}log_group_requests AS lgr
					INNER JOIN {db_prefix}members AS mem ON (mem.id_member = lgr.id_member)
					INNER JOIN {db_prefix}membergroups AS mg ON (mg.id_group = lgr.id_group)
				WHERE ' . $where . '
					AND lgr.id_request IN ({array_int:request_list})
				ORDER BY mem.lngfile', array('request_list' => $_POST['groupr']));
            $email_details = array();
            $group_changes = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $row['lngfile'] = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
                // If we are approving work out what their new group is.
                if ($_POST['req_action'] == 'approve') {
                    // For people with more than one request at once.
                    if (isset($group_changes[$row['id_member']])) {
                        $row['additional_groups'] = $group_changes[$row['id_member']]['add'];
                        $row['primary_group'] = $group_changes[$row['id_member']]['primary'];
                    } else {
                        $row['additional_groups'] = explode(',', $row['additional_groups']);
                    }
                    // Don't have it already?
                    if ($row['primary_group'] == $row['id_group'] || in_array($row['id_group'], $row['additional_groups'])) {
                        continue;
                    }
                    // Should it become their primary?
                    if ($row['primary_group'] == 0 && $row['hidden'] == 0) {
                        $row['primary_group'] = $row['id_group'];
                    } else {
                        $row['additional_groups'][] = $row['id_group'];
                    }
                    // Add them to the group master list.
                    $group_changes[$row['id_member']] = array('primary' => $row['primary_group'], 'add' => $row['additional_groups']);
                }
                // Add required information to email them.
                if ($row['notify_types'] != 4) {
                    $email_details[] = array('rid' => $row['id_request'], 'member_id' => $row['id_member'], 'member_name' => $row['member_name'], 'group_id' => $row['id_group'], 'group_name' => $row['group_name'], 'email' => $row['email_address'], 'language' => $row['lngfile']);
                }
            }
            $smcFunc['db_free_result']($request);
            // Remove the evidence...
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}log_group_requests
				WHERE id_request IN ({array_int:request_list})', array('request_list' => $_POST['groupr']));
            // Ensure everyone who is online gets their changes right away.
            updateSettings(array('settings_updated' => time()));
            if (!empty($email_details)) {
                require_once $sourcedir . '/Subs-Post.php';
                // They are being approved?
                if ($_POST['req_action'] == 'approve') {
                    // Make the group changes.
                    foreach ($group_changes as $id => $groups) {
                        // Sanity check!
                        foreach ($groups['add'] as $key => $value) {
                            if ($value == 0 || trim($value) == '') {
                                unset($groups['add'][$key]);
                            }
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}members
							SET id_group = {int:primary_group}, additional_groups = {string:additional_groups}
							WHERE id_member = {int:selected_member}', array('primary_group' => $groups['primary'], 'selected_member' => $id, 'additional_groups' => implode(',', $groups['add'])));
                    }
                    $lastLng = $user_info['language'];
                    foreach ($email_details as $email) {
                        $replacements = array('USERNAME' => $email['member_name'], 'GROUPNAME' => $email['group_name']);
                        $emaildata = loadEmailTemplate('mc_group_approve', $replacements, $email['language']);
                        sendmail($email['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 2);
                    }
                } else {
                    // Same as for approving, kind of.
                    $lastLng = $user_info['language'];
                    foreach ($email_details as $email) {
                        $custom_reason = isset($_POST['groupreason']) && isset($_POST['groupreason'][$email['rid']]) ? $_POST['groupreason'][$email['rid']] : '';
                        $replacements = array('USERNAME' => $email['member_name'], 'GROUPNAME' => $email['group_name']);
                        if (!empty($custom_reason)) {
                            $replacements['REASON'] = $custom_reason;
                        }
                        $emaildata = loadEmailTemplate(empty($custom_reason) ? 'mc_group_reject' : 'mc_group_reject_reason', $replacements, $email['language']);
                        sendmail($email['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 2);
                    }
                }
            }
            // Restore the current language.
            loadLanguage('ModerationCenter');
        }
    }
    // We're going to want this for making our list.
    require_once $sourcedir . '/Subs-List.php';
    // This is all the information required for a group listing.
    $listOptions = array('id' => 'group_request_list', 'title' => $txt['mc_group_requests'], 'width' => '100%', 'items_per_page' => $modSettings['defaultMaxMessages'], 'no_items_label' => $txt['mc_groupr_none_found'], 'base_href' => $scripturl . '?action=groups;sa=requests', 'default_sort_col' => 'member', 'get_items' => array('function' => 'list_getGroupRequests', 'params' => array($where, $where_parameters)), 'get_count' => array('function' => 'list_getGroupRequestCount', 'params' => array($where, $where_parameters)), 'columns' => array('member' => array('header' => array('value' => $txt['mc_groupr_member']), 'data' => array('db' => 'member_link'), 'sort' => array('default' => 'mem.member_name', 'reverse' => 'mem.member_name DESC')), 'group' => array('header' => array('value' => $txt['mc_groupr_group']), 'data' => array('db' => 'group_link'), 'sort' => array('default' => 'mg.group_name', 'reverse' => 'mg.group_name DESC')), 'reason' => array('header' => array('value' => $txt['mc_groupr_reason']), 'data' => array('db' => 'reason')), 'action' => array('header' => array('value' => '<input type="checkbox" class="input_check" onclick="invertAll(this, this.form);" />', 'style' => 'width: 4%;'), 'data' => array('sprintf' => array('format' => '<input type="checkbox" name="groupr[]" value="%1$d" class="input_check" />', 'params' => array('id' => false)), 'style' => 'text-align: center;'))), 'form' => array('href' => $scripturl . '?action=groups;sa=requests', 'include_sort' => true, 'include_start' => true, 'hidden_fields' => array($context['session_var'] => $context['session_id'])), 'additional_rows' => array(array('position' => 'bottom_of_list', 'value' => '
					<select name="req_action" onchange="if (this.value != 0 &amp;&amp; (this.value == \'reason\' || confirm(\'' . $txt['mc_groupr_warning'] . '\'))) this.form.submit();">
						<option value="0">' . $txt['with_selected'] . ':</option>
						<option value="0">---------------------</option>
						<option value="approve">' . $txt['mc_groupr_approve'] . '</option>
						<option value="reject">' . $txt['mc_groupr_reject'] . '</option>
						<option value="reason">' . $txt['mc_groupr_reject_w_reason'] . '</option>
					</select>
					<input type="submit" name="go" value="' . $txt['go'] . '" onclick="var sel = document.getElementById(\'req_action\'); if (sel.value != 0 &amp;&amp; sel.value != \'reason\' &amp;&amp; !confirm(\'' . $txt['mc_groupr_warning'] . '\')) return false;" class="button_submit" />', 'align' => 'right')));
    // Create the request list.
    createList($listOptions);
    $context['default_list'] = 'group_request_list';
}
Exemplo n.º 17
0
    $pageTitle .= ' :: ' . $userDetails['fullname'];
}
if (!empty($userDetails) && !empty($uid) && !empty($_GET['city_id']) && !empty($_GET['from_date']) && !empty($_GET['no_days'])) {
    //$horo = new Models_Horo();
    $city = findCity($_GET['city_id']);
    //clearing user sql
    $modelGeneral->clearCache($userSql);
    //updating the city
    if ($uid == $_SESSION['user']['id']) {
        $data = array();
        $md5Check = md5($userDetails['horo_cities']);
        $horo_cities[$city['id']] = $city['name'];
        $data['horo_cities'] = json_encode($horo_cities);
        $md5Check2 = md5($data['horo_cities']);
        if ($md5Check != $md5Check2) {
            updateSettings($_SESSION['user']['id'], $data);
        }
    }
    $fromDate = getDateTime($_GET['from_date']);
    $date = $fromDate['year'] . '-' . $fromDate['month'] . '-' . $fromDate['day'];
    $past = '';
    $returnResult = array();
    for ($counter = 0; $counter < $_GET['no_days']; $counter++) {
        $day = date('d', strtotime("{$date} +{$counter} day"));
        $month = date('m', strtotime("{$date} +{$counter} day"));
        $year = date('Y', strtotime("{$date} +{$counter} day"));
        for ($j = 0; $j < 24; $j = $j + 1) {
            $hour = $j;
            $dob = $year . '-' . $month . '-' . $day . ' ' . $hour . ':00:00';
            $data2 = array_merge($city, array('dob' => $dob));
            $result = $horo->match($userDetails, $data2);
Exemplo n.º 18
0
/**
* execute()
*
* @return
*/
function execute()
{
    global $smcFunc, $execute, $table_prefix;
    checkSession();
    if (empty($_POST['agree']) || empty($_POST['submit_ok'])) {
        fatal_error('How did you get here?', false);
    }
    // how many actioins to do on each loop
    $chunk = 5;
    // Only do these steps if we have not already started our loop
    if (!isset($_SESSION['db_cleaner'])) {
        // init
        $execute = array('tables' => array(), 'columns' => array(), 'indexes' => array(), 'settings' => array(), 'results' => array(), 'actions' => array());
        // build our to do arrays based on what the user selected.
        if (!empty($_POST['columns'])) {
            foreach ($_POST['columns'] as $table_name => $table) {
                if (!preg_match('~^[A-Za-z0-9_]+$~', $table_name)) {
                    continue;
                }
                foreach ($table as $column) {
                    if (preg_match('~^[A-Za-z0-9_]+$~', $column)) {
                        $execute['columns'][$table_name][] = $column;
                    }
                }
            }
        }
        if (!empty($_POST['indexes'])) {
            foreach ($_POST['indexes'] as $table_name => $table) {
                if (!preg_match('~^[A-Za-z0-9_]+$~', $table_name)) {
                    continue;
                }
                foreach ($table as $index) {
                    if (preg_match('~^[A-Za-z0-9_]+$~', $index)) {
                        $execute['indexes'][$table_name][] = $index;
                    }
                }
            }
        }
        if (!empty($_POST['tables'])) {
            foreach ($_POST['tables'] as $table) {
                if (preg_match('~^[A-Za-z0-9_]+$~', $table)) {
                    $execute['tables'][] = $table;
                }
            }
        }
        if (!empty($_POST['settings'])) {
            foreach ($_POST['settings'] as $table) {
                if (preg_match('~^[A-Za-z0-9_]+$~', $table)) {
                    $execute['settings'][] = $table;
                }
            }
        }
        // Step 1: build the remove data for extra index's
        foreach ($execute['indexes'] as $table_name => $table) {
            foreach ($table as $index) {
                $execute['actions'][] = array('prefix' => $table_prefix, 'table' => $table_name, 'index' => $index);
            }
        }
        // Step 2: build the remove data for extra columns
        foreach ($execute['columns'] as $table_name => $table) {
            foreach ($table as $column) {
                $execute['actions'][] = array('prefix' => $table_prefix, 'table' => $table_name, 'column' => $column);
            }
        }
        // Step 3: build the drop data for tables
        foreach ($execute['tables'] as $table) {
            $execute['actions'][] = array('prefix' => $table_prefix, 'table' => $table);
        }
        // Step 4: All those unused settings
        $execute['actions'][] = array('prefix' => $table_prefix, 'settings' => $execute['settings']);
        // save the data for future generations
        $_SESSION['db_cleaner']['execute'] = $execute;
        $_SESSION['db_cleaner']['work'] = count($execute['actions']);
        $_SESSION['db_cleaner']['done'] = 0;
    }
    // load up where we are on this pass
    $execute = $_SESSION['db_cleaner']['execute'];
    $done = $_SESSION['db_cleaner']['done'];
    $work = $_SESSION['db_cleaner']['work'];
    // Do some database work, but not to much :)
    $this_loop = 0;
    $done = isset($_SESSION['db_cleaner']['done']) ? $_SESSION['db_cleaner']['done'] : 0;
    for ($i = $done; $i < $work && $this_loop < $chunk; $i++, $this_loop++) {
        // lazy and don't want to type the whole thing in :)
        $todo = $execute['actions'][$i];
        // remove index, then columns, then tables
        if (isset($todo['index'])) {
            $execute['results']['index'][$todo['table']][$todo['index']] = $smcFunc['db_remove_index']($todo['prefix'] . $todo['table'], $todo['index']);
        }
        if (isset($todo['column'])) {
            $execute['results']['column'][$todo['table']][$todo['column']] = $smcFunc['db_remove_column']($todo['prefix'] . $todo['table'], $todo['column']);
        }
        if (isset($todo['table'])) {
            $execute['results']['table'][$todo['table']] = $smcFunc['db_drop_table']($todo['prefix'] . $todo['table']);
        }
        if (isset($todo['settings']) && count($todo['settings']) != 0) {
            global $modSettings;
            // Settings, do these as a 'single' step, first remove them from memory
            foreach ($todo['settings'] as $setting) {
                if (isset($modSettings[$setting])) {
                    unset($modSettings[$setting]);
                }
            }
            // And now from sight
            $execute['results']['settings'] = $smcFunc['db_query']('', 'DELETE FROM ' . $todo['prefix'] . 'settings WHERE variable IN ({array_string:variables})', array('variables' => $todo['settings']));
            // And let SMF know we have been mucking about
            updateSettings(array('settings_updated' => time()));
        }
    }
    // Are we done yet?? ... if not go round again
    $_SESSION['db_cleaner']['execute'] = $execute;
    if ($i < $work) {
        nextStep('db_cleaner', $i);
    } else {
        unset($_SESSION['db_cleaner']);
    }
}
Exemplo n.º 19
0
function moveTopics($topics, $toBoard)
{
    global $sourcedir, $user_info, $modSettings, $smcFunc;
    // Empty array?
    if (empty($topics)) {
        return;
    } elseif (is_numeric($topics)) {
        $topics = array($topics);
    }
    $num_topics = count($topics);
    $fromBoards = array();
    // Destination board empty or equal to 0?
    if (empty($toBoard)) {
        return;
    }
    // Are we moving to the recycle board?
    $isRecycleDest = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $toBoard;
    // Determine the source boards...
    $request = $smcFunc['db_query']('', '
		SELECT id_board, approved, COUNT(*) AS num_topics, SUM(unapproved_posts) AS unapproved_posts,
			SUM(num_replies) AS num_replies
		FROM {db_prefix}topics
		WHERE id_topic IN ({array_int:topics})
		GROUP BY id_board, approved', array('topics' => $topics));
    // Num of rows = 0 -> no topics found. Num of rows > 1 -> topics are on multiple boards.
    if ($smcFunc['db_num_rows']($request) == 0) {
        return;
    }
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        if (!isset($fromBoards[$row['id_board']]['num_posts'])) {
            $fromBoards[$row['id_board']] = array('num_posts' => 0, 'num_topics' => 0, 'unapproved_posts' => 0, 'unapproved_topics' => 0, 'id_board' => $row['id_board']);
        }
        // Posts = (num_replies + 1) for each approved topic.
        $fromBoards[$row['id_board']]['num_posts'] += $row['num_replies'] + ($row['approved'] ? $row['num_topics'] : 0);
        $fromBoards[$row['id_board']]['unapproved_posts'] += $row['unapproved_posts'];
        // Add the topics to the right type.
        if ($row['approved']) {
            $fromBoards[$row['id_board']]['num_topics'] += $row['num_topics'];
        } else {
            $fromBoards[$row['id_board']]['unapproved_topics'] += $row['num_topics'];
        }
    }
    $smcFunc['db_free_result']($request);
    // Move over the mark_read data. (because it may be read and now not by some!)
    $SaveAServer = max(0, $modSettings['maxMsgID'] - 50000);
    $request = $smcFunc['db_query']('', '
		SELECT lmr.id_member, lmr.id_msg, t.id_topic
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board
				AND lmr.id_msg > t.id_first_msg AND lmr.id_msg > {int:protect_lmr_msg})
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = lmr.id_member)
		WHERE t.id_topic IN ({array_int:topics})
			AND lmr.id_msg > IFNULL(lt.id_msg, 0)', array('protect_lmr_msg' => $SaveAServer, 'topics' => $topics));
    $log_topics = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        $log_topics[] = array($row['id_topic'], $row['id_member'], $row['id_msg']);
        // Prevent queries from getting too big. Taking some steam off.
        if (count($log_topics) > 500) {
            $smcFunc['db_insert']('replace', '{db_prefix}log_topics', array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), $log_topics, array('id_topic', 'id_member'));
            $log_topics = array();
        }
    }
    $smcFunc['db_free_result']($request);
    // Now that we have all the topics that *should* be marked read, and by which members...
    if (!empty($log_topics)) {
        // Insert that information into the database!
        $smcFunc['db_insert']('replace', '{db_prefix}log_topics', array('id_topic' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), $log_topics, array('id_topic', 'id_member'));
    }
    // Update the number of posts on each board.
    $totalTopics = 0;
    $totalPosts = 0;
    $totalUnapprovedTopics = 0;
    $totalUnapprovedPosts = 0;
    foreach ($fromBoards as $stats) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}boards
			SET
				num_posts = CASE WHEN {int:num_posts} > num_posts THEN 0 ELSE num_posts - {int:num_posts} END,
				num_topics = CASE WHEN {int:num_topics} > num_topics THEN 0 ELSE num_topics - {int:num_topics} END,
				unapproved_posts = CASE WHEN {int:unapproved_posts} > unapproved_posts THEN 0 ELSE unapproved_posts - {int:unapproved_posts} END,
				unapproved_topics = CASE WHEN {int:unapproved_topics} > unapproved_topics THEN 0 ELSE unapproved_topics - {int:unapproved_topics} END
			WHERE id_board = {int:id_board}', array('id_board' => $stats['id_board'], 'num_posts' => $stats['num_posts'], 'num_topics' => $stats['num_topics'], 'unapproved_posts' => $stats['unapproved_posts'], 'unapproved_topics' => $stats['unapproved_topics']));
        $totalTopics += $stats['num_topics'];
        $totalPosts += $stats['num_posts'];
        $totalUnapprovedTopics += $stats['unapproved_topics'];
        $totalUnapprovedPosts += $stats['unapproved_posts'];
    }
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}boards
		SET
			num_topics = num_topics + {int:total_topics},
			num_posts = num_posts + {int:total_posts},' . ($isRecycleDest ? '
			unapproved_posts = {int:no_unapproved}, unapproved_topics = {int:no_unapproved}' : '
			unapproved_posts = unapproved_posts + {int:total_unapproved_posts},
			unapproved_topics = unapproved_topics + {int:total_unapproved_topics}') . '
		WHERE id_board = {int:id_board}', array('id_board' => $toBoard, 'total_topics' => $totalTopics, 'total_posts' => $totalPosts, 'total_unapproved_topics' => $totalUnapprovedTopics, 'total_unapproved_posts' => $totalUnapprovedPosts, 'no_unapproved' => 0));
    // Move the topic.  Done.  :P
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}topics
		SET id_board = {int:id_board}' . ($isRecycleDest ? ',
			unapproved_posts = {int:no_unapproved}, approved = {int:is_approved}' : '') . '
		WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics, 'is_approved' => 1, 'no_unapproved' => 0));
    // If this was going to the recycle bin, check what messages are being recycled, and remove them from the queue.
    if ($isRecycleDest && ($totalUnapprovedTopics || $totalUnapprovedPosts)) {
        $request = $smcFunc['db_query']('', '
			SELECT id_msg
			FROM {db_prefix}messages
			WHERE id_topic IN ({array_int:topics})
				and approved = {int:not_approved}', array('topics' => $topics, 'not_approved' => 0));
        $approval_msgs = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $approval_msgs[] = $row['id_msg'];
        }
        $smcFunc['db_free_result']($request);
        // Empty the approval queue for these, as we're going to approve them next.
        if (!empty($approval_msgs)) {
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}approval_queue
				WHERE id_msg IN ({array_int:message_list})
					AND id_attach = {int:id_attach}', array('message_list' => $approval_msgs, 'id_attach' => 0));
        }
        // Get all the current max and mins.
        $request = $smcFunc['db_query']('', '
			SELECT id_topic, id_first_msg, id_last_msg
			FROM {db_prefix}topics
			WHERE id_topic IN ({array_int:topics})', array('topics' => $topics));
        $topicMaxMin = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $topicMaxMin[$row['id_topic']] = array('min' => $row['id_first_msg'], 'max' => $row['id_last_msg']);
        }
        $smcFunc['db_free_result']($request);
        // Check the MAX and MIN are correct.
        $request = $smcFunc['db_query']('', '
			SELECT id_topic, MIN(id_msg) AS first_msg, MAX(id_msg) AS last_msg
			FROM {db_prefix}messages
			WHERE id_topic IN ({array_int:topics})
			GROUP BY id_topic', array('topics' => $topics));
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // If not, update.
            if ($row['first_msg'] != $topicMaxMin[$row['id_topic']]['min'] || $row['last_msg'] != $topicMaxMin[$row['id_topic']]['max']) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}topics
					SET id_first_msg = {int:first_msg}, id_last_msg = {int:last_msg}
					WHERE id_topic = {int:selected_topic}', array('first_msg' => $row['first_msg'], 'last_msg' => $row['last_msg'], 'selected_topic' => $row['id_topic']));
            }
        }
        $smcFunc['db_free_result']($request);
    }
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}messages
		SET id_board = {int:id_board}' . ($isRecycleDest ? ',approved = {int:is_approved}' : '') . '
		WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics, 'is_approved' => 1));
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}log_reported
		SET id_board = {int:id_board}
		WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics));
    $smcFunc['db_query']('', '
		UPDATE {db_prefix}calendar
		SET id_board = {int:id_board}
		WHERE id_topic IN ({array_int:topics})', array('id_board' => $toBoard, 'topics' => $topics));
    // Mark target board as seen, if it was already marked as seen before.
    $request = $smcFunc['db_query']('', '
		SELECT (IFNULL(lb.id_msg, 0) >= b.id_msg_updated) AS isSeen
		FROM {db_prefix}boards AS b
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
		WHERE b.id_board = {int:id_board}', array('current_member' => $user_info['id'], 'id_board' => $toBoard));
    list($isSeen) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    if (!empty($isSeen) && !$user_info['is_guest']) {
        $smcFunc['db_insert']('replace', '{db_prefix}log_boards', array('id_board' => 'int', 'id_member' => 'int', 'id_msg' => 'int'), array($toBoard, $user_info['id'], $modSettings['maxMsgID']), array('id_board', 'id_member'));
    }
    // Update 'em pesky stats.
    updateStats('topic');
    updateStats('message');
    updateSettings(array('calendar_updated' => time()));
    // Update the cache?
    if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3) {
        foreach ($topics as $topic_id) {
            cache_put_data('topic_board-' . $topic_id, null, 120);
        }
    }
    require_once $sourcedir . '/Subs-Post.php';
    $updates = array_keys($fromBoards);
    $updates[] = $toBoard;
    updateLastMessages(array_unique($updates));
}
 /**
  * Activate an account.
  * This function is called from the profile account actions area.
  */
 public function action_activateaccount()
 {
     global $context, $user_profile, $modSettings;
     isAllowedTo('moderate_forum');
     $memID = currentMemberID();
     if (isset($_REQUEST['save']) && isset($user_profile[$memID]['is_activated']) && $user_profile[$memID]['is_activated'] != 1) {
         require_once SUBSDIR . '/Members.subs.php';
         // If we are approving the deletion of an account, we do something special ;)
         if ($user_profile[$memID]['is_activated'] == 4) {
             deleteMembers($context['id_member']);
             redirectexit();
         }
         // Actually update this member now, as it guarantees the unapproved count can't get corrupted.
         approveMembers(array('members' => array($context['id_member']), 'activated_status' => $user_profile[$memID]['is_activated']));
         // Log what we did?
         logAction('approve_member', array('member' => $memID), 'admin');
         // If we are doing approval, update the stats for the member just in case.
         if (in_array($user_profile[$memID]['is_activated'], array(3, 4, 13, 14))) {
             updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > 1 ? $modSettings['unapprovedMembers'] - 1 : 0));
         }
         // Make sure we update the stats too.
         updateStats('member', false);
     }
     // Leave it be...
     redirectexit('action=profile;u=' . $memID . ';area=summary');
 }
Exemplo n.º 21
0
 * @version 1.0.0 Beta 1
 */
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('ELK')) {
    $_GET['debug'] = 'Blue Dream!';
    require_once dirname(__FILE__) . '/SSI.php';
} elseif (!defined('ELK')) {
    exit('<b>Error:</b> Cannot install - please verify you put this in the same place as ELK\'s index.php.');
}
global $modSettings, $package_cache;
$defaults = array('sp_portal_mode' => 1, 'sp_disableForumRedirect' => 1, 'showleft' => 1, 'showright' => 1, 'leftwidth' => 200, 'rightwidth' => 200, 'sp_enableIntegration' => 1, 'sp_adminIntegrationHide' => 1, 'sp_resize_images' => 1, 'sp_articles_index_per_page' => 5, 'sp_articles_index_total' => 20, 'sp_articles_per_page' => 10, 'sp_articles_comments_per_page' => 20);
$updates = array('sp_version' => '2.4');
foreach ($defaults as $index => $value) {
    if (!isset($modSettings[$index])) {
        $updates[$index] = $value;
    }
}
updateSettings($updates);
$standalone_file = BOARDDIR . '/PortalStandalone.php';
if (isset($package_cache[$standalone_file])) {
    $package_cache[$standalone_file] = str_replace('full/path/to/forum', BOARDDIR, $package_cache[$standalone_file]);
} elseif (file_exists($standalone_file)) {
    $current_data = file_get_contents($standalone_file);
    if (strpos($current_data, 'full/path/to/forum') !== false) {
        $fp = fopen($standalone_file, 'w+');
        fwrite($fp, str_replace('full/path/to/forum', BOARDDIR, $current_data));
        fclose($fp);
    }
}
if (ELK == 'SSI') {
    echo 'Settings changes were carried out successfully.';
}
Exemplo n.º 22
0
function reloadSettings()
{
    global $modSettings, $db_prefix, $boarddir, $func, $txt, $db_character_set;
    global $mysql_set_mode, $context;
    // This makes it possible to have SMF automatically change the sql_mode and autocommit if needed.
    if (isset($mysql_set_mode) && $mysql_set_mode === true) {
        db_query("SET sql_mode='', AUTOCOMMIT=1", false, false);
    }
    // Most database systems have not set UTF-8 as their default input charset.
    if (isset($db_character_set) && preg_match('~^\\w+$~', $db_character_set) === 1) {
        db_query("\n\t\t\tSET NAMES {$db_character_set}", __FILE__, __LINE__);
    }
    // Try to load it from the cache first; it'll never get cached if the setting is off.
    if (($modSettings = cache_get_data('modSettings', 90)) == null) {
        $request = db_query("\n\t\t\tSELECT variable, value\n\t\t\tFROM {$db_prefix}settings", false, false);
        $modSettings = array();
        if (!$request) {
            db_fatal_error();
        }
        while ($row = mysql_fetch_row($request)) {
            $modSettings[$row[0]] = $row[1];
        }
        mysql_free_result($request);
        // Do a few things to protect against missing settings or settings with invalid values...
        if (empty($modSettings['defaultMaxTopics']) || $modSettings['defaultMaxTopics'] <= 0 || $modSettings['defaultMaxTopics'] > 999) {
            $modSettings['defaultMaxTopics'] = 20;
        }
        if (empty($modSettings['defaultMaxMessages']) || $modSettings['defaultMaxMessages'] <= 0 || $modSettings['defaultMaxMessages'] > 999) {
            $modSettings['defaultMaxMessages'] = 15;
        }
        if (empty($modSettings['defaultMaxMembers']) || $modSettings['defaultMaxMembers'] <= 0 || $modSettings['defaultMaxMembers'] > 999) {
            $modSettings['defaultMaxMembers'] = 30;
        }
        if (!empty($modSettings['cache_enable'])) {
            cache_put_data('modSettings', $modSettings, 90);
        }
    }
    // UTF-8 in regular expressions is unsupported on PHP(win) versions < 4.2.3.
    $utf8 = (empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8' && (strpos(strtolower(PHP_OS), 'win') === false || @version_compare(PHP_VERSION, '4.2.3') != -1);
    // Set a list of common functions.
    $ent_list = empty($modSettings['disableEntityCheck']) ? '&(#\\d{1,7}|quot|amp|lt|gt|nbsp);' : '&(#021|quot|amp|lt|gt|nbsp);';
    $ent_check = empty($modSettings['disableEntityCheck']) ? array('preg_replace(\'~(&#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~e\', \'$func[\\\'entity_fix\\\'](\\\'\\2\\\')\', ', ')') : array('', '');
    // Preg_replace can handle complex characters only for higher PHP versions.
    $space_chars = $utf8 ? @version_compare(PHP_VERSION, '4.3.3') != -1 ? '\\x{A0}\\x{2000}-\\x{200F}\\x{201F}\\x{202F}\\x{3000}\\x{FEFF}' : pack('C*', 0xc2, 0xa0, 0xe2, 0x80, 0x80) . '-' . pack('C*', 0xe2, 0x80, 0x8f, 0xe2, 0x80, 0x9f, 0xe2, 0x80, 0xaf, 0xe2, 0x80, 0x9f, 0xe3, 0x80, 0x80, 0xef, 0xbb, 0xbf) : '\\xA0';
    $func = array('entity_fix' => create_function('$string', '
			$num = substr($string, 0, 1) === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
			return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) ? \'\' : \'&#\' . $num . \';\';'), 'substr' => create_function('$string, $start, $length = null', '
			global $func;
			$ent_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$string', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
			return $length === null ? implode(\'\', array_slice($ent_arr, $start)) : implode(\'\', array_slice($ent_arr, $start, $length));'), 'strlen' => create_function('$string', '
			global $func;
			return strlen(preg_replace(\'~' . $ent_list . ($utf8 ? '|.~u' : '~') . '\', \'_\', ' . implode('$string', $ent_check) . '));'), 'strpos' => create_function('$haystack, $needle, $offset = 0', '
			global $func;
			$haystack_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$haystack', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
			$haystack_size = count($haystack_arr);
			if (strlen($needle) === 1)
			{
				$result = array_search($needle, array_slice($haystack_arr, $offset));
				return is_int($result) ? $result + $offset : false;
			}
			else
			{
				$needle_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\',  ' . implode('$needle', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
				$needle_size = count($needle_arr);

				$result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
				while (is_int($result))
				{
					$offset += $result;
					if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr)
						return $offset;
					$result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
				}
				return false;
			}'), 'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'ISO-8859-1\'', '
			global $func;
			return ' . strtr($ent_check[0], array('&' => '&amp;')) . 'htmlspecialchars($string, $quote_style, ' . ($utf8 ? '\'UTF-8\'' : '$charset') . ')' . $ent_check[1] . ';'), 'htmltrim' => create_function('$string', '
			global $func;
			return preg_replace(\'~^([ \\t\\n\\r\\x0B\\x00' . $space_chars . ']|&nbsp;)+|([ \\t\\n\\r\\x0B\\x00' . $space_chars . ']|&nbsp;)+$~' . ($utf8 ? 'u' : '') . '\', \'\', ' . implode('$string', $ent_check) . ');'), 'truncate' => create_function('$string, $length', (empty($modSettings['disableEntityCheck']) ? '
			global $func;
			$string = ' . implode('$string', $ent_check) . ';' : '') . '
			preg_match(\'~^(' . $ent_list . '|.){\' . $func[\'strlen\'](substr($string, 0, $length)) . \'}~' . ($utf8 ? 'u' : '') . '\', $string, $matches);
			$string = $matches[0];
			while (strlen($string) > $length)
				$string = preg_replace(\'~(' . $ent_list . '|.)$~' . ($utf8 ? 'u' : '') . '\', \'\', $string);
			return $string;'), 'strtolower' => $utf8 ? function_exists('mb_strtolower') ? create_function('$string', '
			return mb_strtolower($string, \'UTF-8\');') : create_function('$string', '
			global $sourcedir;
			require_once($sourcedir . \'/Subs-Charset.php\');
			return utf8_strtolower($string);') : 'strtolower', 'strtoupper' => $utf8 ? function_exists('mb_strtoupper') ? create_function('$string', '
			return mb_strtoupper($string, \'UTF-8\');') : create_function('$string', '
			global $sourcedir;
			require_once($sourcedir . \'/Subs-Charset.php\');
			return utf8_strtoupper($string);') : 'strtoupper', 'ucfirst' => $utf8 ? create_function('$string', '
			global $func;
			return $func[\'strtoupper\']($func[\'substr\']($string, 0, 1)) . $func[\'substr\']($string, 1);') : 'ucfirst', 'ucwords' => $utf8 ? function_exists('mb_convert_case') ? create_function('$string', '
			return mb_convert_case($string, MB_CASE_TITLE, \'UTF-8\');') : create_function('$string', '
			global $func;
			$words = preg_split(\'~([\\s\\r\\n\\t]+)~\', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
			for ($i = 0, $n = count($words); $i < $n; $i += 2)
				$words[$i] = $func[\'ucfirst\']($words[$i]);
			return implode(\'\', $words);') : 'ucwords');
    // Setting the timezone is a requirement for some functions in PHP >= 5.1.
    if (isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set')) {
        date_default_timezone_set($modSettings['default_timezone']);
    }
    // Check the load averages?
    if (!empty($modSettings['loadavg_enable'])) {
        if (($modSettings['load_average'] = cache_get_data('loadavg', 90)) == null) {
            $modSettings['load_average'] = @file_get_contents('/proc/loadavg');
            if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) != 0) {
                $modSettings['load_average'] = (double) $matches[1];
            } elseif (($modSettings['load_average'] = @`uptime`) != null && preg_match('~load average[s]?: (\\d+\\.\\d+), (\\d+\\.\\d+), (\\d+\\.\\d+)~i', $modSettings['load_average'], $matches) != 0) {
                $modSettings['load_average'] = (double) $matches[1];
            } else {
                unset($modSettings['load_average']);
            }
            if (!empty($modSettings['load_average'])) {
                cache_put_data('loadavg', $modSettings['load_average'], 90);
            }
        }
        if (!empty($modSettings['loadavg_forum']) && !empty($modSettings['load_average']) && $modSettings['load_average'] >= $modSettings['loadavg_forum']) {
            db_fatal_error(true);
        }
    }
    // Integration is cool.
    if (defined('SMF_INTEGRATION_SETTINGS')) {
        $modSettings = unserialize(SMF_INTEGRATION_SETTINGS) + $modSettings;
    }
    if (isset($modSettings['integrate_pre_include']) && file_exists(strtr($modSettings['integrate_pre_include'], array('$boarddir' => $boarddir)))) {
        require_once strtr($modSettings['integrate_pre_include'], array('$boarddir' => $boarddir));
    }
    if (isset($modSettings['integrate_pre_load']) && function_exists($modSettings['integrate_pre_load'])) {
        call_user_func($modSettings['integrate_pre_load']);
    }
    // Is it time again to optimize the database?
    if (empty($modSettings['autoOptDatabase']) || $modSettings['autoOptLastOpt'] + $modSettings['autoOptDatabase'] * 3600 * 24 >= time() || SMF == 'SSI') {
        return;
    }
    if (!empty($modSettings['load_average']) && !empty($modSettings['loadavg_auto_opt']) && $modSettings['load_average'] >= $modSettings['loadavg_auto_opt']) {
        return;
    }
    if (!empty($modSettings['autoOptMaxOnline'])) {
        $request = db_query("\n\t\t\tSELECT COUNT(*)\n\t\t\tFROM {$db_prefix}log_online", __FILE__, __LINE__);
        list($dont_do_it) = mysql_fetch_row($request);
        mysql_free_result($request);
        if ($dont_do_it > $modSettings['autoOptMaxOnline']) {
            return;
        }
    }
    // Handle if things are prefixed with a database name.
    if (preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) != 0) {
        $request = db_query("\n\t\t\tSHOW TABLES\n\t\t\tFROM `" . strtr($match[1], array('`' => '')) . "`\n\t\t\tLIKE '" . str_replace('_', '\\_', $match[2]) . "%'", __FILE__, __LINE__);
    } else {
        $request = db_query("\n\t\t\tSHOW TABLES\n\t\t\tLIKE '" . str_replace('_', '\\_', $db_prefix) . "%'", __FILE__, __LINE__);
    }
    $tables = array();
    while ($row = mysql_fetch_row($request)) {
        $tables[] = $row[0];
    }
    mysql_free_result($request);
    updateSettings(array('autoOptLastOpt' => time()));
    // Don't bail if the user does.
    ignore_user_abort(true);
    // Do them one at a time for locking reasons...
    foreach ($tables as $table) {
        db_query("\n\t\t\tOPTIMIZE TABLE `{$table}`", __FILE__, __LINE__);
    }
}
Exemplo n.º 23
0
function TagsSettings2()
{
    // Check permission
    isAllowedTo('smftags_manage');
    // Get the settings
    $smftags_set_mintaglength = (int) $_REQUEST['smftags_set_mintaglength'];
    $smftags_set_maxtaglength = (int) $_REQUEST['smftags_set_maxtaglength'];
    $smftags_set_maxtags = (int) $_REQUEST['smftags_set_maxtags'];
    $smftags_set_cloud_tags_per_row = (int) $_REQUEST['smftags_set_cloud_tags_per_row'];
    $smftags_set_cloud_tags_to_show = (int) $_REQUEST['smftags_set_cloud_tags_to_show'];
    $smftags_set_cloud_max_font_size_precent = (int) $_REQUEST['smftags_set_cloud_max_font_size_precent'];
    $smftags_set_cloud_min_font_size_precent = (int) $_REQUEST['smftags_set_cloud_min_font_size_precent'];
    // Save the setting information
    updateSettings(array('smftags_set_maxtags' => $smftags_set_maxtags, 'smftags_set_mintaglength' => $smftags_set_mintaglength, 'smftags_set_maxtaglength' => $smftags_set_maxtaglength, 'smftags_set_cloud_tags_per_row' => $smftags_set_cloud_tags_per_row, 'smftags_set_cloud_tags_to_show' => $smftags_set_cloud_tags_to_show, 'smftags_set_cloud_max_font_size_precent' => $smftags_set_cloud_max_font_size_precent, 'smftags_set_cloud_min_font_size_precent' => $smftags_set_cloud_min_font_size_precent));
    // Redirect to the admin section
    redirectexit('action=admin;area=tags;sa=admin');
}
Exemplo n.º 24
0
function checkActivation()
{
    global $context, $txt, $scripturl, $user_settings, $modSettings;
    if (!isset($context['login_errors'])) {
        $context['login_errors'] = array();
    }
    // What is the true activation status of this account?
    $activation_status = $user_settings['is_activated'] > 10 ? $user_settings['is_activated'] - 10 : $user_settings['is_activated'];
    // Check if the account is activated - COPPA first...
    if ($activation_status == 5) {
        $context['login_errors'][] = $txt['coppa_no_concent'] . ' <a href="' . $scripturl . '?action=coppa;member=' . $user_settings['id_member'] . '">' . $txt['coppa_need_more_details'] . '</a>';
        return false;
    } elseif ($activation_status == 3) {
        fatal_lang_error('still_awaiting_approval', 'user');
    } elseif ($activation_status == 4) {
        if (isset($_REQUEST['undelete'])) {
            updateMemberData($user_settings['id_member'], array('is_activated' => 1));
            updateSettings(array('unapprovedMembers' => $modSettings['unapprovedMembers'] > 0 ? $modSettings['unapprovedMembers'] - 1 : 0));
        } else {
            $context['login_errors'][] = $txt['awaiting_delete_account'];
            $context['login_show_undelete'] = true;
            return false;
        }
    } elseif ($activation_status != 1) {
        log_error($txt['activate_not_completed1'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', false);
        $context['login_errors'][] = $txt['activate_not_completed1'] . ' <a href="' . $scripturl . '?action=activate;sa=resend;u=' . $user_settings['id_member'] . '">' . $txt['activate_not_completed2'] . '</a>';
        return false;
    }
    return true;
}
Exemplo n.º 25
0
function InstallSmileySet()
{
    global $sourcedir, $boarddir, $modSettings;
    isAllowedTo('manage_smileys');
    checkSession('request');
    require_once $sourcedir . '/Subs-Package.php';
    $name = strtok(basename(isset($_FILES['set_gz']) ? $_FILES['set_gz']['name'] : $_REQUEST['set_gz']), '.');
    $name = preg_replace(array('/\\s/', '/\\.[\\.]+/', '/[^\\w_\\.\\-]/'), array('_', '.', ''), $name);
    // !!! Decide: overwrite or not?
    if (isset($_FILES['set_gz']) && is_uploaded_file($_FILES['set_gz']['tmp_name']) && (@ini_get('open_basedir') != '' || file_exists($_FILES['set_gz']['tmp_name']))) {
        $extracted = read_tgz_file($_FILES['set_gz']['tmp_name'], $boarddir . '/Smileys/' . $name);
    } elseif (isset($_REQUEST['set_gz'])) {
        checkSession('request');
        // Check that the theme is from simplemachines.org, for now... maybe add mirroring later.
        if (preg_match('~^http://[\\w_\\-]+\\.simplemachines\\.org/~', $_REQUEST['set_gz']) == 0 || strpos($_REQUEST['set_gz'], 'dlattach') !== false) {
            fatal_lang_error('not_on_simplemachines');
        }
        $extracted = read_tgz_file($_REQUEST['set_gz'], $boarddir . '/Smileys/' . $name);
    } else {
        redirectexit('action=smileys');
    }
    updateSettings(array('smiley_sets_known' => addslashes($modSettings['smiley_sets_known'] . ',' . $name), 'smiley_sets_names' => addslashes($modSettings['smiley_sets_names'] . "\n" . strtok(basename(isset($_FILES['set_gz']) ? $_FILES['set_gz']['name'] : $_REQUEST['set_gz']), '.'))));
    cache_put_data('parsing_smileys', null, 480);
    cache_put_data('posting_smileys', null, 480);
    // !!! Add some confirmation?
    redirectexit('action=smileys');
}
Exemplo n.º 26
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);
}
Exemplo n.º 27
0
}
//Create Tags Table
db_query("CREATE TABLE IF NOT EXISTS {$db_prefix}tags\n(ID_TAG mediumint(8) NOT NULL auto_increment,\ntag tinytext NOT NULL,\napproved tinyint(4) NOT NULL default '0',\n`parent_id` MEDIUMINT(8) NULL DEFAULT NULL,\n`taggable` TINYINT(4) NOT NULL DEFAULT '1',\nPRIMARY KEY  (ID_TAG))", __FILE__, __LINE__);
// Create Tags Log
db_query("CREATE TABLE IF NOT EXISTS {$db_prefix}tags_log\n(ID int(11) NOT NULL auto_increment,\nID_TAG mediumint(8) unsigned NOT NULL default '0',\nID_TOPIC mediumint(8) unsigned NOT NULL default '0',\nID_MEMBER mediumint(8) unsigned NOT NULL default '0',\napproved` TINYINT(4) NOT NULL DEFAULT '0',\nPRIMARY KEY  (ID))", __FILE__, __LINE__);
if ($modSettings['smftagsver'] != '3.0') {
    // add unique constraint to tags log table for ease of use (functions like merge rely on this)
    db_query("DELETE FROM b USING `{$db_prefix}tags_log` AS a, `{$db_prefix}tags_log` as b WHERE a.id != b.id AND a.id_tag = b.id_tag AND a.id_topic = b.id_topic");
    db_query("ALTER TABLE {$db_prefix}tags_log ADD UNIQUE INDEX(`id_tag`, `id_topic`)");
    // and also to the tags table as a safeguard for stupid cases we must also change to VARCHAR
    db_query("ALTER TABLE  `{$db_prefix}tags` CHANGE  `tag`  `tag` VARCHAR(64) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL");
    db_query("ALTER TABLE  `{$db_prefix}tags` ADD UNIQUE (`tag`)");
    // approve all pre-existing tags and taggings
    db_query("UPDATE `{$db_prefix}tags` SET approved = 1", __FILE__, __LINE__);
    db_query("UPDATE `{$db_prefix}tags_log` SET approved = 1", __FILE__, __LINE__);
    updateSettings(array('smftagsver' => '3.0'));
}
//Insert the settings
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_mintaglength', '3')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_maxtaglength', '64')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_maxtags', '10')", __FILE__, __LINE__);
// Tags Cloud settings
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_cloud_tags_per_row', '5')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_cloud_tags_to_show', '50')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_cloud_max_font_size_precent', '250')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_cloud_min_font_size_precent', '100')", __FILE__, __LINE__);
// default to the former defaults for minimal confusion, but only if not already there
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_listtags', '0')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_manualtags', '1')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_display_top', '1')", __FILE__, __LINE__);
db_query("INSERT IGNORE INTO {$db_prefix}settings VALUES ('smftags_set_display_bottom', '0')", __FILE__, __LINE__);
Exemplo n.º 28
0
function ConvertUtf8()
{
    global $scripturl, $context, $txt, $language, $db_character_set;
    global $modSettings, $user_info, $sourcedir, $smcFunc, $db_prefix;
    // Show me your badge!
    isAllowedTo('admin_forum');
    // The character sets used in SMF's language files with their db equivalent.
    $charsets = array('big5' => 'big5', 'gbk' => 'gbk', 'ISO-8859-1' => 'latin1', 'ISO-8859-2' => 'latin2', 'ISO-8859-9' => 'latin5', 'ISO-8859-15' => 'latin9', 'tis-620' => 'tis620', 'UTF-8' => 'utf8', 'windows-1251' => 'cp1251', 'windows-1253' => 'utf8', 'windows-1255' => 'utf8', 'windows-1256' => 'cp1256');
    // Get a list of character sets supported by your MySQL server.
    $request = $smcFunc['db_query']('', '
		SHOW CHARACTER SET', array());
    $db_charsets = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        $db_charsets[] = $row['Charset'];
    }
    $smcFunc['db_free_result']($request);
    // Character sets supported by both MySQL and SMF's language files.
    $charsets = array_intersect($charsets, $db_charsets);
    // This is for the first screen telling backups is good.
    if (!isset($_POST['proceed'])) {
        // Character set conversions are only supported as of MySQL 4.1.2.
        if (version_compare('4.1.2', preg_replace('~\\-.+?$~', '', $smcFunc['db_server_info']())) > 0) {
            fatal_lang_error('utf8_db_version_too_low');
        }
        // Use the messages.body column as indicator for the database charset.
        $request = $smcFunc['db_query']('', '
			SHOW FULL COLUMNS
			FROM {db_prefix}messages
			LIKE {string:body_like}', array('body_like' => 'body'));
        $column_info = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        // A collation looks like latin1_swedish. We only need the character set.
        list($context['database_charset']) = explode('_', $column_info['Collation']);
        $context['database_charset'] = in_array($context['database_charset'], $charsets) ? array_search($context['database_charset'], $charsets) : $context['database_charset'];
        // No need to convert to UTF-8 if it already is.
        if ($db_character_set === 'utf8' && !empty($modSettings['global_character_set']) && $modSettings['global_character_set'] === 'UTF-8') {
            fatal_lang_error('utf8_already_utf8');
        }
        // Cannot do conversion if using a fulltext index
        if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext') {
            fatal_lang_error('utf8_cannot_convert_fulltext');
        }
        // Grab the character set from the default language file.
        loadLanguage('index', $language, true);
        $context['charset_detected'] = $txt['lang_character_set'];
        $context['charset_about_detected'] = sprintf($txt['utf8_detected_charset'], $language, $context['charset_detected']);
        // Go back to your own language.
        loadLanguage('index', $user_info['language'], true);
        // Show a warning if the character set seems not to be supported.
        if (!isset($charsets[strtr(strtolower($context['charset_detected']), array('utf' => 'UTF', 'iso' => 'ISO'))])) {
            $context['charset_warning'] = sprintf($txt['utf8_charset_not_supported'], $txt['lang_character_set']);
            // Default to ISO-8859-1.
            $context['charset_detected'] = 'ISO-8859-1';
        }
        $context['charset_list'] = array_keys($charsets);
        $context['page_title'] = $txt['utf8_title'];
        $context['sub_template'] = 'convert_utf8';
        return;
    }
    // After this point we're starting the conversion. But first: session check.
    checkSession();
    // Translation table for the character sets not native for MySQL.
    $translation_tables = array('windows-1255' => array('0x81' => '\'\'', '0x8A' => '\'\'', '0x8C' => '\'\'', '0x8D' => '\'\'', '0x8E' => '\'\'', '0x8F' => '\'\'', '0x90' => '\'\'', '0x9A' => '\'\'', '0x9C' => '\'\'', '0x9D' => '\'\'', '0x9E' => '\'\'', '0x9F' => '\'\'', '0xCA' => '\'\'', '0xD9' => '\'\'', '0xDA' => '\'\'', '0xDB' => '\'\'', '0xDC' => '\'\'', '0xDD' => '\'\'', '0xDE' => '\'\'', '0xDF' => '\'\'', '0xFB' => '\'\'', '0xFC' => '\'\'', '0xFF' => '\'\'', '0xC2' => '0xFF', '0x80' => '0xFC', '0xE2' => '0xFB', '0xA0' => '0xC2A0', '0xA1' => '0xC2A1', '0xA2' => '0xC2A2', '0xA3' => '0xC2A3', '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7', '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB', '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE', '0xAF' => '0xC2AF', '0xB0' => '0xC2B0', '0xB1' => '0xC2B1', '0xB2' => '0xC2B2', '0xB3' => '0xC2B3', '0xB4' => '0xC2B4', '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7', '0xB8' => '0xC2B8', '0xB9' => '0xC2B9', '0xBB' => '0xC2BB', '0xBC' => '0xC2BC', '0xBD' => '0xC2BD', '0xBE' => '0xC2BE', '0xBF' => '0xC2BF', '0xD7' => '0xD7B3', '0xD1' => '0xD781', '0xD4' => '0xD7B0', '0xD5' => '0xD7B1', '0xD6' => '0xD7B2', '0xE0' => '0xD790', '0xEA' => '0xD79A', '0xEC' => '0xD79C', '0xED' => '0xD79D', '0xEE' => '0xD79E', '0xEF' => '0xD79F', '0xF0' => '0xD7A0', '0xF1' => '0xD7A1', '0xF2' => '0xD7A2', '0xF3' => '0xD7A3', '0xF5' => '0xD7A5', '0xF6' => '0xD7A6', '0xF7' => '0xD7A7', '0xF8' => '0xD7A8', '0xF9' => '0xD7A9', '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6', '0x86' => '0xE280A0', '0x87' => '0xE280A1', '0x89' => '0xE280B0', '0x8B' => '0xE280B9', '0x93' => '0xE2809C', '0x94' => '0xE2809D', '0x95' => '0xE280A2', '0x97' => '0xE28094', '0x99' => '0xE284A2', '0xC0' => '0xD6B0', '0xC1' => '0xD6B1', '0xC3' => '0xD6B3', '0xC4' => '0xD6B4', '0xC5' => '0xD6B5', '0xC6' => '0xD6B6', '0xC7' => '0xD6B7', '0xC8' => '0xD6B8', '0xC9' => '0xD6B9', '0xCB' => '0xD6BB', '0xCC' => '0xD6BC', '0xCD' => '0xD6BD', '0xCE' => '0xD6BE', '0xCF' => '0xD6BF', '0xD0' => '0xD780', '0xD2' => '0xD782', '0xE3' => '0xD793', '0xE4' => '0xD794', '0xE5' => '0xD795', '0xE7' => '0xD797', '0xE9' => '0xD799', '0xFD' => '0xE2808E', '0xFE' => '0xE2808F', '0x92' => '0xE28099', '0x83' => '0xC692', '0xD3' => '0xD783', '0x88' => '0xCB86', '0x98' => '0xCB9C', '0x91' => '0xE28098', '0x96' => '0xE28093', '0xBA' => '0xC3B7', '0x9B' => '0xE280BA', '0xAA' => '0xC397', '0xA4' => '0xE282AA', '0xE1' => '0xD791', '0xE6' => '0xD796', '0xE8' => '0xD798', '0xEB' => '0xD79B', '0xF4' => '0xD7A4', '0xFA' => '0xD7AA', '0xFF' => '0xD6B2', '0xFC' => '0xE282AC', '0xFB' => '0xD792'), 'windows-1253' => array('0x81' => '\'\'', '0x88' => '\'\'', '0x8A' => '\'\'', '0x8C' => '\'\'', '0x8D' => '\'\'', '0x8E' => '\'\'', '0x8F' => '\'\'', '0x90' => '\'\'', '0x98' => '\'\'', '0x9A' => '\'\'', '0x9C' => '\'\'', '0x9D' => '\'\'', '0x9E' => '\'\'', '0x9F' => '\'\'', '0xAA' => '\'\'', '0xD2' => '\'\'', '0xFF' => '\'\'', '0xCE' => '0xCE9E', '0xB8' => '0xCE88', '0xBA' => '0xCE8A', '0xBC' => '0xCE8C', '0xBE' => '0xCE8E', '0xBF' => '0xCE8F', '0xC0' => '0xCE90', '0xC8' => '0xCE98', '0xCA' => '0xCE9A', '0xCC' => '0xCE9C', '0xCD' => '0xCE9D', '0xCF' => '0xCE9F', '0xDA' => '0xCEAA', '0xE8' => '0xCEB8', '0xEA' => '0xCEBA', '0xEC' => '0xCEBC', '0xEE' => '0xCEBE', '0xEF' => '0xCEBF', '0xC2' => '0xFF', '0xBD' => '0xC2BD', '0xED' => '0xCEBD', '0xB2' => '0xC2B2', '0xA0' => '0xC2A0', '0xA3' => '0xC2A3', '0xA4' => '0xC2A4', '0xA5' => '0xC2A5', '0xA6' => '0xC2A6', '0xA7' => '0xC2A7', '0xA8' => '0xC2A8', '0xA9' => '0xC2A9', '0xAB' => '0xC2AB', '0xAC' => '0xC2AC', '0xAD' => '0xC2AD', '0xAE' => '0xC2AE', '0xB0' => '0xC2B0', '0xB1' => '0xC2B1', '0xB3' => '0xC2B3', '0xB5' => '0xC2B5', '0xB6' => '0xC2B6', '0xB7' => '0xC2B7', '0xBB' => '0xC2BB', '0xE2' => '0xCEB2', '0x80' => '0xD2', '0x82' => '0xE2809A', '0x84' => '0xE2809E', '0x85' => '0xE280A6', '0x86' => '0xE280A0', '0xA1' => '0xCE85', '0xA2' => '0xCE86', '0x87' => '0xE280A1', '0x89' => '0xE280B0', '0xB9' => '0xCE89', '0x8B' => '0xE280B9', '0x91' => '0xE28098', '0x99' => '0xE284A2', '0x92' => '0xE28099', '0x93' => '0xE2809C', '0x94' => '0xE2809D', '0x95' => '0xE280A2', '0x96' => '0xE28093', '0x97' => '0xE28094', '0x9B' => '0xE280BA', '0xAF' => '0xE28095', '0xB4' => '0xCE84', '0xC1' => '0xCE91', '0xC3' => '0xCE93', '0xC4' => '0xCE94', '0xC5' => '0xCE95', '0xC6' => '0xCE96', '0x83' => '0xC692', '0xC7' => '0xCE97', '0xC9' => '0xCE99', '0xCB' => '0xCE9B', '0xD0' => '0xCEA0', '0xD1' => '0xCEA1', '0xD3' => '0xCEA3', '0xD4' => '0xCEA4', '0xD5' => '0xCEA5', '0xD6' => '0xCEA6', '0xD7' => '0xCEA7', '0xD8' => '0xCEA8', '0xD9' => '0xCEA9', '0xDB' => '0xCEAB', '0xDC' => '0xCEAC', '0xDD' => '0xCEAD', '0xDE' => '0xCEAE', '0xDF' => '0xCEAF', '0xE0' => '0xCEB0', '0xE1' => '0xCEB1', '0xE3' => '0xCEB3', '0xE4' => '0xCEB4', '0xE5' => '0xCEB5', '0xE6' => '0xCEB6', '0xE7' => '0xCEB7', '0xE9' => '0xCEB9', '0xEB' => '0xCEBB', '0xF0' => '0xCF80', '0xF1' => '0xCF81', '0xF2' => '0xCF82', '0xF3' => '0xCF83', '0xF4' => '0xCF84', '0xF5' => '0xCF85', '0xF6' => '0xCF86', '0xF7' => '0xCF87', '0xF8' => '0xCF88', '0xF9' => '0xCF89', '0xFA' => '0xCF8A', '0xFB' => '0xCF8B', '0xFC' => '0xCF8C', '0xFD' => '0xCF8D', '0xFE' => '0xCF8E', '0xFF' => '0xCE92', '0xD2' => '0xE282AC'));
    // Make some preparations.
    if (isset($translation_tables[$_POST['src_charset']])) {
        $replace = '%field%';
        foreach ($translation_tables[$_POST['src_charset']] as $from => $to) {
            $replace = 'REPLACE(' . $replace . ', ' . $from . ', ' . $to . ')';
        }
    }
    // Grab a list of tables.
    if (preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) === 1) {
        $queryTables = $smcFunc['db_query']('', '
			SHOW TABLE STATUS
			FROM `' . strtr($match[1], array('`' => '')) . '`
			LIKE {string:table_name}', array('table_name' => str_replace('_', '\\_', $match[2]) . '%'));
    } else {
        $queryTables = $smcFunc['db_query']('', '
			SHOW TABLE STATUS
			LIKE {string:table_name}', array('table_name' => str_replace('_', '\\_', $db_prefix) . '%'));
    }
    while ($table_info = $smcFunc['db_fetch_assoc']($queryTables)) {
        // Just to make sure it doesn't time out.
        if (function_exists('apache_reset_timeout')) {
            @apache_reset_timeout();
        }
        $table_charsets = array();
        // Loop through each column.
        $queryColumns = $smcFunc['db_query']('', '
			SHOW FULL COLUMNS
			FROM ' . $table_info['Name'], array());
        while ($column_info = $smcFunc['db_fetch_assoc']($queryColumns)) {
            // Only text'ish columns have a character set and need converting.
            if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false) {
                $collation = empty($column_info['Collation']) || $column_info['Collation'] === 'NULL' ? $table_info['Collation'] : $column_info['Collation'];
                if (!empty($collation) && $collation !== 'NULL') {
                    list($charset) = explode('_', $collation);
                    if (!isset($table_charsets[$charset])) {
                        $table_charsets[$charset] = array();
                    }
                    $table_charsets[$charset][] = $column_info;
                }
            }
        }
        $smcFunc['db_free_result']($queryColumns);
        // Only change the column if the data doesn't match the current charset.
        if (count($table_charsets) === 1 && key($table_charsets) !== $charsets[$_POST['src_charset']] || count($table_charsets) > 1) {
            $updates_blob = '';
            $updates_text = '';
            foreach ($table_charsets as $charset => $columns) {
                if ($charset !== $charsets[$_POST['src_charset']]) {
                    foreach ($columns as $column) {
                        $updates_blob .= '
							CHANGE COLUMN ' . $column['Field'] . ' ' . $column['Field'] . ' ' . strtr($column['Type'], array('text' => 'blob', 'char' => 'binary')) . ($column['Null'] === 'YES' ? ' NULL' : ' NOT NULL') . (strpos($column['Type'], 'char') === false ? '' : ' default \'' . $column['Default'] . '\'') . ',';
                        $updates_text .= '
							CHANGE COLUMN ' . $column['Field'] . ' ' . $column['Field'] . ' ' . $column['Type'] . ' CHARACTER SET ' . $charsets[$_POST['src_charset']] . ($column['Null'] === 'YES' ? '' : ' NOT NULL') . (strpos($column['Type'], 'char') === false ? '' : ' default \'' . $column['Default'] . '\'') . ',';
                    }
                }
            }
            // Change the columns to binary form.
            $smcFunc['db_query']('', '
				ALTER TABLE {raw:table_name}{raw:updates_blob}', array('table_name' => $table_info['Name'], 'updates_blob' => substr($updates_blob, 0, -1)));
            // Convert the character set if MySQL has no native support for it.
            if (isset($translation_tables[$_POST['src_charset']])) {
                $update = '';
                foreach ($table_charsets as $charset => $columns) {
                    foreach ($columns as $column) {
                        $update .= '
							' . $column['Field'] . ' = ' . strtr($replace, array('%field%' => $column['Field'])) . ',';
                    }
                }
                $smcFunc['db_query']('', '
					UPDATE {raw:table_name}
					SET {raw:updates}', array('table_name' => $table_info['Name'], 'updates' => substr($update, 0, -1)));
            }
            // Change the columns back, but with the proper character set.
            $smcFunc['db_query']('', '
				ALTER TABLE {raw:table_name}{raw:updates_text}', array('table_name' => $table_info['Name'], 'updates_text' => substr($updates_text, 0, -1)));
        }
        // Now do the actual conversion (if still needed).
        if ($charsets[$_POST['src_charset']] !== 'utf8') {
            $smcFunc['db_query']('', '
				ALTER TABLE {raw:table_name}
				CONVERT TO CHARACTER SET utf8', array('table_name' => $table_info['Name']));
        }
    }
    $smcFunc['db_free_result']($queryTables);
    // Let the settings know we have a new character set.
    updateSettings(array('global_character_set' => 'UTF-8', 'previousCharacterSet' => empty($translation_tables[$_POST['src_charset']]) ? $charsets[$_POST['src_charset']] : $translation_tables[$_POST['src_charset']]));
    // Store it in Settings.php too because it's needed before db connection.
    require_once $sourcedir . '/Subs-Admin.php';
    updateSettingsFile(array('db_character_set' => '\'utf8\''));
    // The conversion might have messed up some serialized strings. Fix them!
    require_once $sourcedir . '/Subs-Charset.php';
    fix_serialized_columns();
    redirectexit('action=admin;area=maintain;done=convertutf8');
}
Exemplo n.º 29
0
<?php

if (!defined('ELK') && file_exists(dirname(__FILE__) . '/SSI.php')) {
    require_once dirname(__FILE__) . '/SSI.php';
} elseif (!defined('ELK')) {
    die('<b>Error:</b> Cannot install - please verify you put this in the same place as ELK\'s index.php.');
}
$db_table = db_table();
$db_table->db_add_column('{db_prefix}message_likes', array('name' => 'like_timestamp', 'type' => 'int', 'size' => 10, 'unsigned' => true, 'default' => 0));
$db_table->db_change_column('{db_prefix}postby_emails_filters', 'filter_style', array('type' => 'char', 'size' => '6'));
$db_table->db_change_column('{db_prefix}mail_queue', 'message_id', array('type' => 'varchar', 'size' => '12'));
updateSettings(array('elkVersion' => '1.0.1'));
if (ELK == 'SSI') {
    echo 'Database changes were carried out successfully.';
}
Exemplo n.º 30
0
function DeleteInstall()
{
    global $txt, $HTTP_SESSION_VARS, $incontext;
    global $current_smf_version, $sourcedir, $forum_version, $modSettings, $user_info, $db_type;
    $incontext['page_title'] = $txt['congratulations'];
    $incontext['sub_template'] = 'delete_install';
    $incontext['continue'] = 0;
    require dirname(__FILE__) . '/Settings.php';
    load_database();
    chdir(dirname(__FILE__));
    require_once $sourcedir . '/Errors.php';
    require_once $sourcedir . '/lib/Subs.php';
    require_once $sourcedir . '/CommonAPI.php';
    require_once $sourcedir . '/Load.php';
    require_once $sourcedir . '/Security.php';
    require_once $sourcedir . '/lib/Subs-Auth.php';
    // Bring a warning over.
    if (!empty($incontext['account_existed'])) {
        $incontext['warning'] = $incontext['account_existed'];
    }
    smf_db_query('
		SET NAMES utf8', array());
    // As track stats is by default enabled let's add some activity.
    smf_db_insert('ignore', '{db_prefix}log_activity', array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'), array(strftime('%Y-%m-%d', time()), 1, 1, !empty($incontext['member_id']) ? 1 : 0), array('date'));
    // Automatically log them in ;)
    if (isset($incontext['member_id']) && isset($incontext['member_salt'])) {
        setLoginCookie(3153600 * 60, $incontext['member_id'], sha1(sha1(strtolower($_POST['username']) . $_POST['password1']) . $incontext['member_salt']));
    }
    $result = smf_db_query('
		SELECT value
		FROM {db_prefix}settings
		WHERE variable = {string:db_sessions}', array('db_sessions' => 'databaseSession_enable', 'db_error_skip' => true));
    if (mysql_num_rows($result) != 0) {
        list($db_sessions) = mysql_fetch_row($result);
    }
    mysql_free_result($result);
    if (empty($db_sessions)) {
        if (@version_compare(PHP_VERSION, '4.2.0') == -1) {
            $HTTP_SESSION_VARS['php_412_bugfix'] = true;
        }
        $_SESSION['admin_time'] = time();
    } else {
        $_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211);
        smf_db_insert('replace', '{db_prefix}sessions', array('session_id' => 'string', 'last_update' => 'int', 'data' => 'string'), array(session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';'), array('session_id'));
    }
    // We're going to want our lovely $modSettings now.
    $request = smf_db_query('
		SELECT variable, value
		FROM {db_prefix}settings', array('db_error_skip' => true));
    // Only proceed if we can load the data.
    if ($request) {
        while ($row = mysql_fetch_row($request)) {
            $modSettings[$row[0]] = $row[1];
        }
        mysql_free_result($request);
    }
    updateStats('member');
    updateStats('message');
    updateStats('topic');
    $request = smf_db_query('
		SELECT id_msg
		FROM {db_prefix}messages
		WHERE id_msg = 1
			AND modified_time = 0
		LIMIT 1', array('db_error_skip' => true));
    if (mysql_num_rows($request) > 0) {
        updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject']));
    }
    mysql_free_result($request);
    // Now is the perfect time to fetch the SM files.
    require_once $sourcedir . '/ScheduledTasks.php';
    // Sanity check that they loaded earlier!
    if (isset($modSettings['recycle_board'])) {
        $forum_version = $current_smf_version;
        // The variable is usually defined in index.php so lets just use our variable to do it for us.
        scheduled_fetchSMfiles();
        // Now go get those files!
        // We've just installed!
        $user_info['ip'] = $_SERVER['REMOTE_ADDR'];
        $user_info['id'] = isset($incontext['member_id']) ? $incontext['member_id'] : 0;
        logAction('install', array('version' => $forum_version), 'admin');
    }
    // Check if we need some stupid MySQL fix.
    $server_version = smf_db_get_version();
    if ($db_type == 'mysql' && in_array(substr($server_version, 0, 6), array('5.0.50', '5.0.51'))) {
        updateSettings(array('db_mysql_group_by_fix' => '1'));
    }
    // Some final context for the template.
    $incontext['dir_still_writable'] = is_writable(dirname(__FILE__)) && substr(__FILE__, 1, 2) != ':\\';
    $incontext['probably_delete_install'] = isset($_SESSION['installer_temp_ftp']) || is_writable(dirname(__FILE__)) || is_writable(__FILE__);
    return false;
}