array(
'type' => 'callback',
'callback_func' => 'avatar_select',
// This handles the permissions too.
'preload' => 'profileLoadAvatarData',
'input_validate' => 'profileSaveAvatarData',
'save_key' => 'avatar',
),
'bday1' => array(
'type' => 'callback',
'callback_func' => 'birthdate',
'permission' => 'profile_extra',
'preload' => function() use ($cur_profile, &$context)
{
// Split up the birthdate....
list ($uyear, $umonth, $uday) = explode('-', empty($cur_profile['birthdate']) || $cur_profile['birthdate'] === '1004-01-01' ? '--' : $cur_profile['birthdate']);
$context['member']['birth_date'] = array(
'year' => $uyear,
'month' => $umonth,
'day' => $uday,
);
return true;
},
'input_validate' => function(&$value) use (&$cur_profile, &$profile_vars)
{
if (isset($_POST['bday2'], $_POST['bday3']) && $value > 0 && $_POST['bday2'] > 0)
{
// Set to blank?
if ((int) $_POST['bday3'] == 1 && (int) $_POST['bday2'] == 1 && (int) $value == 1)
$value = '1004-01-01';
else
$value = checkdate($value, $_POST['bday2'], $_POST['bday3'] < 1004 ? 1004 : $_POST['bday3']) ? sprintf('%04d-%02d-%02d', $_POST['bday3'] < 1004 ? 1004 : $_POST['bday3'], $_POST['bday1'], $_POST['bday2']) : '1004-01-01';
}
else
$value = '1004-01-01';
$profile_vars['birthdate'] = $value;
$cur_profile['birthdate'] = $value;
return false;
},
),
// Setting the birthdate the old style way?
'birthdate' => array(
'type' => 'hidden',
'permission' => 'profile_extra',
'input_validate' => function(&$value) use ($cur_profile)
{
// @todo Should we check for this year and tell them they made a mistake :P? (based on coppa at least?)
if (preg_match('/(\d{4})[\-\., ](\d{2})[\-\., ](\d{2})/', $value, $dates) === 1)
{
$value = checkdate($dates[2], $dates[3], $dates[1] < 4 ? 4 : $dates[1]) ? sprintf('%04d-%02d-%02d', $dates[1] < 4 ? 4 : $dates[1], $dates[2], $dates[3]) : '1004-01-01';
return true;
}
else
{
$value = empty($cur_profile['birthdate']) ? '1004-01-01' : $cur_profile['birthdate'];
return false;
}
},
),
'date_registered' => array(
'type' => 'date',
'value' => empty($cur_profile['date_registered']) ? $txt['not_applicable'] : smf_strftime('%Y-%m-%d', $cur_profile['date_registered']),
'label' => $txt['date_registered'],
'log_change' => true,
'permission' => 'moderate_forum',
'input_validate' => function(&$value) use ($txt, $user_info, $modSettings, $cur_profile, $context)
{
// Bad date! Go try again - please?
if (($value = strtotime($value)) === false)
{
$value = $cur_profile['date_registered'];
return $txt['invalid_registration'] . ' ' . smf_strftime('%d %b %Y ' . (strpos($user_info['time_format'], '%H') !== false ? '%I:%M:%S %p' : '%H:%M:%S'), time());
}
// As long as it doesn't equal "N/A"...
elseif ($value != $txt['not_applicable'] && $value != strtotime(smf_strftime('%Y-%m-%d', $cur_profile['date_registered'])))
{
$diff = $cur_profile['date_registered'] - strtotime(smf_strftime('%Y-%m-%d', $cur_profile['date_registered']));
$value = $value + $diff;
}
else
$value = $cur_profile['date_registered'];
return true;
},
),
'email_address' => array(
'type' => 'email',
'label' => $txt['user_email_address'],
'subtext' => $txt['valid_email'],
'log_change' => true,
'permission' => 'profile_password',
'js_submit' => !empty($modSettings['send_validation_onChange']) ? '
form_handle.addEventListener("submit", function(event)
{
if (this.email_address.value != "' . (!empty($cur_profile['email_address']) ? $cur_profile['email_address'] : '') . '")
{
alert(' . JavaScriptEscape($txt['email_change_logout']) . ');
return true;
}
}, false);' : '',
'input_validate' => function(&$value)
{
global $context, $old_profile, $profile_vars, $sourcedir, $modSettings;
if (strtolower($value) == strtolower($old_profile['email_address']))
return false;
$isValid = profileValidateEmail($value, $context['id_member']);
// Do they need to revalidate? If so schedule the function!
if ($isValid === true && !empty($modSettings['send_validation_onChange']) && !allowedTo('moderate_forum'))
{
require_once($sourcedir . '/Subs-Members.php');
$profile_vars['validation_code'] = generateValidationCode();
$profile_vars['is_activated'] = 2;
$context['profile_execute_on_save'][] = 'profileSendActivation';
unset($context['profile_execute_on_save']['reload_user']);
}
return $isValid;
},
),
// Selecting group membership is a complicated one so we treat it separate!
'id_group' => array(
'type' => 'callback',
'callback_func' => 'group_manage',
'permission' => 'manage_membergroups',
'preload' => 'profileLoadGroups',
'log_change' => true,
'input_validate' => 'profileSaveGroups',
),
'id_theme' => array(
'type' => 'callback',
'callback_func' => 'theme_pick',
'permission' => 'profile_extra',
'enabled' => $modSettings['theme_allow'] || allowedTo('admin_forum'),
'preload' => function() use ($smcFunc, &$context, $cur_profile, $txt)
{
$request = $smcFunc['db_query']('', '
SELECT value
FROM {db_prefix}themes
WHERE id_theme = {int:id_theme}
AND variable = {string:variable}
LIMIT 1', array(
'id_theme' => $cur_profile['id_theme'],
'variable' => 'name',
)
);
list ($name) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
$context['member']['theme'] = array(
'id' => $cur_profile['id_theme'],
'name' => empty($cur_profile['id_theme']) ? $txt['theme_forum_default'] : $name
);
return true;
},
'input_validate' => function(&$value)
{
$value = (int) $value;
return true;
},
),
'lngfile' => array(
'type' => 'select',
'options' => function() use (&$context)
{
return $context['profile_languages'];
},
'label' => $txt['preferred_language'],
'permission' => 'profile_identity',
'preload' => 'profileLoadLanguages',
'enabled' => !empty($modSettings['userLanguage']),
'value' => empty($cur_profile['lngfile']) ? $language : $cur_profile['lngfile'],
'input_validate' => function(&$value) use (&$context, $cur_profile)
{
// Load the languages.
profileLoadLanguages();
if (isset($context['profile_languages'][$value]))
{
if ($context['user']['is_owner'] && empty($context['password_auth_failed']))
$_SESSION['language'] = $value;
return true;
}
else
{
$value = $cur_profile['lngfile'];
return false;
}
},
),
// The username is not always editable - so adjust it as such.
'member_name' => array(
'type' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? 'text' : 'label',
'label' => $txt['username'],
'subtext' => allowedTo('admin_forum') && !isset($_GET['changeusername']) ? '[' . $txt['username_change'] . ']' : '',
'log_change' => true,
'permission' => 'profile_identity',
'prehtml' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? '
' . $txt['username_warning'] . '
' : '',
'input_validate' => function(&$value) use ($sourcedir, $context, $user_info, $cur_profile)
{
if (allowedTo('admin_forum'))
{
// We'll need this...
require_once($sourcedir . '/Subs-Auth.php');
// Maybe they are trying to change their password as well?
$resetPassword = true;
if (isset($_POST['passwrd1']) && $_POST['passwrd1'] != '' && isset($_POST['passwrd2']) && $_POST['passwrd1'] == $_POST['passwrd2'] && validatePassword(un_htmlspecialchars($_POST['passwrd1']), $value, array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email'])) == null)
$resetPassword = false;
// Do the reset... this will send them an email too.
if ($resetPassword)
resetPassword($context['id_member'], $value);
elseif ($value !== null)
{
validateUsername($context['id_member'], trim(normalize_spaces(sanitize_chars($value, 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true))));
updateMemberData($context['id_member'], array('member_name' => $value));
// Call this here so any integrated systems will know about the name change (resetPassword() takes care of this if we're letting SMF generate the password)
call_integration_hook('integrate_reset_pass', array($cur_profile['member_name'], $value, $_POST['passwrd1']));
}
}
return false;
},
),
'passwrd1' => array(
'type' => 'password',
'label' => $txt['choose_pass'],
'subtext' => $txt['password_strength'],
'size' => 20,
'value' => '',
'permission' => 'profile_password',
'save_key' => 'passwd',
// Note this will only work if passwrd2 also exists!
'input_validate' => function(&$value) use ($sourcedir, $user_info, $smcFunc, $cur_profile)
{
// If we didn't try it then ignore it!
if ($value == '')
return false;
// Do the two entries for the password even match?
if (!isset($_POST['passwrd2']) || $value != $_POST['passwrd2'])
return 'bad_new_password';
// Let's get the validation function into play...
require_once($sourcedir . '/Subs-Auth.php');
$passwordErrors = validatePassword(un_htmlspecialchars($value), $cur_profile['member_name'], array($cur_profile['real_name'], $user_info['username'], $user_info['name'], $user_info['email']));
// Were there errors?
if ($passwordErrors != null)
return 'password_' . $passwordErrors;
// Set up the new password variable... ready for storage.
$value = hash_password($cur_profile['member_name'], un_htmlspecialchars($value));
return true;
},
),
'passwrd2' => array(
'type' => 'password',
'label' => $txt['verify_pass'],
'size' => 20,
'value' => '',
'permission' => 'profile_password',
'is_dummy' => true,
),
'personal_text' => array(
'type' => 'text',
'label' => $txt['personal_text'],
'log_change' => true,
'input_attr' => array('maxlength="50"'),
'size' => 50,
'permission' => 'profile_blurb',
'input_validate' => function(&$value) use ($smcFunc)
{
if ($smcFunc['strlen']($value) > 50)
return 'personal_text_too_long';
return true;
},
),
// This does ALL the pm settings
'pm_prefs' => array(
'type' => 'callback',
'callback_func' => 'pm_settings',
'permission' => 'pm_read',
'preload' => function() use (&$context, $cur_profile)
{
$context['display_mode'] = $cur_profile['pm_prefs'] & 3;
$context['receive_from'] = !empty($cur_profile['pm_receive_from']) ? $cur_profile['pm_receive_from'] : 0;
return true;
},
'input_validate' => function(&$value) use (&$cur_profile, &$profile_vars)
{
// Simple validate and apply the two "sub settings"
$value = max(min($value, 2), 0);
$cur_profile['pm_receive_from'] = $profile_vars['pm_receive_from'] = max(min((int) $_POST['pm_receive_from'], 4), 0);
return true;
},
),
'posts' => array(
'type' => 'int',
'label' => $txt['profile_posts'],
'log_change' => true,
'size' => 7,
'min' => 0,
'max' => 2 ** 24 - 1,
'permission' => 'moderate_forum',
'input_validate' => function(&$value)
{
if (!is_numeric($value))
return 'digits_only';
elseif ($value < 0 || $value > 2 ** 24 - 1)
return 'posts_out_of_range';
else
$value = $value != '' ? strtr($value, array(',' => '', '.' => '', ' ' => '')) : 0;
return true;
},
),
'real_name' => array(
'type' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum') ? 'text' : 'label',
'label' => $txt['name'],
'subtext' => $txt['display_name_desc'],
'log_change' => true,
'input_attr' => array('maxlength="60"'),
'permission' => 'profile_displayed_name',
'enabled' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum'),
'input_validate' => function(&$value) use ($context, $smcFunc, $sourcedir, $cur_profile)
{
$value = trim(normalize_spaces(sanitize_chars($value, 1, ' '), true, true, array('no_breaks' => true, 'replace_tabs' => true, 'collapse_hspace' => true)));
if (trim($value) == '')
return 'no_name';
elseif ($smcFunc['strlen']($value) > 60)
return 'name_too_long';
elseif ($cur_profile['real_name'] != $value)
{
require_once($sourcedir . '/Subs-Members.php');
if (isReservedName($value, $context['id_member']))
return 'name_taken';
}
return true;
},
),
'secret_question' => array(
'type' => 'text',
'label' => $txt['secret_question'],
'subtext' => $txt['secret_desc'],
'size' => 50,
'permission' => 'profile_password',
),
'secret_answer' => array(
'type' => 'text',
'label' => $txt['secret_answer'],
'subtext' => $txt['secret_desc2'],
'size' => 20,
'postinput' => ' ' . $txt['secret_why_blank'] . '',
'value' => '',
'permission' => 'profile_password',
'input_validate' => function(&$value) use ($cur_profile)
{
$value = $value != '' ? hash_password($cur_profile['member_name'], $value) : '';
return true;
},
),
'signature' => array(
'type' => 'callback',
'callback_func' => 'signature_modify',
'permission' => 'profile_signature',
'enabled' => substr($modSettings['signature_settings'], 0, 1) == 1,
'preload' => 'profileLoadSignatureData',
'input_validate' => 'profileValidateSignature',
),
'show_online' => array(
'type' => 'check',
'label' => $txt['show_online'],
'permission' => 'profile_identity',
'enabled' => !empty($modSettings['allow_hideOnline']) || allowedTo('moderate_forum'),
),
'smiley_set' => array(
'type' => 'callback',
'callback_func' => 'smiley_pick',
'enabled' => !empty($modSettings['smiley_sets_enable']),
'permission' => 'profile_extra',
'preload' => function() use ($modSettings, &$context, &$txt, $cur_profile, $smcFunc, $settings, $language)
{
$context['member']['smiley_set']['id'] = empty($cur_profile['smiley_set']) ? '' : $cur_profile['smiley_set'];
$context['smiley_sets'] = explode(',', 'none,,' . $modSettings['smiley_sets_known']);
$set_names = explode("\n", $txt['smileys_none'] . "\n" . $txt['smileys_forum_board_default'] . "\n" . $modSettings['smiley_sets_names']);
$filenames = array();
$result = $smcFunc['db_query']('', '
SELECT f.filename, f.smiley_set
FROM {db_prefix}smiley_files AS f
JOIN {db_prefix}smileys AS s ON (s.id_smiley = f.id_smiley)
WHERE s.code = {string:smiley}',
array(
'smiley' => ':)',
)
);
while ($row = $smcFunc['db_fetch_assoc']($result))
$filenames[$row['smiley_set']] = $row['filename'];
$smcFunc['db_free_result']($result);
// In case any sets don't contain a ':)' smiley
$no_smiley_sets = array_diff(explode(',', $modSettings['smiley_sets_known']), array_keys($filenames));
foreach ($no_smiley_sets as $set)
{
$allowedTypes = array('gif', 'png', 'jpg', 'jpeg', 'tiff', 'svg');
$images = glob(implode('/', array($modSettings['smileys_dir'], $set, '*.{' . (implode(',', $allowedTypes) . '}'))), GLOB_BRACE);
// Just use some image or other
if (!empty($images))
{
$image = array_pop($images);
$filenames[$set] = pathinfo($image, PATHINFO_BASENAME);
}
// No images at all? That's no good. Let the admin know, and quietly skip for this user.
else
{
loadLanguage('Errors', $language);
log_error(sprintf($txt['smiley_set_dir_not_found'], $set_names[array_search($set, $context['smiley_sets'])]));
$context['smiley_sets'] = array_filter($context['smiley_sets'], function($v) use ($set)
{
return $v != $set;
});
}
}
foreach ($context['smiley_sets'] as $i => $set)
{
$context['smiley_sets'][$i] = array(
'id' => $smcFunc['htmlspecialchars']($set),
'name' => $smcFunc['htmlspecialchars']($set_names[$i]),
'selected' => $set == $context['member']['smiley_set']['id']
);
if ($set === 'none')
$context['smiley_sets'][$i]['preview'] = $settings['images_url'] . '/blank.png';
elseif ($set === '')
{
$default_set = !empty($settings['smiley_sets_default']) ? $settings['smiley_sets_default'] : $modSettings['smiley_sets_default'];
$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $default_set, $filenames[$default_set]));
}
else
$context['smiley_sets'][$i]['preview'] = implode('/', array($modSettings['smileys_url'], $set, $filenames[$set]));
if ($context['smiley_sets'][$i]['selected'])
{
$context['member']['smiley_set']['name'] = $set_names[$i];
$context['member']['smiley_set']['preview'] = $context['smiley_sets'][$i]['preview'];
}
$context['smiley_sets'][$i]['preview'] = $smcFunc['htmlspecialchars']($context['smiley_sets'][$i]['preview']);
}
return true;
},
'input_validate' => function(&$value)
{
global $modSettings;
$smiley_sets = explode(',', $modSettings['smiley_sets_known']);
if (!in_array($value, $smiley_sets) && $value != 'none')
$value = '';
return true;
},
),
// Pretty much a dummy entry - it populates all the theme settings.
'theme_settings' => array(
'type' => 'callback',
'callback_func' => 'theme_settings',
'permission' => 'profile_extra',
'is_dummy' => true,
'preload' => function() use (&$context, $user_info, $modSettings)
{
loadLanguage('Settings');
$context['allow_no_censored'] = false;
if ($user_info['is_admin'] || $context['user']['is_owner'])
$context['allow_no_censored'] = !empty($modSettings['allow_no_censored']);
return true;
},
),
'tfa' => array(
'type' => 'callback',
'callback_func' => 'tfa',
'permission' => 'profile_password',
'enabled' => !empty($modSettings['tfa_mode']),
'preload' => function() use (&$context, $cur_profile)
{
$context['tfa_enabled'] = !empty($cur_profile['tfa_secret']);
return true;
},
),
'time_format' => array(
'type' => 'callback',
'callback_func' => 'timeformat_modify',
'permission' => 'profile_extra',
'preload' => function() use (&$context, $user_info, $txt, $cur_profile, $modSettings)
{
$context['easy_timeformats'] = array(
array('format' => '', 'title' => $txt['timeformat_default']),
array('format' => '%B %d, %Y, %I:%M:%S %p', 'title' => $txt['timeformat_easy1']),
array('format' => '%B %d, %Y, %H:%M:%S', 'title' => $txt['timeformat_easy2']),
array('format' => '%Y-%m-%d, %H:%M:%S', 'title' => $txt['timeformat_easy3']),
array('format' => '%d %B %Y, %H:%M:%S', 'title' => $txt['timeformat_easy4']),
array('format' => '%d-%m-%Y, %H:%M:%S', 'title' => $txt['timeformat_easy5'])
);
$context['member']['time_format'] = $cur_profile['time_format'];
$context['current_forum_time'] = timeformat(time(), false, 'forum');
$context['current_forum_time_js'] = smf_strftime('%Y,' . ((int) smf_strftime('%m', time()) - 1) . ',%d,%H,%M,%S', time());
$context['current_forum_time_hour'] = (int) smf_strftime('%H', time());
return true;
},
),
'timezone' => array(
'type' => 'select',
'options' => smf_list_timezones(),
'disabled_options' => array_filter(array_keys(smf_list_timezones()), 'is_int'),
'permission' => 'profile_extra',
'label' => $txt['timezone'],
'value' => empty($cur_profile['timezone']) ? $modSettings['default_timezone'] : $cur_profile['timezone'],
'input_validate' => function($value)
{
$tz = smf_list_timezones();
if (!isset($tz[$value]))
return 'bad_timezone';
return true;
},
),
'usertitle' => array(
'type' => 'text',
'label' => $txt['custom_title'],
'log_change' => true,
'input_attr' => array('maxlength="50"'),
'size' => 50,
'permission' => 'profile_title',
'enabled' => !empty($modSettings['titlesEnable']),
'input_validate' => function(&$value) use ($smcFunc)
{
if ($smcFunc['strlen']($value) > 50)
return 'user_title_too_long';
return true;
},
),
'website_title' => array(
'type' => 'text',
'label' => $txt['website_title'],
'subtext' => $txt['include_website_url'],
'size' => 50,
'permission' => 'profile_website',
'link_with' => 'website',
'input_validate' => function(&$value) use ($smcFunc)
{
if (mb_strlen($value) > 250)
return 'website_title_too_long';
return true;
},
),
'website_url' => array(
'type' => 'url',
'label' => $txt['website_url'],
'subtext' => $txt['complete_url'],
'size' => 50,
'permission' => 'profile_website',
// Fix the URL...
'input_validate' => function(&$value)
{
if (strlen(trim($value)) > 0 && strpos($value, '://') === false)
$value = 'http://' . $value;
if (strlen($value) < 8 || (substr($value, 0, 7) !== 'http://' && substr($value, 0, 8) !== 'https://'))
$value = '';
$value = (string) validate_iri(normalize_iri($value));
return true;
},
'link_with' => 'website',
),
);
call_integration_hook('integrate_load_profile_fields', array(&$profile_fields));
$disabled_fields = !empty($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
// For each of the above let's take out the bits which don't apply - to save memory and security!
foreach ($profile_fields as $key => $field)
{
// Do we have permission to do this?
if (isset($field['permission']) && !allowedTo(($context['user']['is_owner'] ? array($field['permission'] . '_own', $field['permission'] . '_any') : $field['permission'] . '_any')) && !allowedTo($field['permission']))
unset($profile_fields[$key]);
// Is it enabled?
if (isset($field['enabled']) && !$field['enabled'])
unset($profile_fields[$key]);
// Is it specifically disabled?
if (in_array($key, $disabled_fields) || (isset($field['link_with']) && in_array($field['link_with'], $disabled_fields)))
unset($profile_fields[$key]);
}
}
/**
* Setup the context for a page load!
*
* @param array $fields The profile fields to display. Each item should correspond to an item in the $profile_fields array generated by loadProfileFields
*/
function setupProfileContext($fields)
{
global $profile_fields, $context, $cur_profile, $txt;
// Some default bits.
$context['profile_prehtml'] = '';
$context['profile_posthtml'] = '';
$context['profile_javascript'] = '';
$context['profile_onsubmit_javascript'] = '';
call_integration_hook('integrate_setup_profile_context', array(&$fields));
// Make sure we have this!
loadProfileFields(true);
// First check for any linked sets.
foreach ($profile_fields as $key => $field)
if (isset($field['link_with']) && in_array($field['link_with'], $fields))
$fields[] = $key;
$i = 0;
$last_type = '';
foreach ($fields as $key => $field)
{
if (isset($profile_fields[$field]))
{
// Shortcut.
$cur_field = &$profile_fields[$field];
// Does it have a preload and does that preload succeed?
if (isset($cur_field['preload']) && !$cur_field['preload']())
continue;
// If this is anything but complex we need to do more cleaning!
if ($cur_field['type'] != 'callback' && $cur_field['type'] != 'hidden')
{
if (!isset($cur_field['label']))
$cur_field['label'] = isset($txt[$field]) ? $txt[$field] : $field;
// Everything has a value!
if (!isset($cur_field['value']))
$cur_field['value'] = isset($cur_profile[$field]) ? $cur_profile[$field] : '';
// Any input attributes?
$cur_field['input_attr'] = !empty($cur_field['input_attr']) ? implode(',', $cur_field['input_attr']) : '';
}
// Was there an error with this field on posting?
if (isset($context['profile_errors'][$field]))
$cur_field['is_error'] = true;
// Any javascript stuff?
if (!empty($cur_field['js_submit']))
$context['profile_onsubmit_javascript'] .= $cur_field['js_submit'];
if (!empty($cur_field['js']))
$context['profile_javascript'] .= $cur_field['js'];
// Any template stuff?
if (!empty($cur_field['prehtml']))
$context['profile_prehtml'] .= $cur_field['prehtml'];
if (!empty($cur_field['posthtml']))
$context['profile_posthtml'] .= $cur_field['posthtml'];
// Finally put it into context?
if ($cur_field['type'] != 'hidden')
{
$last_type = $cur_field['type'];
$context['profile_fields'][$field] = &$profile_fields[$field];
}
}
// Bodge in a line break - without doing two in a row ;)
elseif ($field == 'hr' && $last_type != 'hr' && $last_type != '')
{
$last_type = 'hr';
$context['profile_fields'][$i++]['type'] = 'hr';
}
}
// Some spicy JS.
addInlineJavaScript('
var form_handle = document.forms.creator;
createEventListener(form_handle);
' . (!empty($context['require_password']) ? '
form_handle.addEventListener("submit", function(event)
{
if (this.oldpasswrd.value == "")
{
event.preventDefault();
alert(' . (JavaScriptEscape($txt['required_security_reasons'])) . ');
return false;
}
}, false);' : ''), true);
// Any onsubmit javascript?
if (!empty($context['profile_onsubmit_javascript']))
addInlineJavaScript($context['profile_onsubmit_javascript'], true);
// Any totally custom stuff?
if (!empty($context['profile_javascript']))
addInlineJavaScript($context['profile_javascript'], true);
// Free up some memory.
unset($profile_fields);
}
/**
* Save the profile changes.
*/
function saveProfileFields()
{
global $profile_fields, $profile_vars, $context, $old_profile, $post_errors, $cur_profile, $smcFunc;
// Load them up.
loadProfileFields();
// This makes things easier...
$old_profile = $cur_profile;
// This allows variables to call activities when they save - by default just to reload their settings
$context['profile_execute_on_save'] = array();
if ($context['user']['is_owner'])
$context['profile_execute_on_save']['reload_user'] = 'profileReloadUser';
// Assume we log nothing.
$context['log_changes'] = array();
// Cycle through the profile fields working out what to do!
foreach ($profile_fields as $key => $field)
{
if (!isset($_POST[$key]) || !empty($field['is_dummy']) || (isset($_POST['preview_signature']) && $key == 'signature'))
continue;
$_POST[$key] = sanitize_chars($smcFunc['normalize']($_POST[$key]), in_array($key, array('member_name', 'real_name')) ? 1 : 0);
// What gets updated?
$db_key = isset($field['save_key']) ? $field['save_key'] : $key;
// Right - we have something that is enabled, we can act upon and has a value posted to it. Does it have a validation function?
if (isset($field['input_validate']))
{
$is_valid = $field['input_validate']($_POST[$key]);
// An error occurred - set it as such!
if ($is_valid !== true)
{
// Is this an actual error?
if ($is_valid !== false)
{
$post_errors[$key] = $is_valid;
$profile_fields[$key]['is_error'] = $is_valid;
}
// Retain the old value.
$cur_profile[$key] = $_POST[$key];
continue;
}
}
// Are we doing a cast?
$field['cast_type'] = empty($field['cast_type']) ? $field['type'] : $field['cast_type'];
// Finally, clean up certain types.
if ($field['cast_type'] == 'int')
$_POST[$key] = (int) $_POST[$key];
elseif ($field['cast_type'] == 'float')
$_POST[$key] = (float) $_POST[$key];
elseif ($field['cast_type'] == 'check')
$_POST[$key] = !empty($_POST[$key]) ? 1 : 0;
// If we got here we're doing OK.
if ($field['type'] != 'hidden' && (!isset($old_profile[$key]) || $_POST[$key] != $old_profile[$key]))
{
// Set the save variable.
$profile_vars[$db_key] = $_POST[$key];
// And update the user profile.
$cur_profile[$key] = $_POST[$key];
// Are we logging it?
if (!empty($field['log_change']) && isset($old_profile[$key]))
$context['log_changes'][$key] = array(
'previous' => $old_profile[$key],
'new' => $_POST[$key],
);
}
// Logging group changes are a bit different...
if ($key == 'id_group' && $field['log_change'])
{
profileLoadGroups();
// Any changes to primary group?
if ($_POST['id_group'] != $old_profile['id_group'])
{
$context['log_changes']['id_group'] = array(
'previous' => !empty($old_profile[$key]) && isset($context['member_groups'][$old_profile[$key]]) ? $context['member_groups'][$old_profile[$key]]['name'] : '',
'new' => !empty($_POST[$key]) && isset($context['member_groups'][$_POST[$key]]) ? $context['member_groups'][$_POST[$key]]['name'] : '',
);
}
// Prepare additional groups for comparison.
$additional_groups = array(
'previous' => !empty($old_profile['additional_groups']) ? explode(',', $old_profile['additional_groups']) : array(),
'new' => !empty($_POST['additional_groups']) ? array_diff($_POST['additional_groups'], array(0)) : array(),
);
sort($additional_groups['previous']);
sort($additional_groups['new']);
// What about additional groups?
if ($additional_groups['previous'] != $additional_groups['new'])
{
foreach ($additional_groups as $type => $groups)
{
foreach ($groups as $id => $group)
{
if (isset($context['member_groups'][$group]))
$additional_groups[$type][$id] = $context['member_groups'][$group]['name'];
else
unset($additional_groups[$type][$id]);
}
$additional_groups[$type] = implode(', ', $additional_groups[$type]);
}
$context['log_changes']['additional_groups'] = $additional_groups;
}
}
}
// @todo Temporary
if ($context['user']['is_owner'])
$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
else
$changeOther = allowedTo('profile_extra_any');
if ($changeOther && empty($post_errors))
{
makeThemeChanges($context['id_member'], isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
if (!empty($_REQUEST['sa']))
{
$custom_fields_errors = makeCustomFieldChanges($context['id_member'], $_REQUEST['sa'], false, true);
if (!empty($custom_fields_errors))
$post_errors = array_merge($post_errors, $custom_fields_errors);
}
}
// Free memory!
unset($profile_fields);
}
/**
* Save the profile changes
*
* @param array &$profile_vars The items to save
* @param array &$post_errors An array of information about any errors that occurred
* @param int $memID The ID of the member whose profile we're saving
*/
function saveProfileChanges(&$profile_vars, &$post_errors, $memID)
{
global $user_profile, $context;
// These make life easier....
$old_profile = &$user_profile[$memID];
// Permissions...
if ($context['user']['is_owner'])
{
$changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own', 'profile_website_any', 'profile_website_own', 'profile_signature_any', 'profile_signature_own'));
}
else
$changeOther = allowedTo(array('profile_extra_any', 'profile_website_any', 'profile_signature_any'));
// Arrays of all the changes - makes things easier.
$profile_bools = array();
$profile_ints = array();
$profile_floats = array();
$profile_strings = array(
'buddy_list',
'ignore_boards',
);
if (isset($_POST['sa']) && $_POST['sa'] == 'ignoreboards' && empty($_POST['brd']))
$_POST['brd'] = array();
unset($_POST['ignore_boards']); // Whatever it is set to is a dirty filthy thing. Kinda like our minds.
if (isset($_POST['brd']))
{
if (!is_array($_POST['brd']))
$_POST['brd'] = array($_POST['brd']);
foreach ($_POST['brd'] as $k => $d)
{
$d = (int) $d;
if ($d != 0)
$_POST['brd'][$k] = $d;
else
unset($_POST['brd'][$k]);
}
$_POST['ignore_boards'] = implode(',', $_POST['brd']);
unset($_POST['brd']);
}
// Here's where we sort out all the 'other' values...
if ($changeOther)
{
makeThemeChanges($memID, isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
//makeAvatarChanges($memID, $post_errors);
if (!empty($_REQUEST['sa']))
makeCustomFieldChanges($memID, $_REQUEST['sa'], false);
foreach ($profile_bools as $var)
if (isset($_POST[$var]))
$profile_vars[$var] = empty($_POST[$var]) ? '0' : '1';
foreach ($profile_ints as $var)
if (isset($_POST[$var]))
$profile_vars[$var] = $_POST[$var] != '' ? (int) $_POST[$var] : '';
foreach ($profile_floats as $var)
if (isset($_POST[$var]))
$profile_vars[$var] = (float) $_POST[$var];
foreach ($profile_strings as $var)
if (isset($_POST[$var]))
$profile_vars[$var] = $_POST[$var];
}
}
/**
* Make any theme changes that are sent with the profile.
*
* @param int $memID The ID of the user
* @param int $id_theme The ID of the theme
*/
function makeThemeChanges($memID, $id_theme)
{
global $modSettings, $smcFunc, $context, $user_info;
$reservedVars = array(
'actual_theme_url',
'actual_images_url',
'base_theme_dir',
'base_theme_url',
'default_images_url',
'default_theme_dir',
'default_theme_url',
'default_template',
'images_url',
'number_recent_posts',
'smiley_sets_default',
'theme_dir',
'theme_id',
'theme_layers',
'theme_templates',
'theme_url',
);
// Can't change reserved vars.
if ((isset($_POST['options']) && count(array_intersect(array_keys($_POST['options']), $reservedVars)) != 0) || (isset($_POST['default_options']) && count(array_intersect(array_keys($_POST['default_options']), $reservedVars)) != 0))
fatal_lang_error('no_access', false);
// Don't allow any overriding of custom fields with default or non-default options.
$request = $smcFunc['db_query']('', '
SELECT col_name
FROM {db_prefix}custom_fields
WHERE active = {int:is_active}',
array(
'is_active' => 1,
)
);
$custom_fields = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
$custom_fields[] = $row['col_name'];
$smcFunc['db_free_result']($request);
// These are the theme changes...
$themeSetArray = array();
if (isset($_POST['options']) && is_array($_POST['options']))
{
foreach ($_POST['options'] as $opt => $val)
{
if (in_array($opt, $custom_fields))
continue;
// These need to be controlled.
if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
$val = max(0, min($val, 50));
// We don't set this per theme anymore.
elseif ($opt == 'allow_no_censored')
continue;
$themeSetArray[] = array($memID, $id_theme, $opt, is_array($val) ? implode(',', $val) : $val);
}
}
$erase_options = array();
if (isset($_POST['default_options']) && is_array($_POST['default_options']))
foreach ($_POST['default_options'] as $opt => $val)
{
if (in_array($opt, $custom_fields))
continue;
// These need to be controlled.
if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
$val = max(0, min($val, 50));
// Only let admins and owners change the censor.
elseif ($opt == 'allow_no_censored' && !$user_info['is_admin'] && !$context['user']['is_owner'])
continue;
$themeSetArray[] = array($memID, 1, $opt, is_array($val) ? implode(',', $val) : $val);
$erase_options[] = $opt;
}
// If themeSetArray isn't still empty, send it to the database.
if (empty($context['password_auth_failed']))
{
if (!empty($themeSetArray))
{
$smcFunc['db_insert']('replace',
'{db_prefix}themes',
array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
$themeSetArray,
array('id_member', 'id_theme', 'variable')
);
}
if (!empty($erase_options))
{
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}themes
WHERE id_theme != {int:id_theme}
AND variable IN ({array_string:erase_variables})
AND id_member = {int:id_member}',
array(
'id_theme' => 1,
'id_member' => $memID,
'erase_variables' => $erase_options
)
);
}
// Admins can choose any theme, even if it's not enabled...
$themes = allowedTo('admin_forum') ? explode(',', $modSettings['knownThemes']) : explode(',', $modSettings['enableThemes']);
foreach ($themes as $t)
cache_put_data('theme_settings-' . $t . ':' . $memID, null, 60);
}
}
/**
* Make any notification changes that need to be made.
*
* @param int $memID The ID of the member
*/
function makeNotificationChanges($memID)
{
global $smcFunc, $sourcedir;
require_once($sourcedir . '/Subs-Notify.php');
// Update the boards they are being notified on.
if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards']))
{
// Make sure only integers are deleted.
foreach ($_POST['notify_boards'] as $index => $id)
$_POST['notify_boards'][$index] = (int) $id;
// id_board = 0 is reserved for topic notifications.
$_POST['notify_boards'] = array_diff($_POST['notify_boards'], array(0));
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_notify
WHERE id_board IN ({array_int:board_list})
AND id_member = {int:selected_member}',
array(
'board_list' => $_POST['notify_boards'],
'selected_member' => $memID,
)
);
}
// We are editing topic notifications......
elseif (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
{
foreach ($_POST['notify_topics'] as $index => $id)
$_POST['notify_topics'][$index] = (int) $id;
// Make sure there are no zeros left.
$_POST['notify_topics'] = array_diff($_POST['notify_topics'], array(0));
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_notify
WHERE id_topic IN ({array_int:topic_list})
AND id_member = {int:selected_member}',
array(
'topic_list' => $_POST['notify_topics'],
'selected_member' => $memID,
)
);
foreach ($_POST['notify_topics'] as $topic)
setNotifyPrefs((int) $memID, array('topic_notify_' . $topic => 0));
}
// We are removing topic preferences
elseif (isset($_POST['remove_notify_topics']) && !empty($_POST['notify_topics']))
{
$prefs = array();
foreach ($_POST['notify_topics'] as $topic)
$prefs[] = 'topic_notify_' . $topic;
deleteNotifyPrefs($memID, $prefs);
}
// We are removing board preferences
elseif (isset($_POST['remove_notify_board']) && !empty($_POST['notify_boards']))
{
$prefs = array();
foreach ($_POST['notify_boards'] as $board)
$prefs[] = 'board_notify_' . $board;
deleteNotifyPrefs($memID, $prefs);
}
}
/**
* Save any changes to the custom profile fields
*
* @param int $memID The ID of the member
* @param string $area The area of the profile these fields are in
* @param bool $sanitize = true Whether or not to sanitize the data
* @param bool $returnErrors Whether or not to return any error information
* @return void|array Returns nothing or returns an array of error info if $returnErrors is true
*/
function makeCustomFieldChanges($memID, $area, $sanitize = true, $returnErrors = false)
{
global $context, $smcFunc, $user_profile, $user_info, $modSettings;
global $sourcedir;
$errors = array();
if ($sanitize && isset($_POST['customfield']))
$_POST['customfield'] = htmlspecialchars__recursive($_POST['customfield']);
$where = $area == 'register' ? 'show_reg != 0' : 'show_profile = {string:area}';
// Load the fields we are saving too - make sure we save valid data (etc).
$request = $smcFunc['db_query']('', '
SELECT col_name, field_name, field_desc, field_type, field_length, field_options, default_value, show_reg, mask, private
FROM {db_prefix}custom_fields
WHERE ' . $where . '
AND active = {int:is_active}',
array(
'is_active' => 1,
'area' => $area,
)
);
$changes = array();
$deletes = array();
$log_changes = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
{
/* This means don't save if:
- The user is NOT an admin.
- The data is not freely viewable and editable by users.
- The data is not invisible to users but editable by the owner (or if it is the user is not the owner)
- The area isn't registration, and if it is that the field is not supposed to be shown there.
*/
if ($row['private'] != 0 && !allowedTo('admin_forum') && ($memID != $user_info['id'] || $row['private'] != 2) && ($area != 'register' || $row['show_reg'] == 0))
continue;
// Validate the user data.
if ($row['field_type'] == 'check')
$value = isset($_POST['customfield'][$row['col_name']]) ? 1 : 0;
elseif ($row['field_type'] == 'select' || $row['field_type'] == 'radio')
{
$value = $row['default_value'];
foreach (explode(',', $row['field_options']) as $k => $v)
if (isset($_POST['customfield'][$row['col_name']]) && $_POST['customfield'][$row['col_name']] == $k)
$value = $v;
}
// Otherwise some form of text!
else
{
$value = isset($_POST['customfield'][$row['col_name']]) ? $_POST['customfield'][$row['col_name']] : '';
if ($row['field_length'])
$value = $smcFunc['substr']($value, 0, $row['field_length']);
// Any masks?
if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none')
{
$value = $smcFunc['htmltrim']($value);
$valueReference = un_htmlspecialchars($value);
// Try and avoid some checks. '0' could be a valid non-empty value.
if (empty($value) && !is_numeric($value))
$value = '';
if ($row['mask'] == 'nohtml' && ($valueReference != strip_tags($valueReference) || $value != $smcFunc['htmlspecialchars']($value, ENT_NOQUOTES) || preg_match('/<(.+?)[\s]*\/?[\s]*>/si', $valueReference)))
{
if ($returnErrors)
$errors[] = 'custom_field_nohtml_fail';
else
$value = '';
}
elseif ($row['mask'] == 'email' && !empty($value) && (!filter_var($value, FILTER_VALIDATE_EMAIL) || strlen($value) > 255))
{
if ($returnErrors)
$errors[] = 'custom_field_mail_fail';
else
$value = '';
}
elseif ($row['mask'] == 'number')
{
$value = (int) $value;
}
elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0)
{
if ($returnErrors)
$errors[] = 'custom_field_regex_fail';
else
$value = '';
}
unset($valueReference);
}
}
if (!isset($user_profile[$memID]['options'][$row['col_name']]))
$user_profile[$memID]['options'][$row['col_name']] = '';
// Did it change?
if ($user_profile[$memID]['options'][$row['col_name']] != $value)
{
$log_changes[] = array(
'action' => 'customfield_' . $row['col_name'],
'log_type' => 'user',
'extra' => array(
'previous' => !empty($user_profile[$memID]['options'][$row['col_name']])
? $user_profile[$memID]['options'][$row['col_name']]
: '',
'new' => $value,
// The applicator is the same as the member affected
// if we are registering a new member.
'applicator' => empty($user_info['id']) && $area == 'register'
? $memID
: $user_info['id'],
'member_affected' => $memID,
),
);
if (empty($value))
{
$deletes[] = array('id_theme' => 1, 'variable' => $row['col_name'], 'id_member' => $memID);
unset($user_profile[$memID]['options'][$row['col_name']]);
}
else
{
$changes[] = array(1, $row['col_name'], $value, $memID);
$user_profile[$memID]['options'][$row['col_name']] = $value;
}
}
}
$smcFunc['db_free_result']($request);
$hook_errors = call_integration_hook('integrate_save_custom_profile_fields', array(&$changes, &$log_changes, &$errors, $returnErrors, $memID, $area, $sanitize, &$deletes));
if (!empty($hook_errors) && is_array($hook_errors))
$errors = array_merge($errors, $hook_errors);
// Make those changes!
if ((!empty($changes) || !empty($deletes)) && empty($context['password_auth_failed']) && empty($errors))
{
if (!empty($changes))
$smcFunc['db_insert']('replace',
'{db_prefix}themes',
array('id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534', 'id_member' => 'int'),
$changes,
array('id_theme', 'variable', 'id_member')
);
if (!empty($deletes))
foreach ($deletes as $delete)
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}themes
WHERE id_theme = {int:id_theme}
AND variable = {string:variable}
AND id_member = {int:id_member}',
$delete
);
if (!empty($log_changes) && !empty($modSettings['modlog_enabled']))
{
require_once($sourcedir . '/Logging.php');
logActions($log_changes);
}
}
if ($returnErrors)
return $errors;
}
/**
* Show all the users buddies, as well as a add/delete interface.
*
* @param int $memID The ID of the member
*/
function editBuddyIgnoreLists($memID)
{
global $context, $txt, $modSettings;
// Do a quick check to ensure people aren't getting here illegally!
if (!$context['user']['is_owner'] || empty($modSettings['enable_buddylist']))
fatal_lang_error('no_access', false);
// Can we email the user direct?
$context['can_moderate_forum'] = allowedTo('moderate_forum');
$context['can_send_email'] = allowedTo('moderate_forum');
$subActions = array(
'buddies' => array('editBuddies', $txt['editBuddies']),
'ignore' => array('editIgnoreList', $txt['editIgnoreList']),
);
$context['list_area'] = isset($_GET['sa']) && isset($subActions[$_GET['sa']]) ? $_GET['sa'] : 'buddies';
// Create the tabs for the template.
$context[$context['profile_menu_name']]['tab_data'] = array(
'title' => $txt['editBuddyIgnoreLists'],
'description' => $txt['buddy_ignore_desc'],
'icon_class' => 'main_icons profile_hd',
'tabs' => array(
'buddies' => array(),
'ignore' => array(),
),
);
loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
// Pass on to the actual function.
$context['sub_template'] = $subActions[$context['list_area']][0];
$call = call_helper($subActions[$context['list_area']][0], true);
if (!empty($call))
call_user_func($call, $memID);
}
/**
* Show all the users buddies, as well as a add/delete interface.
*
* @param int $memID The ID of the member
*/
function editBuddies($memID)
{
global $txt, $scripturl, $settings, $modSettings;
global $context, $user_profile, $memberContext, $smcFunc;
// For making changes!
$buddiesArray = explode(',', $user_profile[$memID]['buddy_list']);
foreach ($buddiesArray as $k => $dummy)
if ($dummy == '')
unset($buddiesArray[$k]);
// Removing a buddy?
if (isset($_GET['remove']))
{
checkSession('get');
call_integration_hook('integrate_remove_buddy', array($memID));
$_SESSION['prf-save'] = $txt['could_not_remove_person'];
// Heh, I'm lazy, do it the easy way...
foreach ($buddiesArray as $key => $buddy)
if ($buddy == (int) $_GET['remove'])
{
unset($buddiesArray[$key]);
$_SESSION['prf-save'] = true;
}
// Make the changes.
$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
}
elseif (isset($_POST['new_buddy']))
{
checkSession();
// Prepare the string for extraction...
$_POST['new_buddy'] = strtr($smcFunc['htmlspecialchars']($_POST['new_buddy'], ENT_QUOTES), array('"' => '"'));
preg_match_all('~"([^"]+)"~', $_POST['new_buddy'], $matches);
$new_buddies = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_buddy']))));
foreach ($new_buddies as $k => $dummy)
{
$new_buddies[$k] = strtr(trim($new_buddies[$k]), array('\'' => '''));
if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
unset($new_buddies[$k]);
}
call_integration_hook('integrate_add_buddies', array($memID, &$new_buddies));
$_SESSION['prf-save'] = $txt['could_not_add_person'];
if (!empty($new_buddies))
{
// Now find out the id_member of the buddy.
$request = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}members
WHERE member_name IN ({array_string:new_buddies}) OR real_name IN ({array_string:new_buddies})
LIMIT {int:count_new_buddies}',
array(
'new_buddies' => $new_buddies,
'count_new_buddies' => count($new_buddies),
)
);
if ($smcFunc['db_num_rows']($request) != 0)
$_SESSION['prf-save'] = true;
// Add the new member to the buddies array.
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (in_array($row['id_member'], $buddiesArray))
continue;
else
$buddiesArray[] = (int) $row['id_member'];
}
$smcFunc['db_free_result']($request);
// Now update the current users buddy list.
$user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
}
// Back to the buddy list!
redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
}
// Get all the users "buddies"...
$buddies = array();
// Gotta load the custom profile fields names.
$request = $smcFunc['db_query']('', '
SELECT col_name, field_name, field_desc, field_type, field_options, show_mlist, bbc, enclose
FROM {db_prefix}custom_fields
WHERE active = {int:active}
AND private < {int:private_level}',
array(
'active' => 1,
'private_level' => 2,
)
);
$context['custom_pf'] = array();
$disabled_fields = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
while ($row = $smcFunc['db_fetch_assoc']($request))
if (!isset($disabled_fields[$row['col_name']]) && !empty($row['show_mlist']))
$context['custom_pf'][$row['col_name']] = array(
'label' => tokenTxtReplace($row['field_name']),
'type' => $row['field_type'],
'options' => !empty($row['field_options']) ? explode(',', $row['field_options']) : array(),
'bbc' => !empty($row['bbc']),
'enclose' => $row['enclose'],
);
$smcFunc['db_free_result']($request);
if (!empty($buddiesArray))
{
$result = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}members
WHERE id_member IN ({array_int:buddy_list})
ORDER BY real_name
LIMIT {int:buddy_list_count}',
array(
'buddy_list' => $buddiesArray,
'buddy_list_count' => substr_count($user_profile[$memID]['buddy_list'], ',') + 1,
)
);
while ($row = $smcFunc['db_fetch_assoc']($result))
$buddies[] = $row['id_member'];
$smcFunc['db_free_result']($result);
}
$context['buddy_count'] = count($buddies);
// Load all the members up.
loadMemberData($buddies, false, 'profile');
// Setup the context for each buddy.
$context['buddies'] = array();
foreach ($buddies as $buddy)
{
loadMemberContext($buddy);
$context['buddies'][$buddy] = $memberContext[$buddy];
// Make sure to load the appropriate fields for each user
if (!empty($context['custom_pf']))
{
foreach ($context['custom_pf'] as $key => $column)
{
// Don't show anything if there isn't anything to show.
if (!isset($context['buddies'][$buddy]['options'][$key]))
{
$context['buddies'][$buddy]['options'][$key] = '';
continue;
}
$currentKey = 0;
if (!empty($column['options']))
{
foreach ($column['options'] as $k => $v)
{
if (empty($currentKey))
$currentKey = $v == $context['buddies'][$buddy]['options'][$key] ? $k : 0;
}
}
if ($column['bbc'] && !empty($context['buddies'][$buddy]['options'][$key]))
$context['buddies'][$buddy]['options'][$key] = strip_tags(parse_bbc($context['buddies'][$buddy]['options'][$key]));
elseif ($column['type'] == 'check')
$context['buddies'][$buddy]['options'][$key] = $context['buddies'][$buddy]['options'][$key] == 0 ? $txt['no'] : $txt['yes'];
// Enclosing the user input within some other text?
if (!empty($column['enclose']) && !empty($context['buddies'][$buddy]['options'][$key]))
$context['buddies'][$buddy]['options'][$key] = strtr($column['enclose'], array(
'{SCRIPTURL}' => $scripturl,
'{IMAGES_URL}' => $settings['images_url'],
'{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
'{KEY}' => $currentKey,
'{INPUT}' => tokenTxtReplace($context['buddies'][$buddy]['options'][$key]),
));
}
}
}
if (isset($_SESSION['prf-save']))
{
if ($_SESSION['prf-save'] === true)
$context['saved_successful'] = true;
else
$context['saved_failed'] = $_SESSION['prf-save'];
unset($_SESSION['prf-save']);
}
call_integration_hook('integrate_view_buddies', array($memID));
}
/**
* Allows the user to view their ignore list, as well as the option to manage members on it.
*
* @param int $memID The ID of the member
*/
function editIgnoreList($memID)
{
global $txt;
global $context, $user_profile, $memberContext, $smcFunc;
// For making changes!
$ignoreArray = explode(',', $user_profile[$memID]['pm_ignore_list']);
foreach ($ignoreArray as $k => $dummy)
if ($dummy == '')
unset($ignoreArray[$k]);
// Removing a member from the ignore list?
if (isset($_GET['remove']))
{
checkSession('get');
$_SESSION['prf-save'] = $txt['could_not_remove_person'];
// Heh, I'm lazy, do it the easy way...
foreach ($ignoreArray as $key => $id_remove)
if ($id_remove == (int) $_GET['remove'])
{
unset($ignoreArray[$key]);
$_SESSION['prf-save'] = true;
}
// Make the changes.
$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
// Redirect off the page because we don't like all this ugly query stuff to stick in the history.
redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
}
elseif (isset($_POST['new_ignore']))
{
checkSession();
// Prepare the string for extraction...
$_POST['new_ignore'] = strtr($smcFunc['htmlspecialchars']($_POST['new_ignore'], ENT_QUOTES), array('"' => '"'));
preg_match_all('~"([^"]+)"~', $_POST['new_ignore'], $matches);
$new_entries = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_ignore']))));
foreach ($new_entries as $k => $dummy)
{
$new_entries[$k] = strtr(trim($new_entries[$k]), array('\'' => '''));
if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
unset($new_entries[$k]);
}
$_SESSION['prf-save'] = $txt['could_not_add_person'];
if (!empty($new_entries))
{
// Now find out the id_member for the members in question.
$request = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}members
WHERE member_name IN ({array_string:new_entries}) OR real_name IN ({array_string:new_entries})
LIMIT {int:count_new_entries}',
array(
'new_entries' => $new_entries,
'count_new_entries' => count($new_entries),
)
);
if ($smcFunc['db_num_rows']($request) != 0)
$_SESSION['prf-save'] = true;
// Add the new member to the buddies array.
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (in_array($row['id_member'], $ignoreArray))
continue;
else
$ignoreArray[] = (int) $row['id_member'];
}
$smcFunc['db_free_result']($request);
// Now update the current users buddy list.
$user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
}
// Back to the list of pityful people!
redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
}
// Initialise the list of members we're ignoring.
$ignored = array();
if (!empty($ignoreArray))
{
$result = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}members
WHERE id_member IN ({array_int:ignore_list})
ORDER BY real_name
LIMIT {int:ignore_list_count}',
array(
'ignore_list' => $ignoreArray,
'ignore_list_count' => substr_count($user_profile[$memID]['pm_ignore_list'], ',') + 1,
)
);
while ($row = $smcFunc['db_fetch_assoc']($result))
$ignored[] = $row['id_member'];
$smcFunc['db_free_result']($result);
}
$context['ignore_count'] = count($ignored);
// Load all the members up.
loadMemberData($ignored, false, 'profile');
// Setup the context for each buddy.
$context['ignore_list'] = array();
foreach ($ignored as $ignore_member)
{
loadMemberContext($ignore_member);
$context['ignore_list'][$ignore_member] = $memberContext[$ignore_member];
}
if (isset($_SESSION['prf-save']))
{
if ($_SESSION['prf-save'] === true)
$context['saved_successful'] = true;
else
$context['saved_failed'] = $_SESSION['prf-save'];
unset($_SESSION['prf-save']);
}
}
/**
* Handles the account section of the profile
*
* @param int $memID The ID of the member
*/
function account($memID)
{
global $context, $txt;
loadThemeOptions($memID);
if (allowedTo(array('profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any')))
loadCustomFields($memID, 'account');
$context['sub_template'] = 'edit_options';
$context['page_desc'] = $txt['account_info'];
setupProfileContext(
array(
'member_name', 'real_name', 'date_registered', 'posts', 'lngfile', 'hr',
'id_group', 'hr',
'email_address', 'show_online', 'hr',
'tfa', 'hr',
'passwrd1', 'passwrd2', 'hr',
'secret_question', 'secret_answer',
)
);
}
/**
* Handles the main "Forum Profile" section of the profile
*
* @param int $memID The ID of the member
*/
function forumProfile($memID)
{
global $context, $txt;
loadThemeOptions($memID);
if (allowedTo(array('profile_forum_own', 'profile_forum_any')))
loadCustomFields($memID, 'forumprofile');
$context['sub_template'] = 'edit_options';
$context['page_desc'] = sprintf($txt['forumProfile_info'], $context['forum_name_html_safe']);
$context['show_preview_button'] = true;
setupProfileContext(
array(
'avatar_choice', 'hr', 'personal_text', 'hr',
'bday1', 'usertitle', 'signature', 'hr',
'website_title', 'website_url',
)
);
}
/**
* Recursive function to retrieve server-stored avatar files
*
* @param string $directory The directory to look for files in
* @param int $level How many levels we should go in the directory
* @return array An array of information about the files and directories found
*/
function getAvatars($directory, $level)
{
global $context, $txt, $modSettings, $smcFunc;
$result = array();
// Open the directory..
$dir = dir($modSettings['avatar_directory'] . (!empty($directory) ? '/' : '') . $directory);
$dirs = array();
$files = array();
if (!$dir)
return array();
while ($line = $dir->read())
{
if (in_array($line, array('.', '..', 'blank.png', 'index.php')))
continue;
if (is_dir($modSettings['avatar_directory'] . '/' . $directory . (!empty($directory) ? '/' : '') . $line))
$dirs[] = $line;
else
$files[] = $line;
}
$dir->close();
// Sort the results...
natcasesort($dirs);
natcasesort($files);
if ($level == 0)
{
$result[] = array(
'filename' => 'blank.png',
'checked' => in_array($context['member']['avatar']['server_pic'], array('', 'blank.png')),
'name' => $txt['no_pic'],
'is_dir' => false
);
}
foreach ($dirs as $line)
{
$tmp = getAvatars($directory . (!empty($directory) ? '/' : '') . $line, $level + 1);
if (!empty($tmp))
$result[] = array(
'filename' => $smcFunc['htmlspecialchars']($line),
'checked' => strpos($context['member']['avatar']['server_pic'], $line . '/') !== false,
'name' => '[' . $smcFunc['htmlspecialchars'](str_replace('_', ' ', $line)) . ']',
'is_dir' => true,
'files' => $tmp
);
unset($tmp);
}
foreach ($files as $line)
{
$filename = substr($line, 0, (strlen($line) - strlen(strrchr($line, '.'))));
$extension = substr(strrchr($line, '.'), 1);
// Make sure it is an image.
if (strcasecmp($extension, 'gif') != 0 && strcasecmp($extension, 'jpg') != 0 && strcasecmp($extension, 'jpeg') != 0 && strcasecmp($extension, 'png') != 0 && strcasecmp($extension, 'bmp') != 0)
continue;
$result[] = array(
'filename' => $smcFunc['htmlspecialchars']($line),
'checked' => $line == $context['member']['avatar']['server_pic'],
'name' => $smcFunc['htmlspecialchars'](str_replace('_', ' ', $filename)),
'is_dir' => false
);
if ($level == 1)
$context['avatar_list'][] = $directory . '/' . $line;
}
return $result;
}
/**
* Handles the "Look and Layout" section of the profile
*
* @param int $memID The ID of the member
*/
function theme($memID)
{
global $txt, $context;
loadTemplate('Settings');
loadSubTemplate('options');
// Let mods hook into the theme options.
call_integration_hook('integrate_theme_options');
loadThemeOptions($memID);
if (allowedTo(array('profile_extra_own', 'profile_extra_any')))
loadCustomFields($memID, 'theme');
$context['sub_template'] = 'edit_options';
$context['page_desc'] = $txt['theme_info'];
setupProfileContext(
array(
'id_theme', 'smiley_set', 'hr',
'time_format', 'timezone', 'hr',
'theme_settings',
)
);
}
/**
* Display the notifications and settings for changes.
*
* @param int $memID The ID of the member
*/
function notification($memID)
{
global $txt, $context;
// Going to want this for consistency.
loadCSSFile('admin.css', array(), 'smf_admin');
// This is just a bootstrap for everything else.
$sa = array(
'alerts' => 'alert_configuration',
'markread' => 'alert_markread',
'topics' => 'alert_notifications_topics',
'boards' => 'alert_notifications_boards',
);
$subAction = !empty($_GET['sa']) && isset($sa[$_GET['sa']]) ? $_GET['sa'] : 'alerts';
$context['sub_template'] = $sa[$subAction];
$context[$context['profile_menu_name']]['tab_data'] = array(
'title' => $txt['notification'],
'help' => '',
'description' => $txt['notification_info'],
);
$sa[$subAction]($memID);
}
/**
* Handles configuration of alert preferences
*
* @param int $memID The ID of the member
* @param bool $defaultSettings If true, we are loading default options.
*/
function alert_configuration($memID, $defaultSettings = false)
{
global $txt, $context, $modSettings, $smcFunc, $sourcedir, $user_profile;
if (!isset($context['token_check']))
$context['token_check'] = 'profile-nt' . $memID;
is_not_guest();
if (!$context['user']['is_owner'])
isAllowedTo('profile_extra_any');
// Set the post action if we're coming from the profile...
if (!isset($context['action']))
$context['action'] = 'action=profile;area=notification;sa=alerts;u=' . $memID;
// What options are set
loadThemeOptions($memID, $defaultSettings);
loadJavaScriptFile('alertSettings.js', array('minimize' => true), 'smf_alertSettings');
// Now load all the values for this user.
require_once($sourcedir . '/Subs-Notify.php');
$prefs = getNotifyPrefs($memID, '', $memID != 0);
$context['alert_prefs'] = !empty($prefs[$memID]) ? $prefs[$memID] : array();
$context['member'] += array(
'alert_timeout' => isset($context['alert_prefs']['alert_timeout']) ? $context['alert_prefs']['alert_timeout'] : 10,
'notify_announcements' => isset($context['alert_prefs']['announcements']) ? $context['alert_prefs']['announcements'] : 0,
);
// Now for the exciting stuff.
// We have groups of items, each item has both an alert and an email key as well as an optional help string.
// Valid values for these keys are 'always', 'yes', 'never'; if using always or never you should add a help string.
$alert_types = array(
'board' => array(
'topic_notify' => array('alert' => 'yes', 'email' => 'yes'),
'board_notify' => array('alert' => 'yes', 'email' => 'yes'),
),
'msg' => array(
'msg_mention' => array('alert' => 'yes', 'email' => 'yes'),
'msg_quote' => array('alert' => 'yes', 'email' => 'yes'),
'msg_like' => array('alert' => 'yes', 'email' => 'never'),
'unapproved_reply' => array('alert' => 'yes', 'email' => 'yes'),
),
'pm' => array(
'pm_new' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_read', 'is_board' => false)),
'pm_reply' => array('alert' => 'never', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_send', 'is_board' => false)),
),
'groupr' => array(
'groupr_approved' => array('alert' => 'yes', 'email' => 'yes'),
'groupr_rejected' => array('alert' => 'yes', 'email' => 'yes'),
),
'moderation' => array(
'unapproved_attachment' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
'unapproved_post' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'approve_posts', 'is_board' => true)),
'msg_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
'msg_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
'member_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
'member_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
),
'members' => array(
'member_register' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
'request_group' => array('alert' => 'yes', 'email' => 'yes'),
'warn_any' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'issue_warning', 'is_board' => false)),
'buddy_request' => array('alert' => 'yes', 'email' => 'never'),
'birthday' => array('alert' => 'yes', 'email' => 'yes'),
),
'calendar' => array(
'event_new' => array('alert' => 'yes', 'email' => 'yes', 'help' => 'alert_event_new'),
),
'paidsubs' => array(
'paidsubs_expiring' => array('alert' => 'yes', 'email' => 'yes'),
),
);
$group_options = array(
'board' => array(
array('check', 'msg_auto_notify', 'label' => 'after'),
array(empty($modSettings['disallow_sendBody']) ? 'check' : 'hide', 'msg_receive_body', 'label' => 'after'),
array('select', 'msg_notify_pref', 'label' => 'before', 'opts' => array(
0 => $txt['alert_opt_msg_notify_pref_never'],
1 => $txt['alert_opt_msg_notify_pref_instant'],
2 => $txt['alert_opt_msg_notify_pref_first'],
3 => $txt['alert_opt_msg_notify_pref_daily'],
4 => $txt['alert_opt_msg_notify_pref_weekly'],
)),
array('select', 'msg_notify_type', 'label' => 'before', 'opts' => array(
1 => $txt['notify_send_type_everything'],
2 => $txt['notify_send_type_everything_own'],
3 => $txt['notify_send_type_only_replies'],
4 => $txt['notify_send_type_nothing'],
)),
),
'pm' => array(
array('select', 'pm_notify', 'label' => 'before', 'opts' => array(
1 => $txt['email_notify_all'],
2 => $txt['email_notify_buddies'],
)),
),
);
// There are certain things that are disabled at the group level.
if (empty($modSettings['cal_enabled']))
unset($alert_types['calendar']);
// Disable paid subscriptions at group level if they're disabled
if (empty($modSettings['paid_enabled']))
unset($alert_types['paidsubs']);
// Disable membergroup requests at group level if they're disabled
if (empty($modSettings['show_group_membership']))
unset($alert_types['groupr'], $alert_types['members']['request_group']);
// Disable mentions if they're disabled
if (empty($modSettings['enable_mentions']))
unset($alert_types['msg']['msg_mention']);
// Disable likes if they're disabled
if (empty($modSettings['enable_likes']))
unset($alert_types['msg']['msg_like']);
// Disable buddy requests if they're disabled
if (empty($modSettings['enable_buddylist']))
unset($alert_types['members']['buddy_request']);
// Now, now, we could pass this through global but we should really get into the habit of
// passing content to hooks, not expecting hooks to splatter everything everywhere.
call_integration_hook('integrate_alert_types', array(&$alert_types, &$group_options));
// Now we have to do some permissions testing - but only if we're not loading this from the admin center
if (!empty($memID))
{
require_once($sourcedir . '/Subs-Membergroups.php');
$user_groups = explode(',', $user_profile[$memID]['additional_groups']);
$user_groups[] = $user_profile[$memID]['id_group'];
$user_groups[] = $user_profile[$memID]['id_post_group'];
$group_permissions = array('manage_membergroups');
$board_permissions = array();
foreach ($alert_types as $group => $items)
foreach ($items as $alert_key => $alert_value)
if (isset($alert_value['permission']))
{
if (empty($alert_value['permission']['is_board']))
$group_permissions[] = $alert_value['permission']['name'];
else
$board_permissions[] = $alert_value['permission']['name'];
}
$member_groups = getGroupsWithPermissions($group_permissions, $board_permissions);
if (empty($member_groups['manage_membergroups']['allowed']))
{
$request = $smcFunc['db_query']('', '
SELECT COUNT(*)
FROM {db_prefix}group_moderators
WHERE id_member = {int:memID}',
array(
'memID' => $memID,
)
);
list ($is_group_moderator) = $smcFunc['db_fetch_row']($request);
if (empty($is_group_moderator))
unset($alert_types['members']['request_group']);
}
foreach ($alert_types as $group => $items)
{
foreach ($items as $alert_key => $alert_value)
{
if (isset($alert_value['permission']))
{
$allowed = count(array_intersect($user_groups, $member_groups[$alert_value['permission']['name']]['allowed'])) != 0;
if (!$allowed)
unset($alert_types[$group][$alert_key]);
}
}
if (empty($alert_types[$group]))
unset($alert_types[$group]);
}
}
// And finally, exporting it to be useful later.
$context['alert_types'] = $alert_types;
$context['alert_group_options'] = $group_options;
$context['alert_bits'] = array(
'alert' => 0x01,
'email' => 0x02,
);
if (isset($_POST['notify_submit']))
{
checkSession();
validateToken($context['token_check'], 'post');
// We need to step through the list of valid settings and figure out what the user has set.
$update_prefs = array();
// Now the group level options
foreach ($context['alert_group_options'] as $opt_group => $group)
{
foreach ($group as $this_option)
{
switch ($this_option[0])
{
case 'check':
$update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
break;
case 'select':
if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
$update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
else
{
// We didn't have a sane value. Let's grab the first item from the possibles.
$keys = array_keys($this_option['opts']);
$first = array_shift($keys);
$update_prefs[$this_option[1]] = $first;
}
break;
}
}
}
// Now the individual options
foreach ($context['alert_types'] as $alert_group => $items)
{
foreach ($items as $item_key => $this_options)
{
$this_value = 0;
foreach ($context['alert_bits'] as $type => $bitvalue)
{
if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]) || $this_options[$type] == 'always')
$this_value |= $bitvalue;
}
$update_prefs[$item_key] = $this_value;
}
}
if (isset($_POST['opt_alert_timeout']))
$update_prefs['alert_timeout'] = $context['member']['alert_timeout'] = (int) $_POST['opt_alert_timeout'];
else
$update_prefs['alert_timeout'] = $context['alert_prefs']['alert_timeout'];
if (isset($_POST['notify_announcements']))
$update_prefs['announcements'] = $context['member']['notify_announcements'] = (int) $_POST['notify_announcements'];
else
$update_prefs['announcements'] = $context['alert_prefs']['announcements'];
setNotifyPrefs((int) $memID, $update_prefs);
foreach ($update_prefs as $pref => $value)
$context['alert_prefs'][$pref] = $value;
makeNotificationChanges($memID);
$context['profile_updated'] = $txt['profile_updated_own'];
}
createToken($context['token_check'], 'post');
}
/**
* Marks all alerts as read for the specified user
*
* @param int $memID The ID of the member
*/
function alert_markread($memID)
{
global $context, $db_show_debug, $smcFunc;
// We do not want to output debug information here.
$db_show_debug = false;
// We only want to output our little layer here.
$context['template_layers'] = array();
$context['sub_template'] = 'alerts_all_read';
loadLanguage('Alerts');
// Now we're all set up.
is_not_guest();
if (!$context['user']['is_owner'])
fatal_error('no_access');
checkSession('get');
// Assuming we're here, mark everything as read and head back.
// We only spit back the little layer because this should be called AJAXively.
$smcFunc['db_query']('', '
UPDATE {db_prefix}user_alerts
SET is_read = {int:now}
WHERE id_member = {int:current_member}
AND is_read = 0',
array(
'now' => time(),
'current_member' => $memID,
)
);
updateMemberData($memID, array('alerts' => 0));
}
/**
* Marks a group of alerts as un/read
*
* @param int $memID The user ID.
* @param array|integer $toMark The ID of a single alert or an array of IDs. The function will convert single integers to arrays for better handling.
* @param integer $read To mark as read or unread, 1 for read, 0 or any other value different than 1 for unread.
* @return integer How many alerts remain unread
*/
function alert_mark($memID, $toMark, $read = 0)
{
global $smcFunc;
if (empty($toMark) || empty($memID))
return false;
$toMark = (array) $toMark;
$smcFunc['db_query']('', '
UPDATE {db_prefix}user_alerts
SET is_read = {int:read}
WHERE id_alert IN({array_int:toMark})',
array(
'read' => $read == 1 ? time() : 0,
'toMark' => $toMark,
)
);
// Gotta know how many unread alerts are left.
$count = alert_count($memID, true);
updateMemberData($memID, array('alerts' => $count));
// Might want to know this.
return $count;
}
/**
* Deletes a single or a group of alerts by ID
*
* @param int|array The ID of a single alert to delete or an array containing the IDs of multiple alerts. The function will convert integers into an array for better handling.
* @param bool|int $memID The user ID. Used to update the user unread alerts count.
* @return void|int If the $memID param is set, returns the new amount of unread alerts.
*/
function alert_delete($toDelete, $memID = false)
{
global $smcFunc;
if (empty($toDelete))
return false;
$toDelete = (array) $toDelete;
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}user_alerts
WHERE id_alert IN({array_int:toDelete})',
array(
'toDelete' => $toDelete,
)
);
// Gotta know how many unread alerts are left.
if ($memID)
{
$count = alert_count($memID, true);
updateMemberData($memID, array('alerts' => $count));
// Might want to know this.
return $count;
}
}
/**
* Deletes all the alerts that a user has already read.
*
* @param int $memID The user ID. Defaults to the current user's ID.
*/
function alert_purge($memID = 0)
{
global $smcFunc, $user_info;
$memID = !empty($memID) && is_int($memID) ? $memID : $user_info['id'];
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}user_alerts
WHERE id_member = {int:memID}
AND is_read > 0',
array(
'memID' => $memID,
)
);
}
/**
* Counts how many alerts a user has - either unread or all depending on $unread
* We can't use db_num_rows here, as we have to determine what boards the user can see
* Possibly in future versions as database support for json is mainstream, we can simplify this.
*
* @param int $memID The user ID.
* @param bool $unread Whether to only count unread alerts.
* @return int The number of requested alerts
*/
function alert_count($memID, $unread = false)
{
global $smcFunc, $user_info;
if (empty($memID))
return false;
$alerts = array();
$possible_topics = array();
$possible_msgs = array();
$possible_attachments = array();
// We have to do this the slow way as to iterate over all possible boards the user can see.
$request = $smcFunc['db_query']('', '
SELECT id_alert, content_id, content_type, content_action, is_read
FROM {db_prefix}user_alerts
WHERE id_member = {int:id_member}
' . ($unread ? '
AND is_read = 0' : ''),
array(
'id_member' => $memID,
)
);
// First we dump alerts and possible boards information out.
while ($row = $smcFunc['db_fetch_assoc']($request))
{
$alerts[$row['id_alert']] = $row;
// For these types, we need to check whether they can actually see the content.
if ($row['content_type'] == 'msg')
{
$alerts[$row['id_alert']]['visible'] = false;
$possible_msgs[$row['id_alert']] = $row['content_id'];
}
elseif (in_array($row['content_type'], array('topic', 'board')))
{
$alerts[$row['id_alert']]['visible'] = false;
$possible_topics[$row['id_alert']] = $row['content_id'];
}
// For the rest, they can always see it.
else
$alerts[$row['id_alert']]['visible'] = true;
}
$smcFunc['db_free_result']($request);
// If we need to check board access, use the correct board access filter for the member in question.
if ((!isset($user_info['query_see_board']) || $user_info['id'] != $memID) && (!empty($possible_msgs) || !empty($possible_topics)))
$qb = build_query_board($memID);
else
{
$qb['query_see_topic_board'] = '{query_see_topic_board}';
$qb['query_see_message_board'] = '{query_see_message_board}';
}
// We want only the stuff they can see.
if (!empty($possible_msgs))
{
$flipped_msgs = array();
foreach ($possible_msgs as $id_alert => $id_msg)
{
if (!isset($flipped_msgs[$id_msg]))
$flipped_msgs[$id_msg] = array();
$flipped_msgs[$id_msg][] = $id_alert;
}
$request = $smcFunc['db_query']('', '
SELECT m.id_msg
FROM {db_prefix}messages AS m
WHERE ' . $qb['query_see_message_board'] . '
AND m.id_msg IN ({array_int:msgs})',
array(
'msgs' => $possible_msgs,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
foreach ($flipped_msgs[$row['id_msg']] as $id_alert)
$alerts[$id_alert]['visible'] = true;
}
$smcFunc['db_free_result']($request);
}
if (!empty($possible_topics))
{
$flipped_topics = array();
foreach ($possible_topics as $id_alert => $id_topic)
{
if (!isset($flipped_topics[$id_topic]))
$flipped_topics[$id_topic] = array();
$flipped_topics[$id_topic][] = $id_alert;
}
$request = $smcFunc['db_query']('', '
SELECT t.id_topic
FROM {db_prefix}topics AS t
WHERE ' . $qb['query_see_topic_board'] . '
AND t.id_topic IN ({array_int:topics})',
array(
'topics' => $possible_topics,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
foreach ($flipped_topics[$row['id_topic']] as $id_alert)
$alerts[$id_alert]['visible'] = true;
}
$smcFunc['db_free_result']($request);
}
// Now check alerts again and remove any they can't see.
$deletes = array();
$num_unread_deletes = 0;
foreach ($alerts as $id_alert => $alert)
{
if (!$alert['visible'])
{
if (empty($alert['is_read']))
$num_unread_deletes++;
unset($alerts[$id_alert]);
$deletes[] = $id_alert;
}
}
// Penultimate task - delete these orphaned, invisible alerts, otherwise they might hang around forever.
// This can happen if they are deleted or moved to a board this user cannot access.
// Note that unread alerts are never purged.
if (!empty($deletes))
{
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}user_alerts
WHERE id_alert IN ({array_int:alerts})',
array(
'alerts' => $deletes,
)
);
}
// One last thing - tweak counter on member record.
// Do it directly, as updateMemberData() calls this function, and may create a loop.
// Note that $user_info is not populated when this is invoked via cron, hence the CASE statement.
if ($num_unread_deletes > 0)
{
$smcFunc['db_query']('', '
UPDATE {db_prefix}members
SET alerts =
CASE
WHEN alerts < {int:unread_deletes} THEN 0
ELSE alerts - {int:unread_deletes}
END
WHERE id_member = {int:member}',
array(
'unread_deletes' => $num_unread_deletes,
'member' => $memID,
)
);
}
return count($alerts);
}
/**
* Handles alerts related to topics and posts
*
* @param int $memID The ID of the member
*/
function alert_notifications_topics($memID)
{
global $txt, $scripturl, $context, $modSettings, $sourcedir;
// Because of the way this stuff works, we want to do this ourselves.
if (isset($_POST['edit_notify_topics']) || isset($_POST['remove_notify_topics']))
{
checkSession();
validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
makeNotificationChanges($memID);
$context['profile_updated'] = $txt['profile_updated_own'];
}
// Now set up for the token check.
$context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
createToken($context['token_check'], 'post');
// Gonna want this for the list.
require_once($sourcedir . '/Subs-List.php');
// Do the topic notifications.
$listOptions = array(
'id' => 'topic_notification_list',
'width' => '100%',
'items_per_page' => $modSettings['defaultMaxListItems'],
'no_items_label' => $txt['notifications_topics_none'] . '