bbcodes)
{
$this->bbcode_init();
}
global $user;
$this->bbcode_bitfield = '';
$bitfield = new bitfield();
foreach ($this->bbcodes as $bbcode_name => $bbcode_data)
{
if (isset($bbcode_data['disabled']) && $bbcode_data['disabled'])
{
foreach ($bbcode_data['regexp'] as $regexp => $replacement)
{
if (preg_match($regexp, $this->message))
{
$this->warn_msg[] = sprintf($user->lang['UNAUTHORISED_BBCODE'] , '[' . $bbcode_name . ']');
continue;
}
}
}
else
{
foreach ($bbcode_data['regexp'] as $regexp => $replacement)
{
// The pattern gets compiled and cached by the PCRE extension,
// it should not demand recompilation
if (preg_match($regexp, $this->message))
{
$this->message = preg_replace($regexp, $replacement, $this->message);
$bitfield->set($bbcode_data['bbcode_id']);
}
}
}
}
$this->bbcode_bitfield = $bitfield->get_base64();
}
/**
* Prepare some bbcodes for better parsing
*/
function prepare_bbcodes()
{
// Ok, seems like users instead want the no-parsing of urls, smilies, etc. after and before and within quote tags being tagged as "not a bug".
// Fine by me ;) Will ease our live... but do not come back and cry at us, we won't hear you.
/* Add newline at the end and in front of each quote block to prevent parsing errors (urls, smilies, etc.)
if (strpos($this->message, '[quote') !== false && strpos($this->message, '[/quote]') !== false)
{
$this->message = str_replace("\r\n", "\n", $this->message);
// We strip newlines and spaces after and before quotes in quotes (trimming) and then add exactly one newline
$this->message = preg_replace('#\[quote(=".*?")?\]\s*(.*?)\s*\[/quote\]#siu', '[quote\1]' . "\n" . '\2' ."\n[/quote]", $this->message);
}
*/
// Add other checks which needs to be placed before actually parsing anything (be it bbcodes, smilies, urls...)
}
/**
* Init bbcode data for later parsing
*/
function bbcode_init()
{
static $rowset;
// This array holds all bbcode data. BBCodes will be processed in this
// order, so it is important to keep [code] in first position and
// [quote] in second position.
$this->bbcodes = array(
'code' => array('bbcode_id' => 8, 'regexp' => array('#\[code(?:=([a-z]+))?\](.+\[/code\])#ise' => "\$this->bbcode_code('\$1', '\$2')")),
'quote' => array('bbcode_id' => 0, 'regexp' => array('#\[quote(?:="(.*?)")?\](.+)\[/quote\]#ise' => "\$this->bbcode_quote('\$0')")),
'attachment' => array('bbcode_id' => 12, 'regexp' => array('#\[attachment=([0-9]+)\](.*?)\[/attachment\]#ise' => "\$this->bbcode_attachment('\$1', '\$2')")),
'b' => array('bbcode_id' => 1, 'regexp' => array('#\[b\](.*?)\[/b\]#ise' => "\$this->bbcode_strong('\$1')")),
'i' => array('bbcode_id' => 2, 'regexp' => array('#\[i\](.*?)\[/i\]#ise' => "\$this->bbcode_italic('\$1')")),
'url' => array('bbcode_id' => 3, 'regexp' => array('#\[url(=(.*))?\](.*)\[/url\]#iUe' => "\$this->validate_url('\$2', '\$3')")),
'img' => array('bbcode_id' => 4, 'regexp' => array('#\[img\](.*)\[/img\]#iUe' => "\$this->bbcode_img('\$1')")),
'size' => array('bbcode_id' => 5, 'regexp' => array('#\[size=([\-\+]?\d+)\](.*?)\[/size\]#ise' => "\$this->bbcode_size('\$1', '\$2')")),
'color' => array('bbcode_id' => 6, 'regexp' => array('!\[color=(#[0-9a-f]{6}|[a-z\-]+)\](.*?)\[/color\]!ise' => "\$this->bbcode_color('\$1', '\$2')")),
'u' => array('bbcode_id' => 7, 'regexp' => array('#\[u\](.*?)\[/u\]#ise' => "\$this->bbcode_underline('\$1')")),
'list' => array('bbcode_id' => 9, 'regexp' => array('#\[list(?:=(?:[a-z0-9]|disc|circle|square))?].*\[/list]#ise' => "\$this->bbcode_parse_list('\$0')")),
'email' => array('bbcode_id' => 10, 'regexp' => array('#\[email=?(.*?)?\](.*?)\[/email\]#ise' => "\$this->validate_email('\$1', '\$2')")),
'flash' => array('bbcode_id' => 11, 'regexp' => array('#\[flash=([0-9]+),([0-9]+)\](.*?)\[/flash\]#ie' => "\$this->bbcode_flash('\$1', '\$2', '\$3')"))
);
// Zero the parsed items array
$this->parsed_items = array();
foreach ($this->bbcodes as $tag => $bbcode_data)
{
$this->parsed_items[$tag] = 0;
}
if (!is_array($rowset))
{
global $db;
$rowset = array();
$sql = 'SELECT *
FROM ' . BBCODES_TABLE;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$rowset[] = $row;
}
$db->sql_freeresult($result);
}
foreach ($rowset as $row)
{
$this->bbcodes[$row['bbcode_tag']] = array(
'bbcode_id' => (int) $row['bbcode_id'],
'regexp' => array($row['first_pass_match'] => str_replace('$uid', $this->bbcode_uid, $row['first_pass_replace']))
);
}
}
/**
* Making some pre-checks for bbcodes as well as increasing the number of parsed items
*/
function check_bbcode($bbcode, &$in)
{
// when using the /e modifier, preg_replace slashes double-quotes but does not
// seem to slash anything else
$in = str_replace("\r\n", "\n", str_replace('\"', '"', $in));
// Trimming here to make sure no empty bbcodes are parsed accidently
if (trim($in) == '')
{
return false;
}
$this->parsed_items[$bbcode]++;
return true;
}
/**
* Transform some characters in valid bbcodes
*/
function bbcode_specialchars($text)
{
$str_from = array('<', '>', '[', ']', '.', ':');
$str_to = array('<', '>', '[', ']', '.', ':');
return str_replace($str_from, $str_to, $text);
}
/**
* Parse size tag
*/
function bbcode_size($stx, $in)
{
global $user, $config;
if (!$this->check_bbcode('size', $in))
{
return $in;
}
if ($config['max_' . $this->mode . '_font_size'] && $config['max_' . $this->mode . '_font_size'] < $stx)
{
$this->warn_msg[] = sprintf($user->lang['MAX_FONT_SIZE_EXCEEDED'], $config['max_' . $this->mode . '_font_size']);
return '[size=' . $stx . ']' . $in . '[/size]';
}
// Do not allow size=0
if ($stx <= 0)
{
return '[size=' . $stx . ']' . $in . '[/size]';
}
return '[size=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/size:' . $this->bbcode_uid . ']';
}
/**
* Parse color tag
*/
function bbcode_color($stx, $in)
{
if (!$this->check_bbcode('color', $in))
{
return $in;
}
return '[color=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/color:' . $this->bbcode_uid . ']';
}
/**
* Parse u tag
*/
function bbcode_underline($in)
{
if (!$this->check_bbcode('u', $in))
{
return $in;
}
return '[u:' . $this->bbcode_uid . ']' . $in . '[/u:' . $this->bbcode_uid . ']';
}
/**
* Parse b tag
*/
function bbcode_strong($in)
{
if (!$this->check_bbcode('b', $in))
{
return $in;
}
return '[b:' . $this->bbcode_uid . ']' . $in . '[/b:' . $this->bbcode_uid . ']';
}
/**
* Parse i tag
*/
function bbcode_italic($in)
{
if (!$this->check_bbcode('i', $in))
{
return $in;
}
return '[i:' . $this->bbcode_uid . ']' . $in . '[/i:' . $this->bbcode_uid . ']';
}
/**
* Parse img tag
*/
function bbcode_img($in)
{
global $user, $config;
if (!$this->check_bbcode('img', $in))
{
return $in;
}
$in = trim($in);
$error = false;
$in = str_replace(' ', '%20', $in);
// Checking urls
if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) && !preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
{
return '[img]' . $in . '[/img]';
}
// Try to cope with a common user error... not specifying a protocol but only a subdomain
if (!preg_match('#^[a-z0-9]+://#i', $in))
{
$in = 'http://' . $in;
}
if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
{
$stats = @getimagesize($in);
if ($stats === false)
{
$error = true;
$this->warn_msg[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
}
else
{
if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $stats[1])
{
$error = true;
$this->warn_msg[] = sprintf($user->lang['MAX_IMG_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
}
if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $stats[0])
{
$error = true;
$this->warn_msg[] = sprintf($user->lang['MAX_IMG_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
}
}
}
if ($error || $this->path_in_domain($in))
{
return '[img]' . $in . '[/img]';
}
return '[img:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/img:' . $this->bbcode_uid . ']';
}
/**
* Parse flash tag
*/
function bbcode_flash($width, $height, $in)
{
global $user, $config;
if (!$this->check_bbcode('flash', $in))
{
return $in;
}
$in = trim($in);
$error = false;
// Do not allow 0-sizes generally being entered
if ($width <= 0 || $height <= 0)
{
return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
}
// Apply the same size checks on flash files as on images
if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
{
if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $height)
{
$error = true;
$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
}
if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $width)
{
$error = true;
$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
}
}
if ($error || $this->path_in_domain($in))
{
return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
}
return '[flash=' . $width . ',' . $height . ':' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/flash:' . $this->bbcode_uid . ']';
}
/**
* Parse inline attachments [ia]
*/
function bbcode_attachment($stx, $in)
{
if (!$this->check_bbcode('attachment', $in))
{
return $in;
}
return '[attachment=' . $stx . ':' . $this->bbcode_uid . ']' . trim($in) . '[/attachment:' . $this->bbcode_uid . ']';
}
/**
* Parse code text from code tag
* @access private
*/
function bbcode_parse_code($stx, &$code)
{
switch (strtolower($stx))
{
case 'php':
$remove_tags = false;
$str_from = array('<', '>', '[', ']', '.', ':', ':');
$str_to = array('<', '>', '[', ']', '.', ':', ':');
$code = str_replace($str_from, $str_to, $code);
if (!preg_match('/\<\?.*?\?\>/is', $code))
{
$remove_tags = true;
$code = "";
}
$conf = array('highlight.bg', 'highlight.comment', 'highlight.default', 'highlight.html', 'highlight.keyword', 'highlight.string');
foreach ($conf as $ini_var)
{
@ini_set($ini_var, str_replace('highlight.', 'syntax', $ini_var));
}
// Because highlight_string is specialcharing the text (but we already did this before), we have to reverse this in order to get correct results
$code = htmlspecialchars_decode($code);
$code = highlight_string($code, true);
$str_from = array('', '', '','[', ']', '.', ':');
$str_to = array('', '', '', '[', ']', '.', ':');
if ($remove_tags)
{
$str_from[] = '<?php ';
$str_to[] = '';
$str_from[] = '<?php ';
$str_to[] = '';
}
$code = str_replace($str_from, $str_to, $code);
$code = preg_replace('#^()\n?(.*?)\n?()$#is', '$1$2$3', $code);
if ($remove_tags)
{
$code = preg_replace('#()?\?>()#', '$1 $2', $code);
}
$code = preg_replace('#^(.*)#s', '$2', $code);
$code = preg_replace('#(?:\s++| )*+$#u', '', $code);
// remove newline at the end
if (!empty($code) && substr($code, -1) == "\n")
{
$code = substr($code, 0, -1);
}
return "[code=$stx:" . $this->bbcode_uid . ']' . $code . '[/code:' . $this->bbcode_uid . ']';
break;
default:
return '[code:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($code) . '[/code:' . $this->bbcode_uid . ']';
break;
}
}
/**
* Parse code tag
* Expects the argument to start right after the opening [code] tag and to end with [/code]
*/
function bbcode_code($stx, $in)
{
if (!$this->check_bbcode('code', $in))
{
return $in;
}
// We remove the hardcoded elements from the code block here because it is not used in code blocks
// Having it here saves us one preg_replace per message containing [code] blocks
// Additionally, magic url parsing should go after parsing bbcodes, but for safety those are stripped out too...
$htm_match = get_preg_expression('bbcode_htm');
unset($htm_match[4], $htm_match[5]);
$htm_replace = array('\1', '\1', '\2', '\1');
$out = $code_block = '';
$open = 1;
while ($in)
{
// Determine position and tag length of next code block
preg_match('#(.*?)(\[code(?:=([a-z]+))?\])(.+)#is', $in, $buffer);
$pos = (isset($buffer[1])) ? strlen($buffer[1]) : false;
$tag_length = (isset($buffer[2])) ? strlen($buffer[2]) : false;
// Determine position of ending code tag
$pos2 = stripos($in, '[/code]');
// Which is the next block, ending code or code block
if ($pos !== false && $pos < $pos2)
{
// Open new block
if (!$open)
{
$out .= substr($in, 0, $pos);
$in = substr($in, $pos);
$stx = (isset($buffer[3])) ? $buffer[3] : '';
$code_block = '';
}
else
{
// Already opened block, just append to the current block
$code_block .= substr($in, 0, $pos) . ((isset($buffer[2])) ? $buffer[2] : '');
$in = substr($in, $pos);
}
$in = substr($in, $tag_length);
$open++;
}
else
{
// Close the block
if ($open == 1)
{
$code_block .= substr($in, 0, $pos2);
$code_block = preg_replace($htm_match, $htm_replace, $code_block);
// Parse this code block
$out .= $this->bbcode_parse_code($stx, $code_block);
$code_block = '';
$open--;
}
else if ($open)
{
// Close one open tag... add to the current code block
$code_block .= substr($in, 0, $pos2 + 7);
$open--;
}
else
{
// end code without opening code... will be always outside code block
$out .= substr($in, 0, $pos2 + 7);
}
$in = substr($in, $pos2 + 7);
}
}
// if now $code_block has contents we need to parse the remaining code while removing the last closing tag to match up.
if ($code_block)
{
$code_block = substr($code_block, 0, -7);
$code_block = preg_replace($htm_match, $htm_replace, $code_block);
$out .= $this->bbcode_parse_code($stx, $code_block);
}
return $out;
}
/**
* Parse list bbcode
* Expects the argument to start with a tag
*/
function bbcode_parse_list($in)
{
if (!$this->check_bbcode('list', $in))
{
return $in;
}
// $tok holds characters to stop at. Since the string starts with a '[' we'll get everything up to the first ']' which should be the opening [list] tag
$tok = ']';
$out = '[';
// First character is [
$in = substr($in, 1);
$list_end_tags = $item_end_tags = array();
do
{
$pos = strlen($in);
for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
{
$tmp_pos = strpos($in, $tok[$i]);
if ($tmp_pos !== false && $tmp_pos < $pos)
{
$pos = $tmp_pos;
}
}
$buffer = substr($in, 0, $pos);
$tok = $in[$pos];
$in = substr($in, $pos + 1);
if ($tok == ']')
{
// if $tok is ']' the buffer holds a tag
if (strtolower($buffer) == '/list' && sizeof($list_end_tags))
{
// valid [/list] tag, check nesting so that we don't hit false positives
if (sizeof($item_end_tags) && sizeof($item_end_tags) >= sizeof($list_end_tags))
{
// current li tag has not been closed
$out = preg_replace('/\n?\[$/', '[', $out) . array_pop($item_end_tags) . '][';
}
$out .= array_pop($list_end_tags) . ']';
$tok = '[';
}
else if (preg_match('#^list(=[0-9a-z]+)?$#i', $buffer, $m))
{
// sub-list, add a closing tag
if (empty($m[1]) || preg_match('/^(?:disc|square|circle)$/i', $m[1]))
{
array_push($list_end_tags, '/list:u:' . $this->bbcode_uid);
}
else
{
array_push($list_end_tags, '/list:o:' . $this->bbcode_uid);
}
$out .= 'list' . substr($buffer, 4) . ':' . $this->bbcode_uid . ']';
$tok = '[';
}
else
{
if (($buffer == '*' || substr($buffer, -2) == '[*') && sizeof($list_end_tags))
{
// the buffer holds a bullet tag and we have a [list] tag open
if (sizeof($item_end_tags) >= sizeof($list_end_tags))
{
if (substr($buffer, -2) == '[*')
{
$out .= substr($buffer, 0, -2) . '[';
}
// current li tag has not been closed
if (preg_match('/\n\[$/', $out, $m))
{
$out = preg_replace('/\n\[$/', '[', $out);
$buffer = array_pop($item_end_tags) . "]\n[*:" . $this->bbcode_uid;
}
else
{
$buffer = array_pop($item_end_tags) . '][*:' . $this->bbcode_uid;
}
}
else
{
$buffer = '*:' . $this->bbcode_uid;
}
$item_end_tags[] = '/*:m:' . $this->bbcode_uid;
}
else if ($buffer == '/*')
{
array_pop($item_end_tags);
$buffer = '/*:' . $this->bbcode_uid;
}
$out .= $buffer . $tok;
$tok = '[]';
}
}
else
{
// Not within a tag, just add buffer to the return string
$out .= $buffer . $tok;
$tok = ($tok == '[') ? ']' : '[]';
}
}
while ($in);
// do we have some tags open? close them now
if (sizeof($item_end_tags))
{
$out .= '[' . implode('][', $item_end_tags) . ']';
}
if (sizeof($list_end_tags))
{
$out .= '[' . implode('][', $list_end_tags) . ']';
}
return $out;
}
/**
* Parse quote bbcode
* Expects the argument to start with a tag
*/
function bbcode_quote($in)
{
global $config, $user;
/**
* If you change this code, make sure the cases described within the following reports are still working:
* #3572 - [quote="[test]test"]test [ test[/quote] - (correct: parsed)
* #14667 - [quote]test[/quote] test ] and [ test [quote]test[/quote] (correct: parsed)
* #14770 - [quote="["]test[/quote] (correct: parsed)
* [quote="[i]test[/i]"]test[/quote] (correct: parsed)
* [quote="[quote]test[/quote]"]test[/quote] (correct: parsed - Username displayed as [quote]test[/quote])
* #20735 - [quote]test[/[/b]quote] test [/quote][/quote] test - (correct: quoted: "test[/[/b]quote] test" / non-quoted: "[/quote] test" - also failed if layout distorted)
*/
$in = str_replace("\r\n", "\n", str_replace('\"', '"', trim($in)));
if (!$in)
{
return '';
}
// To let the parser not catch tokens within quote_username quotes we encode them before we start this...
$in = preg_replace('#quote="(.*?)"\]#ie', "'quote="' . str_replace(array('[', ']'), array('[', ']'), '\$1') . '"]'", $in);
$tok = ']';
$out = '[';
$in = substr($in, 1);
$close_tags = $error_ary = array();
$buffer = '';
do
{
$pos = strlen($in);
for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
{
$tmp_pos = strpos($in, $tok[$i]);
if ($tmp_pos !== false && $tmp_pos < $pos)
{
$pos = $tmp_pos;
}
}
$buffer .= substr($in, 0, $pos);
$tok = $in[$pos];
$in = substr($in, $pos + 1);
if ($tok == ']')
{
if (strtolower($buffer) == '/quote' && sizeof($close_tags) && substr($out, -1, 1) == '[')
{
// we have found a closing tag
$out .= array_pop($close_tags) . ']';
$tok = '[';
$buffer = '';
/* Add space at the end of the closing tag if not happened before to allow following urls/smilies to be parsed correctly
* Do not try to think for the user. :/ Do not parse urls/smilies if there is no space - is the same as with other bbcodes too.
* Also, we won't have any spaces within $in anyway, only adding up spaces -> #10982
if (!$in || $in[0] !== ' ')
{
$out .= ' ';
}*/
}
else if (preg_match('#^quote(?:="(.*?)")?$#is', $buffer, $m) && substr($out, -1, 1) == '[')
{
$this->parsed_items['quote']++;
// the buffer holds a valid opening tag
if ($config['max_quote_depth'] && sizeof($close_tags) >= $config['max_quote_depth'])
{
// there are too many nested quotes
$error_ary['quote_depth'] = sprintf($user->lang['QUOTE_DEPTH_EXCEEDED'], $config['max_quote_depth']);
$out .= $buffer . $tok;
$tok = '[]';
$buffer = '';
continue;
}
array_push($close_tags, '/quote:' . $this->bbcode_uid);
if (isset($m[1]) && $m[1])
{
$username = str_replace(array('[', ']'), array('[', ']'), $m[1]);
$username = preg_replace('#\[(?!b|i|u|color|url|email|/b|/i|/u|/color|/url|/email)#iU', '[$1', $username);
$end_tags = array();
$error = false;
preg_match_all('#\[((?:/)?(?:[a-z]+))#i', $username, $tags);
foreach ($tags[1] as $tag)
{
if ($tag[0] != '/')
{
$end_tags[] = '/' . $tag;
}
else
{
$end_tag = array_pop($end_tags);
$error = ($end_tag != $tag) ? true : false;
}
}
if ($error)
{
$username = $m[1];
}
$out .= 'quote="' . $username . '":' . $this->bbcode_uid . ']';
}
else
{
$out .= 'quote:' . $this->bbcode_uid . ']';
}
$tok = '[';
$buffer = '';
}
else if (preg_match('#^quote="(.*?)#is', $buffer, $m))
{
// the buffer holds an invalid opening tag
$buffer .= ']';
}
else
{
$out .= $buffer . $tok;
$tok = '[]';
$buffer = '';
}
}
else
{
/**
* Old quote code working fine, but having errors listed in bug #3572
*
* $out .= $buffer . $tok;
* $tok = ($tok == '[') ? ']' : '[]';
* $buffer = '';
*/
$out .= $buffer . $tok;
if ($tok == '[')
{
// Search the text for the next tok... if an ending quote comes first, then change tok to []
$pos1 = stripos($in, '[/quote');
// If the token ] comes first, we change it to ]
$pos2 = strpos($in, ']');
// If the token [ comes first, we change it to [
$pos3 = strpos($in, '[');
if ($pos1 !== false && ($pos2 === false || $pos1 < $pos2) && ($pos3 === false || $pos1 < $pos3))
{
$tok = '[]';
}
else if ($pos3 !== false && ($pos2 === false || $pos3 < $pos2))
{
$tok = '[';
}
else
{
$tok = ']';
}
}
else
{
$tok = '[]';
}
$buffer = '';
}
}
while ($in);
if (sizeof($close_tags))
{
$out .= '[' . implode('][', $close_tags) . ']';
}
foreach ($error_ary as $error_msg)
{
$this->warn_msg[] = $error_msg;
}
return $out;
}
/**
* Validate email
*/
function validate_email($var1, $var2)
{
$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
$txt = $var2;
$email = ($var1) ? $var1 : $var2;
$validated = true;
if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
{
$validated = false;
}
if (!$validated)
{
return '[email' . (($var1) ? "=$var1" : '') . ']' . $var2 . '[/email]';
}
$this->parsed_items['email']++;
if ($var1)
{
$retval = '[email=' . $this->bbcode_specialchars($email) . ':' . $this->bbcode_uid . ']' . $txt . '[/email:' . $this->bbcode_uid . ']';
}
else
{
$retval = '[email:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($email) . '[/email:' . $this->bbcode_uid . ']';
}
return $retval;
}
/**
* Validate url
*
* @param string $var1 optional url parameter for url bbcode: [url(=$var1)]$var2[/url]
* @param string $var2 url bbcode content: [url(=$var1)]$var2[/url]
*/
function validate_url($var1, $var2)
{
global $config;
$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
$url = ($var1) ? $var1 : $var2;
if ($var1 && !$var2)
{
$var2 = $var1;
}
if (!$url)
{
return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
}
$valid = false;
$url = str_replace(' ', '%20', $url);
// Checking urls
if (preg_match('#^' . get_preg_expression('url') . '$#i', $url) ||
preg_match('#^' . get_preg_expression('www_url') . '$#i', $url) ||
preg_match('#^' . preg_quote(generate_board_url(), '#') . get_preg_expression('relative_url') . '$#i', $url))
{
$valid = true;
}
if ($valid)
{
$this->parsed_items['url']++;
// if there is no scheme, then add http schema
if (!preg_match('#^[a-z][a-z\d+\-.]*:/{2}#i', $url))
{
$url = 'http://' . $url;
}
// Is this a link to somewhere inside this board? If so then remove the session id from the url
if (strpos($url, generate_board_url()) !== false && strpos($url, 'sid=') !== false)
{
$url = preg_replace('/(&|\?)sid=[0-9a-f]{32}&/', '\1', $url);
$url = preg_replace('/(&|\?)sid=[0-9a-f]{32}$/', '', $url);
$url = append_sid($url);
}
return ($var1) ? '[url=' . $this->bbcode_specialchars($url) . ':' . $this->bbcode_uid . ']' . $var2 . '[/url:' . $this->bbcode_uid . ']' : '[url:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($url) . '[/url:' . $this->bbcode_uid . ']';
}
return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
}
/**
* Check if url is pointing to this domain/script_path/php-file
*
* @param string $url the url to check
* @return true if the url is pointing to this domain/script_path/php-file, false if not
*
* @access private
*/
function path_in_domain($url)
{
global $config, $phpEx, $user;
if ($config['force_server_vars'])
{
$check_path = $config['script_path'];
}
else
{
$check_path = ($user->page['root_script_path'] != '/') ? substr($user->page['root_script_path'], 0, -1) : '/';
}
// Is the user trying to link to a php file in this domain and script path?
if (strpos($url, ".{$phpEx}") !== false && strpos($url, $check_path) !== false)
{
$server_name = $user->host;
// Forcing server vars is the only way to specify/override the protocol
if ($config['force_server_vars'] || !$server_name)
{
$server_name = $config['server_name'];
}
// Check again in correct order...
$pos_ext = strpos($url, ".{$phpEx}");
$pos_path = strpos($url, $check_path);
$pos_domain = strpos($url, $server_name);
if ($pos_domain !== false && $pos_path >= $pos_domain && $pos_ext >= $pos_path)
{
// Ok, actually we allow linking to some files (this may be able to be extended in some way later...)
if (strpos($url, '/' . $check_path . '/download/file.' . $phpEx) !== 0)
{
return false;
}
return true;
}
}
return false;
}
}
/**
* Main message parser for posting, pm, etc. takes raw message
* and parses it for attachments, bbcode and smilies
* @package phpBB3
*/
class parse_message extends bbcode_firstpass
{
var $attachment_data = array();
var $filename_data = array();
// Helps ironing out user error
var $message_status = '';
var $allow_img_bbcode = true;
var $allow_flash_bbcode = true;
var $allow_quote_bbcode = true;
var $allow_url_bbcode = true;
var $mode;
/**
* Init - give message here or manually
*/
function parse_message($message = '')
{
// Init BBCode UID
$this->bbcode_uid = substr(base_convert(unique_id(), 16, 36), 0, BBCODE_UID_LEN);
if ($message)
{
$this->message = $message;
}
}
/**
* Parse Message
*/
function parse($allow_bbcode, $allow_magic_url, $allow_smilies, $allow_img_bbcode = true, $allow_flash_bbcode = true, $allow_quote_bbcode = true, $allow_url_bbcode = true, $update_this_message = true, $mode = 'post')
{
global $config, $db, $user;
$mode = ($mode != 'post') ? 'sig' : 'post';
$this->mode = $mode;
$this->allow_img_bbcode = $allow_img_bbcode;
$this->allow_flash_bbcode = $allow_flash_bbcode;
$this->allow_quote_bbcode = $allow_quote_bbcode;
$this->allow_url_bbcode = $allow_url_bbcode;
// If false, then $this->message won't be altered, the text will be returned instead.
if (!$update_this_message)
{
$tmp_message = $this->message;
$return_message = &$this->message;
}
if ($this->message_status == 'display')
{
$this->decode_message();
}
// Do some general 'cleanup' first before processing message,
// e.g. remove excessive newlines(?), smilies(?)
$match = array('#(script|about|applet|activex|chrome):#i');
$replace = array("\\1:");
$this->message = preg_replace($match, $replace, trim($this->message));
// Message length check. 0 disables this check completely.
if ($config['max_' . $mode . '_chars'] > 0)
{
$msg_len = ($mode == 'post') ? utf8_strlen($this->message) : utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message));
if ((!$msg_len && $mode !== 'sig') || $config['max_' . $mode . '_chars'] && $msg_len > $config['max_' . $mode . '_chars'])
{
$this->warn_msg[] = (!$msg_len) ? $user->lang['TOO_FEW_CHARS'] : sprintf($user->lang['TOO_MANY_CHARS_' . strtoupper($mode)], $msg_len, $config['max_' . $mode . '_chars']);
return (!$update_this_message) ? $return_message : $this->warn_msg;
}
}
// Check for "empty" message
if ($mode !== 'sig' && utf8_clean_string($this->message) === '')
{
$this->warn_msg[] = $user->lang['TOO_FEW_CHARS'];
return (!$update_this_message) ? $return_message : $this->warn_msg;
}
// Prepare BBcode (just prepares some tags for better parsing)
if ($allow_bbcode && strpos($this->message, '[') !== false)
{
$this->bbcode_init();
$disallow = array('img', 'flash', 'quote', 'url');
foreach ($disallow as $bool)
{
if (!${'allow_' . $bool . '_bbcode'})
{
$this->bbcodes[$bool]['disabled'] = true;
}
}
$this->prepare_bbcodes();
}
// Parse smilies
if ($allow_smilies)
{
$this->smilies($config['max_' . $mode . '_smilies']);
}
$num_urls = 0;
// Parse BBCode
if ($allow_bbcode && strpos($this->message, '[') !== false)
{
$this->parse_bbcode();
$num_urls += $this->parsed_items['url'];
}
// Parse URL's
if ($allow_magic_url)
{
$this->magic_url(generate_board_url());
if ($config['max_' . $mode . '_urls'])
{
$num_urls += preg_match_all('#\';
}
$db->sql_freeresult($result);
}
if (sizeof($match))
{
if ($max_smilies)
{
$num_matches = preg_match_all('#' . implode('|', $match) . '#', $this->message, $matches);
unset($matches);
if ($num_matches !== false && $num_matches > $max_smilies)
{
$this->warn_msg[] = sprintf($user->lang['TOO_MANY_SMILIES'], $max_smilies);
return;
}
}
// Make sure the delimiter # is added in front and at the end of every element within $match
$this->message = trim(preg_replace(explode(chr(0), '#' . implode('#' . chr(0) . '#', $match) . '#'), $replace, $this->message));
}
}
/**
* Parse Attachments
*/
function parse_attachments($form_name, $mode, $forum_id, $submit, $preview, $refresh, $is_message = false)
{
global $config, $auth, $user, $phpbb_root_path, $phpEx, $db;
$error = array();
$num_attachments = sizeof($this->attachment_data);
$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
$upload_file = (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none' && trim($_FILES[$form_name]['name'])) ? true : false;
$add_file = (isset($_POST['add_file'])) ? true : false;
$delete_file = (isset($_POST['delete_file'])) ? true : false;
// First of all adjust comments if changed
$actual_comment_list = utf8_normalize_nfc(request_var('comment_list', array(''), true));
foreach ($actual_comment_list as $comment_key => $comment)
{
if (!isset($this->attachment_data[$comment_key]))
{
continue;
}
if ($this->attachment_data[$comment_key]['attach_comment'] != $actual_comment_list[$comment_key])
{
$this->attachment_data[$comment_key]['attach_comment'] = $actual_comment_list[$comment_key];
}
}
$cfg = array();
$cfg['max_attachments'] = ($is_message) ? $config['max_attachments_pm'] : $config['max_attachments'];
$forum_id = ($is_message) ? 0 : $forum_id;
if ($submit && in_array($mode, array('post', 'reply', 'quote', 'edit')) && $upload_file)
{
if ($num_attachments < $cfg['max_attachments'] || $auth->acl_get('a_') || $auth->acl_get('m_', $forum_id))
{
$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
$error = $filedata['error'];
if ($filedata['post_attach'] && !sizeof($error))
{
$sql_ary = array(
'physical_filename' => $filedata['physical_filename'],
'attach_comment' => $this->filename_data['filecomment'],
'real_filename' => $filedata['real_filename'],
'extension' => $filedata['extension'],
'mimetype' => $filedata['mimetype'],
'filesize' => $filedata['filesize'],
'filetime' => $filedata['filetime'],
'thumbnail' => $filedata['thumbnail'],
'is_orphan' => 1,
'in_message' => ($is_message) ? 1 : 0,
'poster_id' => $user->data['user_id'],
);
$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
$new_entry = array(
'attach_id' => $db->sql_nextid(),
'is_orphan' => 1,
'real_filename' => $filedata['real_filename'],
'attach_comment'=> $this->filename_data['filecomment'],
);
$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
$this->filename_data['filecomment'] = '';
// This Variable is set to false here, because Attachments are entered into the
// Database in two modes, one if the id_list is 0 and the second one if post_attach is true
// Since post_attach is automatically switched to true if an Attachment got added to the filesystem,
// but we are assigning an id of 0 here, we have to reset the post_attach variable to false.
//
// This is very relevant, because it could happen that the post got not submitted, but we do not
// know this circumstance here. We could be at the posting page or we could be redirected to the entered
// post. :)
$filedata['post_attach'] = false;
}
}
else
{
$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
}
}
if ($preview || $refresh || sizeof($error))
{
// Perform actions on temporary attachments
if ($delete_file)
{
include_once($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
$index = array_keys(request_var('delete_file', array(0 => 0)));
$index = (!empty($index)) ? $index[0] : false;
if ($index !== false && !empty($this->attachment_data[$index]))
{
// delete selected attachment
if ($this->attachment_data[$index]['is_orphan'])
{
$sql = 'SELECT attach_id, physical_filename, thumbnail
FROM ' . ATTACHMENTS_TABLE . '
WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id'] . '
AND is_orphan = 1
AND poster_id = ' . $user->data['user_id'];
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($row)
{
phpbb_unlink($row['physical_filename'], 'file');
if ($row['thumbnail'])
{
phpbb_unlink($row['physical_filename'], 'thumbnail');
}
$db->sql_query('DELETE FROM ' . ATTACHMENTS_TABLE . ' WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id']);
}
}
else
{
delete_attachments('attach', array(intval($this->attachment_data[$index]['attach_id'])));
}
unset($this->attachment_data[$index]);
$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "(\\1 == \$index) ? '' : ((\\1 > \$index) ? '[attachment=' . (\\1 - 1) . ']\\2[/attachment]' : '\\0')", $this->message);
// Reindex Array
$this->attachment_data = array_values($this->attachment_data);
}
}
else if (($add_file || $preview) && $upload_file)
{
if ($num_attachments < $cfg['max_attachments'] || $auth->acl_gets('m_', 'a_', $forum_id))
{
$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
$error = array_merge($error, $filedata['error']);
if (!sizeof($error))
{
$sql_ary = array(
'physical_filename' => $filedata['physical_filename'],
'attach_comment' => $this->filename_data['filecomment'],
'real_filename' => $filedata['real_filename'],
'extension' => $filedata['extension'],
'mimetype' => $filedata['mimetype'],
'filesize' => $filedata['filesize'],
'filetime' => $filedata['filetime'],
'thumbnail' => $filedata['thumbnail'],
'is_orphan' => 1,
'in_message' => ($is_message) ? 1 : 0,
'poster_id' => $user->data['user_id'],
);
$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
$new_entry = array(
'attach_id' => $db->sql_nextid(),
'is_orphan' => 1,
'real_filename' => $filedata['real_filename'],
'attach_comment'=> $this->filename_data['filecomment'],
);
$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
$this->filename_data['filecomment'] = '';
}
}
else
{
$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
}
}
}
foreach ($error as $error_msg)
{
$this->warn_msg[] = $error_msg;
}
}
/**
* Get Attachment Data
*/
function get_submitted_attachment_data($check_user_id = false)
{
global $user, $db, $phpbb_root_path, $phpEx, $config;
$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
$attachment_data = (isset($_POST['attachment_data'])) ? $_POST['attachment_data'] : array();
$this->attachment_data = array();
$check_user_id = ($check_user_id === false) ? $user->data['user_id'] : $check_user_id;
if (!sizeof($attachment_data))
{
return;
}
$not_orphan = $orphan = array();
foreach ($attachment_data as $pos => $var_ary)
{
if ($var_ary['is_orphan'])
{
$orphan[(int) $var_ary['attach_id']] = $pos;
}
else
{
$not_orphan[(int) $var_ary['attach_id']] = $pos;
}
}
// Regenerate already posted attachments
if (sizeof($not_orphan))
{
// Get the attachment data, based on the poster id...
$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
FROM ' . ATTACHMENTS_TABLE . '
WHERE ' . $db->sql_in_set('attach_id', array_keys($not_orphan)) . '
AND poster_id = ' . $check_user_id;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$pos = $not_orphan[$row['attach_id']];
$this->attachment_data[$pos] = $row;
set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
unset($not_orphan[$row['attach_id']]);
}
$db->sql_freeresult($result);
}
if (sizeof($not_orphan))
{
trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
}
// Regenerate newly uploaded attachments
if (sizeof($orphan))
{
$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
FROM ' . ATTACHMENTS_TABLE . '
WHERE ' . $db->sql_in_set('attach_id', array_keys($orphan)) . '
AND poster_id = ' . $user->data['user_id'] . '
AND is_orphan = 1';
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$pos = $orphan[$row['attach_id']];
$this->attachment_data[$pos] = $row;
set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
unset($orphan[$row['attach_id']]);
}
$db->sql_freeresult($result);
}
if (sizeof($orphan))
{
trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
}
ksort($this->attachment_data);
}
/**
* Parse Poll
*/
function parse_poll(&$poll)
{
global $auth, $user, $config;
$poll_max_options = $poll['poll_max_options'];
// Parse Poll Option text ;)
$tmp_message = $this->message;
$this->message = $poll['poll_option_text'];
$bbcode_bitfield = $this->bbcode_bitfield;
$poll['poll_option_text'] = $this->parse($poll['enable_bbcode'], ($config['allow_post_links']) ? $poll['enable_urls'] : false, $poll['enable_smilies'], $poll['img_status'], false, false, $config['allow_post_links'], false);
$bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
$this->message = $tmp_message;
// Parse Poll Title
$tmp_message = $this->message;
$this->message = $poll['poll_title'];
$this->bbcode_bitfield = $bbcode_bitfield;
$poll['poll_options'] = explode("\n", trim($poll['poll_option_text']));
$poll['poll_options_size'] = sizeof($poll['poll_options']);
if (!$poll['poll_title'] && $poll['poll_options_size'])
{
$this->warn_msg[] = $user->lang['NO_POLL_TITLE'];
}
else
{
if (utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message)) > 100)
{
$this->warn_msg[] = $user->lang['POLL_TITLE_TOO_LONG'];
}
$poll['poll_title'] = $this->parse($poll['enable_bbcode'], ($config['allow_post_links']) ? $poll['enable_urls'] : false, $poll['enable_smilies'], $poll['img_status'], false, false, $config['allow_post_links'], false);
if (strlen($poll['poll_title']) > 255)
{
$this->warn_msg[] = $user->lang['POLL_TITLE_COMP_TOO_LONG'];
}
}
$this->bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
$this->message = $tmp_message;
unset($tmp_message);
if (sizeof($poll['poll_options']) == 1)
{
$this->warn_msg[] = $user->lang['TOO_FEW_POLL_OPTIONS'];
}
else if ($poll['poll_options_size'] > (int) $config['max_poll_options'])
{
$this->warn_msg[] = $user->lang['TOO_MANY_POLL_OPTIONS'];
}
else if ($poll_max_options > $poll['poll_options_size'])
{
$this->warn_msg[] = $user->lang['TOO_MANY_USER_OPTIONS'];
}
$poll['poll_max_options'] = ($poll['poll_max_options'] < 1) ? 1 : (($poll['poll_max_options'] > $config['max_poll_options']) ? $config['max_poll_options'] : $poll['poll_max_options']);
}
}
?>f='#n1312'>1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
exit;
}
/**
* Obtain user_ids from usernames or vice versa. Returns false on
* success else the error string
*
* @param array &$user_id_ary The user ids to check or empty if usernames used
* @param array &$username_ary The usernames to check or empty if user ids used
* @param mixed $user_type Array of user types to check, false if not restricting by user type
*/
function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
{
global $db;
// Are both arrays already filled? Yep, return else
// are neither array filled?
if ($user_id_ary && $username_ary)
{
return false;
}
else if (!$user_id_ary && !$username_ary)
{
return 'NO_USERS';
}
$which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
if ($$which_ary && !is_array($$which_ary))
{
$$which_ary = array($$which_ary);
}
$sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
unset($$which_ary);
$user_id_ary = $username_ary = array();
// Grab the user id/username records
$sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
$sql = 'SELECT user_id, username
FROM ' . USERS_TABLE . '
WHERE ' . $db->sql_in_set($sql_where, $sql_in);
if ($user_type !== false && !empty($user_type))
{
$sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
}
$result = $db->sql_query($sql);
if (!($row = $db->sql_fetchrow($result)))
{
$db->sql_freeresult($result);
return 'NO_USERS';
}
do
{
$username_ary[$row['user_id']] = $row['username'];
$user_id_ary[] = $row['user_id'];
}
while ($row = $db->sql_fetchrow($result));
$db->sql_freeresult($result);
return false;
}
/**
* Get latest registered username and update database to reflect it
*/
function update_last_username()
{
global $db;
// Get latest username
$sql = 'SELECT user_id, username, user_colour
FROM ' . USERS_TABLE . '
WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
ORDER BY user_id DESC';
$result = $db->sql_query_limit($sql, 1);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($row)
{
set_config('newest_user_id', $row['user_id'], true);
set_config('newest_username', $row['username'], true);
set_config('newest_user_colour', $row['user_colour'], true);
}
}
/**
* Updates a username across all relevant tables/fields
*
* @param string $old_name the old/current username
* @param string $new_name the new username
*/
function user_update_name($old_name, $new_name)
{
global $config, $db, $cache;
$update_ary = array(
FORUMS_TABLE => array('forum_last_poster_name'),
MODERATOR_CACHE_TABLE => array('username'),
POSTS_TABLE => array('post_username'),
TOPICS_TABLE => array('topic_first_poster_name', 'topic_last_poster_name'),
);
foreach ($update_ary as $table => $field_ary)
{
foreach ($field_ary as $field)
{
$sql = "UPDATE $table
SET $field = '" . $db->sql_escape($new_name) . "'
WHERE $field = '" . $db->sql_escape($old_name) . "'";
$db->sql_query($sql);
}
}
if ($config['newest_username'] == $old_name)
{
set_config('newest_username', $new_name, true);
}
// Because some tables/caches use username-specific data we need to purge this here.
$cache->destroy('sql', MODERATOR_CACHE_TABLE);
}
/**
* Adds an user
*
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
* @return the new user's ID.
*/
function user_add($user_row, $cp_data = false)
{
global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
{
return false;
}
$username_clean = utf8_clean_string($user_row['username']);
if (empty($username_clean))
{
return false;
}
$sql_ary = array(
'username' => $user_row['username'],
'username_clean' => $username_clean,
'user_password' => (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
'user_pass_convert' => 0,
'user_email' => strtolower($user_row['user_email']),
'user_email_hash' => phpbb_email_hash($user_row['user_email']),
'group_id' => $user_row['group_id'],
'user_type' => $user_row['user_type'],
);
// These are the additional vars able to be specified
$additional_vars = array(
'user_permissions' => '',
'user_timezone' => $config['board_timezone'],
'user_dateformat' => $config['default_dateformat'],
'user_lang' => $config['default_lang'],
'user_style' => (int) $config['default_style'],
'user_actkey' => '',
'user_ip' => '',
'user_regdate' => time(),
'user_passchg' => time(),
'user_options' => 230271,
// We do not set the new flag here - registration scripts need to specify it
'user_new' => 0,
'user_inactive_reason' => 0,
'user_inactive_time' => 0,
'user_lastmark' => time(),
'user_lastvisit' => 0,
'user_lastpost_time' => 0,
'user_lastpage' => '',
'user_posts' => 0,
'user_dst' => (int) $config['board_dst'],
'user_colour' => '',
'user_occ' => '',
'user_interests' => '',
'user_avatar' => '',
'user_avatar_type' => 0,
'user_avatar_width' => 0,
'user_avatar_height' => 0,
'user_new_privmsg' => 0,
'user_unread_privmsg' => 0,
'user_last_privmsg' => 0,
'user_message_rules' => 0,
'user_full_folder' => PRIVMSGS_NO_BOX,
'user_emailtime' => 0,
'user_notify' => 0,
'user_notify_pm' => 1,
'user_notify_type' => NOTIFY_EMAIL,
'user_allow_pm' => 1,
'user_allow_viewonline' => 1,
'user_allow_viewemail' => 1,
'user_allow_massemail' => 1,
'user_sig' => '',
'user_sig_bbcode_uid' => '',
'user_sig_bbcode_bitfield' => '',
'user_form_salt' => unique_id(),
);
// Now fill the sql array with not required variables
foreach ($additional_vars as $key => $default_value)
{
$sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
}
// Any additional variables in $user_row not covered above?
$remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
// Now fill our sql array with the remaining vars
if (sizeof($remaining_vars))
{
foreach ($remaining_vars as $key)
{
$sql_ary[$key] = $user_row[$key];
}
}
$sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
$db->sql_query($sql);
$user_id = $db->sql_nextid();
// Insert Custom Profile Fields
if ($cp_data !== false && sizeof($cp_data))
{
$cp_data['user_id'] = (int) $user_id;
if (!class_exists('custom_profile'))
{
include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
}
$sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
$db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
$db->sql_query($sql);
}
// Place into appropriate group...
$sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
'user_id' => (int) $user_id,
'group_id' => (int) $user_row['group_id'],
'user_pending' => 0)
);
$db->sql_query($sql);
// Now make it the users default group...
group_set_user_default($user_row['group_id'], array($user_id), false);
// Add to newly registered users group if user_new is 1
if ($config['new_member_post_limit'] && $sql_ary['user_new'])
{
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = 'NEWLY_REGISTERED'
AND group_type = " . GROUP_SPECIAL;
$result = $db->sql_query($sql);
$add_group_id = (int) $db->sql_fetchfield('group_id');
$db->sql_freeresult($result);
if ($add_group_id)
{
// Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
$GLOBALS['skip_add_log'] = true;
// Add user to "newly registered users" group and set to default group if admin specified so.
if ($config['new_member_group_default'])
{
group_user_add($add_group_id, $user_id, false, false, true);
$user_row['group_id'] = $add_group_id;
}
else
{
group_user_add($add_group_id, $user_id);
}
unset($GLOBALS['skip_add_log']);
}
}
// set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
{
set_config('newest_user_id', $user_id, true);
set_config('newest_username', $user_row['username'], true);
set_config_count('num_users', 1, true);
$sql = 'SELECT group_colour
FROM ' . GROUPS_TABLE . '
WHERE group_id = ' . (int) $user_row['group_id'];
$result = $db->sql_query_limit($sql, 1);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
set_config('newest_user_colour', $row['group_colour'], true);
}
return $user_id;
}
/**
* Remove User
*/
function user_delete($mode, $user_id, $post_username = false)
{
global $cache, $config, $db, $user, $auth;
global $phpbb_root_path, $phpEx;
$sql = 'SELECT *
FROM ' . USERS_TABLE . '
WHERE user_id = ' . $user_id;
$result = $db->sql_query($sql);
$user_row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$user_row)
{
return false;
}
// Before we begin, we will remove the reports the user issued.
$sql = 'SELECT r.post_id, p.topic_id
FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
WHERE r.user_id = ' . $user_id . '
AND p.post_id = r.post_id';
$result = $db->sql_query($sql);
$report_posts = $report_topics = array();
while ($row = $db->sql_fetchrow($result))
{
$report_posts[] = $row['post_id'];
$report_topics[] = $row['topic_id'];
}
$db->sql_freeresult($result);
if (sizeof($report_posts))
{
$report_posts = array_unique($report_posts);
$report_topics = array_unique($report_topics);
// Get a list of topics that still contain reported posts
$sql = 'SELECT DISTINCT topic_id
FROM ' . POSTS_TABLE . '
WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
AND post_reported = 1
AND ' . $db->sql_in_set('post_id', $report_posts, true);
$result = $db->sql_query($sql);
$keep_report_topics = array();
while ($row = $db->sql_fetchrow($result))
{
$keep_report_topics[] = $row['topic_id'];
}
$db->sql_freeresult($result);
if (sizeof($keep_report_topics))
{
$report_topics = array_diff($report_topics, $keep_report_topics);
}
unset($keep_report_topics);
// Now set the flags back
$sql = 'UPDATE ' . POSTS_TABLE . '
SET post_reported = 0
WHERE ' . $db->sql_in_set('post_id', $report_posts);
$db->sql_query($sql);
if (sizeof($report_topics))
{
$sql = 'UPDATE ' . TOPICS_TABLE . '
SET topic_reported = 0
WHERE ' . $db->sql_in_set('topic_id', $report_topics);
$db->sql_query($sql);
}
}
// Remove reports
$db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
{
avatar_delete('user', $user_row);
}
switch ($mode)
{
case 'retain':
$db->sql_transaction('begin');
if ($post_username === false)
{
$post_username = $user->lang['GUEST'];
}
// If the user is inactive and newly registered we assume no posts from this user being there...
if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
{
}
else
{
$sql = 'UPDATE ' . FORUMS_TABLE . '
SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
WHERE forum_last_poster_id = $user_id";
$db->sql_query($sql);
$sql = 'UPDATE ' . POSTS_TABLE . '
SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
WHERE poster_id = $user_id";
$db->sql_query($sql);
$sql = 'UPDATE ' . POSTS_TABLE . '
SET post_edit_user = ' . ANONYMOUS . "
WHERE post_edit_user = $user_id";
$db->sql_query($sql);
$sql = 'UPDATE ' . TOPICS_TABLE . '
SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
WHERE topic_poster = $user_id";
$db->sql_query($sql);
$sql = 'UPDATE ' . TOPICS_TABLE . '
SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
WHERE topic_last_poster_id = $user_id";
$db->sql_query($sql);
$sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
SET poster_id = ' . ANONYMOUS . "
WHERE poster_id = $user_id";
$db->sql_query($sql);
// Since we change every post by this author, we need to count this amount towards the anonymous user
// Update the post count for the anonymous user
if ($user_row['user_posts'])
{
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_posts = user_posts + ' . $user_row['user_posts'] . '
WHERE user_id = ' . ANONYMOUS;
$db->sql_query($sql);
}
}
$db->sql_transaction('commit');
break;
case 'remove':
if (!function_exists('delete_posts'))
{
include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
}
// Delete posts, attachments, etc.
delete_posts('poster_id', $user_id);
break;
}
$db->sql_transaction('begin');
$table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
foreach ($table_ary as $table)
{
$sql = "DELETE FROM $table
WHERE user_id = $user_id";
$db->sql_query($sql);
}
$cache->destroy('sql', MODERATOR_CACHE_TABLE);
// Delete user log entries about this user
$sql = 'DELETE FROM ' . LOG_TABLE . '
WHERE reportee_id = ' . $user_id;
$db->sql_query($sql);
// Change user_id to anonymous for this users triggered events
$sql = 'UPDATE ' . LOG_TABLE . '
SET user_id = ' . ANONYMOUS . '
WHERE user_id = ' . $user_id;
$db->sql_query($sql);
// Delete the user_id from the zebra table
$sql = 'DELETE FROM ' . ZEBRA_TABLE . '
WHERE user_id = ' . $user_id . '
OR zebra_id = ' . $user_id;
$db->sql_query($sql);
// Delete the user_id from the banlist
$sql = 'DELETE FROM ' . BANLIST_TABLE . '
WHERE ban_userid = ' . $user_id;
$db->sql_query($sql);
// Delete the user_id from the session table
$sql = 'DELETE FROM ' . SESSIONS_TABLE . '
WHERE session_user_id = ' . $user_id;
$db->sql_query($sql);
// Remove any undelivered mails...
$sql = 'SELECT msg_id, user_id
FROM ' . PRIVMSGS_TO_TABLE . '
WHERE author_id = ' . $user_id . '
AND folder_id = ' . PRIVMSGS_NO_BOX;
$result = $db->sql_query($sql);
$undelivered_msg = $undelivered_user = array();
while ($row = $db->sql_fetchrow($result))
{
$undelivered_msg[] = $row['msg_id'];
$undelivered_user[$row['user_id']][] = true;
}
$db->sql_freeresult($result);
if (sizeof($undelivered_msg))
{
$sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
$db->sql_query($sql);
}
$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
WHERE author_id = ' . $user_id . '
AND folder_id = ' . PRIVMSGS_NO_BOX;
$db->sql_query($sql);
// Delete all to-information
$sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
WHERE user_id = ' . $user_id;
$db->sql_query($sql);
// Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
$sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
SET author_id = ' . ANONYMOUS . '
WHERE author_id = ' . $user_id;
$db->sql_query($sql);
$sql = 'UPDATE ' . PRIVMSGS_TABLE . '
SET author_id = ' . ANONYMOUS . '
WHERE author_id = ' . $user_id;
$db->sql_query($sql);
foreach ($undelivered_user as $_user_id => $ary)
{
if ($_user_id == $user_id)
{
continue;
}
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
WHERE user_id = ' . $_user_id;
$db->sql_query($sql);
}
$db->sql_transaction('commit');
// Reset newest user info if appropriate
if ($config['newest_user_id'] == $user_id)
{
update_last_username();
}
// Decrement number of users if this user is active
if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
{
set_config_count('num_users', -1, true);
}
return false;
}
/**
* Flips user_type from active to inactive and vice versa, handles group membership updates
*
* @param string $mode can be flip for flipping from active/inactive, activate or deactivate
*/
function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
{
global $config, $db, $user, $auth;
$deactivated = $activated = 0;
$sql_statements = array();
if (!is_array($user_id_ary))
{
$user_id_ary = array($user_id_ary);
}
if (!sizeof($user_id_ary))
{
return;
}
$sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
FROM ' . USERS_TABLE . '
WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$sql_ary = array();
if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
{
continue;
}
if ($row['user_type'] == USER_INACTIVE)
{
$activated++;
}
else
{
$deactivated++;
// Remove the users session key...
$user->reset_login_keys($row['user_id']);
}
$sql_ary += array(
'user_type' => ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
'user_inactive_time' => ($row['user_type'] == USER_NORMAL) ? time() : 0,
'user_inactive_reason' => ($row['user_type'] == USER_NORMAL) ? $reason : 0,
);
$sql_statements[$row['user_id']] = $sql_ary;
}
$db->sql_freeresult($result);
if (sizeof($sql_statements))
{
foreach ($sql_statements as $user_id => $sql_ary)
{
$sql = 'UPDATE ' . USERS_TABLE . '
SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
WHERE user_id = ' . $user_id;
$db->sql_query($sql);
}
$auth->acl_clear_prefetch(array_keys($sql_statements));
}
if ($deactivated)
{
set_config_count('num_users', $deactivated * (-1), true);
}
if ($activated)
{
set_config_count('num_users', $activated, true);
}
// Update latest username
update_last_username();
}
/**
* Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
*
* @param string $mode Type of ban. One of the following: user, ip, email
* @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
* @param int $ban_len Ban length in minutes
* @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
* @param boolean $ban_exclude Exclude these entities from banning?
* @param string $ban_reason String describing the reason for this ban
* @return boolean
*/
function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
{
global $db, $user, $auth, $cache;
// Delete stale bans
$sql = 'DELETE FROM ' . BANLIST_TABLE . '
WHERE ban_end < ' . time() . '
AND ban_end <> 0';
$db->sql_query($sql);
$ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
$ban_list_log = implode(', ', $ban_list);
$current_time = time();
// Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
if ($ban_len)
{
if ($ban_len != -1 || !$ban_len_other)
{
$ban_end = max($current_time, $current_time + ($ban_len) * 60);
}
else
{
$ban_other = explode('-', $ban_len_other);
if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
(strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
{
$time_offset = (isset($user->timezone) && isset($user->dst)) ? (int) $user->timezone + (int) $user->dst : 0;
$ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]) - $time_offset);
}
else
{
trigger_error('LENGTH_BAN_INVALID', E_USER_WARNING);
}
}
}
else
{
$ban_end = 0;
}
$founder = $founder_names = array();
if (!$ban_exclude)
{
// Create a list of founder...
$sql = 'SELECT user_id, user_email, username_clean
FROM ' . USERS_TABLE . '
WHERE user_type = ' . USER_FOUNDER;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$founder[$row['user_id']] = $row['user_email'];
$founder_names[$row['user_id']] = $row['username_clean'];
}
$db->sql_freeresult($result);
}
$banlist_ary = array();
switch ($mode)
{
case 'user':
$type = 'ban_userid';
// At the moment we do not support wildcard username banning
// Select the relevant user_ids.
$sql_usernames = array();
foreach ($ban_list as $username)
{
$username = trim($username);
if ($username != '')
{
$clean_name = utf8_clean_string($username);
if ($clean_name == $user->data['username_clean'])
{
trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
}
if (in_array($clean_name, $founder_names))
{
trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
}
$sql_usernames[] = $clean_name;
}
}
// Make sure we have been given someone to ban
if (!sizeof($sql_usernames))
{
trigger_error('NO_USER_SPECIFIED', E_USER_WARNING);
}
$sql = 'SELECT user_id
FROM ' . USERS_TABLE . '
WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
// Do not allow banning yourself, the guest account, or founders.
$non_bannable = array($user->data['user_id'], ANONYMOUS);
if (sizeof($founder))
{
$sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), $non_bannable), true);
}
else
{
$sql .= ' AND ' . $db->sql_in_set('user_id', $non_bannable, true);
}
$result = $db->sql_query($sql);
if ($row = $db->sql_fetchrow($result))
{
do
{
$banlist_ary[] = (int) $row['user_id'];
}
while ($row = $db->sql_fetchrow($result));
}
else
{
$db->sql_freeresult($result);
trigger_error('NO_USERS', E_USER_WARNING);
}
$db->sql_freeresult($result);
break;
case 'ip':
$type = 'ban_ip';
foreach ($ban_list as $ban_item)
{
if (preg_match('#^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$#', trim($ban_item), $ip_range_explode))
{
// This is an IP range
// Don't ask about all this, just don't ask ... !
$ip_1_counter = $ip_range_explode[1];
$ip_1_end = $ip_range_explode[5];
while ($ip_1_counter <= $ip_1_end)
{
$ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
$ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
if ($ip_2_counter == 0 && $ip_2_end == 254)
{
$ip_2_counter = 256;
$ip_2_fragment = 256;
$banlist_ary[] = "$ip_1_counter.*";
}
while ($ip_2_counter <= $ip_2_end)
{
$ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
$ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
if ($ip_3_counter == 0 && $ip_3_end == 254)
{
$ip_3_counter = 256;
$ip_3_fragment = 256;
$banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
}
while ($ip_3_counter <= $ip_3_end)
{
$ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
$ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
if ($ip_4_counter == 0 && $ip_4_end == 254)
{
$ip_4_counter = 256;
$ip_4_fragment = 256;
$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
}
while ($ip_4_counter <= $ip_4_end)
{
$banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
$ip_4_counter++;
}
$ip_3_counter++;
}
$ip_2_counter++;
}
$ip_1_counter++;
}
}
else if (preg_match('#^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$#', trim($ban_item)) || preg_match('#^[a-f0-9:]+\*?$#i', trim($ban_item)))
{
// Normal IP address
$banlist_ary[] = trim($ban_item);
}
else if (preg_match('#^\*$#', trim($ban_item)))
{
// Ban all IPs
$banlist_ary[] = '*';
}
else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
{
// hostname
$ip_ary = gethostbynamel(trim($ban_item));
if (!empty($ip_ary))
{
foreach ($ip_ary as $ip)
{
if ($ip)
{
if (strlen($ip) > 40)
{
continue;
}
$banlist_ary[] = $ip;
}
}
}
}
if (empty($banlist_ary))
{
trigger_error('NO_IPS_DEFINED', E_USER_WARNING);
}
}
break;
case 'email':
$type = 'ban_email';
foreach ($ban_list as $ban_item)
{
$ban_item = trim($ban_item);
if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
{
if (strlen($ban_item) > 100)
{
continue;
}
if (!sizeof($founder) || !in_array($ban_item, $founder))
{
$banlist_ary[] = $ban_item;
}
}
}
if (sizeof($ban_list) == 0)
{
trigger_error('NO_EMAILS_DEFINED', E_USER_WARNING);
}
break;
default:
trigger_error('NO_MODE', E_USER_WARNING);
break;
}
// Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
$sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
$sql = "SELECT $type
FROM " . BANLIST_TABLE . "
WHERE $sql_where
AND ban_exclude = " . (int) $ban_exclude;
$result = $db->sql_query($sql);
// Reset $sql_where, because we use it later...
$sql_where = '';
if ($row = $db->sql_fetchrow($result))
{
$banlist_ary_tmp = array();
do
{
switch ($mode)
{
case 'user':
$banlist_ary_tmp[] = $row['ban_userid'];
break;
case 'ip':
$banlist_ary_tmp[] = $row['ban_ip'];
break;
case 'email':
$banlist_ary_tmp[] = $row['ban_email'];
break;
}
}
while ($row = $db->sql_fetchrow($result));
$banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
if (sizeof($banlist_ary_tmp))
{
// One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
$sql = 'DELETE FROM ' . BANLIST_TABLE . '
WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
AND ban_exclude = ' . (int) $ban_exclude;
$db->sql_query($sql);
}
unset($banlist_ary_tmp);
}
$db->sql_freeresult($result);
// We have some entities to ban
if (sizeof($banlist_ary))
{
$sql_ary = array();
foreach ($banlist_ary as $ban_entry)
{
$sql_ary[] = array(
$type => $ban_entry,
'ban_start' => (int) $current_time,
'ban_end' => (int) $ban_end,
'ban_exclude' => (int) $ban_exclude,
'ban_reason' => (string) $ban_reason,
'ban_give_reason' => (string) $ban_give_reason,
);
}
$db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
// If we are banning we want to logout anyone matching the ban
if (!$ban_exclude)
{
switch ($mode)
{
case 'user':
$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
break;
case 'ip':
$sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
break;
case 'email':
$banlist_ary_sql = array();
foreach ($banlist_ary as $ban_entry)
{
$banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
}
$sql = 'SELECT user_id
FROM ' . USERS_TABLE . '
WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
$result = $db->sql_query($sql);
$sql_in = array();
if ($row = $db->sql_fetchrow($result))
{
do
{
$sql_in[] = $row['user_id'];
}
while ($row = $db->sql_fetchrow($result));
$sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
}
$db->sql_freeresult($result);
break;
}
if (isset($sql_where) && $sql_where)
{
$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
$sql_where";
$db->sql_query($sql);
if ($mode == 'user')
{
$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
$db->sql_query($sql);
}
}
}
// Update log
$log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
// Add to moderator log, admin log and user notes
add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
if ($mode == 'user')
{
foreach ($banlist_ary as $user_id)
{
add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
}
}
$cache->destroy('sql', BANLIST_TABLE);
return true;
}
// There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
$cache->destroy('sql', BANLIST_TABLE);
return false;
}
/**
* Unban User
*/
function user_unban($mode, $ban)
{
global $db, $user, $auth, $cache;
// Delete stale bans
$sql = 'DELETE FROM ' . BANLIST_TABLE . '
WHERE ban_end < ' . time() . '
AND ban_end <> 0';
$db->sql_query($sql);
if (!is_array($ban))
{
$ban = array($ban);
}
$unban_sql = array_map('intval', $ban);
if (sizeof($unban_sql))
{
// Grab details of bans for logging information later
switch ($mode)
{
case 'user':
$sql = 'SELECT u.username AS unban_info, u.user_id
FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
AND u.user_id = b.ban_userid';
break;
case 'email':
$sql = 'SELECT ban_email AS unban_info
FROM ' . BANLIST_TABLE . '
WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
break;
case 'ip':
$sql = 'SELECT ban_ip AS unban_info
FROM ' . BANLIST_TABLE . '
WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
break;
}
$result = $db->sql_query($sql);
$l_unban_list = '';
$user_ids_ary = array();
while ($row = $db->sql_fetchrow($result))
{
$l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
if ($mode == 'user')
{
$user_ids_ary[] = $row['user_id'];
}
}
$db->sql_freeresult($result);
$sql = 'DELETE FROM ' . BANLIST_TABLE . '
WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
$db->sql_query($sql);
// Add to moderator log, admin log and user notes
add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
if ($mode == 'user')
{
foreach ($user_ids_ary as $user_id)
{
add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
}
}
}
$cache->destroy('sql', BANLIST_TABLE);
return false;
}
/**
* Internet Protocol Address Whois
* RFC3912: WHOIS Protocol Specification
*
* @param string $ip Ip address, either IPv4 or IPv6.
*
* @return string Empty string if not a valid ip address.
* Otherwise make_clickable()'ed whois result.
*/
function user_ipwhois($ip)
{
if (empty($ip))
{
return '';
}
if (preg_match(get_preg_expression('ipv4'), $ip))
{
// IPv4 address
$whois_host = 'whois.arin.net.';
}
else if (preg_match(get_preg_expression('ipv6'), $ip))
{
// IPv6 address
$whois_host = 'whois.sixxs.net.';
}
else
{
return '';
}
$ipwhois = '';
if (($fsk = @fsockopen($whois_host, 43)))
{
// CRLF as per RFC3912
fputs($fsk, "$ip\r\n");
while (!feof($fsk))
{
$ipwhois .= fgets($fsk, 1024);
}
@fclose($fsk);
}
$match = array();
// Test for referrals from $whois_host to other whois databases, roll on rwhois
if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
{
if (strpos($match[1], ':') !== false)
{
$pos = strrpos($match[1], ':');
$server = substr($match[1], 0, $pos);
$port = (int) substr($match[1], $pos + 1);
unset($pos);
}
else
{
$server = $match[1];
$port = 43;
}
$buffer = '';
if (($fsk = @fsockopen($server, $port)))
{
fputs($fsk, "$ip\r\n");
while (!feof($fsk))
{
$buffer .= fgets($fsk, 1024);
}
@fclose($fsk);
}
// Use the result from $whois_host if we don't get any result here
$ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
}
$ipwhois = htmlspecialchars($ipwhois);
// Magic URL ;)
return trim(make_clickable($ipwhois, false, ''));
}
/**
* Data validation ... used primarily but not exclusively by ucp modules
*
* "Master" function for validating a range of data types
*/
function validate_data($data, $val_ary)
{
global $user;
$error = array();
foreach ($val_ary as $var => $val_seq)
{
if (!is_array($val_seq[0]))
{
$val_seq = array($val_seq);
}
foreach ($val_seq as $validate)
{
$function = array_shift($validate);
array_unshift($validate, $data[$var]);
if ($result = call_user_func_array('validate_' . $function, $validate))
{
// Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
$error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
}
}
}
return $error;
}
/**
* Validate String
*
* @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_string($string, $optional = false, $min = 0, $max = 0)
{
if (empty($string) && $optional)
{
return false;
}
if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
{
return 'TOO_SHORT';
}
else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
{
return 'TOO_LONG';
}
return false;
}
/**
* Validate Number
*
* @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_num($num, $optional = false, $min = 0, $max = 1E99)
{
if (empty($num) && $optional)
{
return false;
}
if ($num < $min)
{
return 'TOO_SMALL';
}
else if ($num > $max)
{
return 'TOO_LARGE';
}
return false;
}
/**
* Validate Date
* @param String $string a date in the dd-mm-yyyy format
* @return boolean
*/
function validate_date($date_string, $optional = false)
{
$date = explode('-', $date_string);
if ((empty($date) || sizeof($date) != 3) && $optional)
{
return false;
}
else if ($optional)
{
for ($field = 0; $field <= 1; $field++)
{
$date[$field] = (int) $date[$field];
if (empty($date[$field]))
{
$date[$field] = 1;
}
}
$date[2] = (int) $date[2];
// assume an arbitrary leap year
if (empty($date[2]))
{
$date[2] = 1980;
}
}
if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
{
return 'INVALID';
}
return false;
}
/**
* Validate Match
*
* @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_match($string, $optional = false, $match = '')
{
if (empty($string) && $optional)
{
return false;
}
if (empty($match))
{
return false;
}
if (!preg_match($match, $string))
{
return 'WRONG_DATA';
}
return false;
}
/**
* Validate Language Pack ISO Name
*
* Tests whether a language name is valid and installed
*
* @param string $lang_iso The language string to test
*
* @return bool|string Either false if validation succeeded or
* a string which will be used as the error message
* (with the variable name appended)
*/
function validate_language_iso_name($lang_iso)
{
global $db;
$sql = 'SELECT lang_id
FROM ' . LANG_TABLE . "
WHERE lang_iso = '" . $db->sql_escape($lang_iso) . "'";
$result = $db->sql_query($sql);
$lang_id = (int) $db->sql_fetchfield('lang_id');
$db->sql_freeresult($result);
return ($lang_id) ? false : 'WRONG_DATA';
}
/**
* Check to see if the username has been taken, or if it is disallowed.
* Also checks if it includes the " character, which we don't allow in usernames.
* Used for registering, changing names, and posting anonymously with a username
*
* @param string $username The username to check
* @param string $allowed_username An allowed username, default being $user->data['username']
*
* @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_username($username, $allowed_username = false)
{
global $config, $db, $user, $cache;
$clean_username = utf8_clean_string($username);
$allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
if ($allowed_username == $clean_username)
{
return false;
}
// ... fast checks first.
if (strpos($username, '"') !== false || strpos($username, '"') !== false || empty($clean_username))
{
return 'INVALID_CHARS';
}
$mbstring = $pcre = false;
// generic UTF-8 character types supported?
if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
{
$pcre = true;
}
else if (function_exists('mb_ereg_match'))
{
mb_regex_encoding('UTF-8');
$mbstring = true;
}
switch ($config['allow_name_chars'])
{
case 'USERNAME_CHARS_ANY':
$pcre = true;
$regex = '.+';
break;
case 'USERNAME_ALPHA_ONLY':
$pcre = true;
$regex = '[A-Za-z0-9]+';
break;
case 'USERNAME_ALPHA_SPACERS':
$pcre = true;
$regex = '[A-Za-z0-9-[\]_+ ]+';
break;
case 'USERNAME_LETTER_NUM':
if ($pcre)
{
$regex = '[\p{Lu}\p{Ll}\p{N}]+';
}
else if ($mbstring)
{
$regex = '[[:upper:][:lower:][:digit:]]+';
}
else
{
$pcre = true;
$regex = '[a-zA-Z0-9]+';
}
break;
case 'USERNAME_LETTER_NUM_SPACERS':
if ($pcre)
{
$regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
}
else if ($mbstring)
{
$regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
}
else
{
$pcre = true;
$regex = '[-\]_+ [a-zA-Z0-9]+';
}
break;
case 'USERNAME_ASCII':
default:
$pcre = true;
$regex = '[\x01-\x7F]+';
break;
}
if ($pcre)
{
if (!preg_match('#^' . $regex . '$#u', $username))
{
return 'INVALID_CHARS';
}
}
else if ($mbstring)
{
mb_ereg_search_init($username, '^' . $regex . '$');
if (!mb_ereg_search())
{
return 'INVALID_CHARS';
}
}
$sql = 'SELECT username
FROM ' . USERS_TABLE . "
WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($row)
{
return 'USERNAME_TAKEN';
}
$sql = 'SELECT group_name
FROM ' . GROUPS_TABLE . "
WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($row)
{
return 'USERNAME_TAKEN';
}
$bad_usernames = $cache->obtain_disallowed_usernames();
foreach ($bad_usernames as $bad_username)
{
if (preg_match('#^' . $bad_username . '$#', $clean_username))
{
return 'USERNAME_DISALLOWED';
}
}
return false;
}
/**
* Check to see if the password meets the complexity settings
*
* @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_password($password)
{
global $config, $db, $user;
if ($password === '' || $config['pass_complex'] === 'PASS_TYPE_ANY')
{
// Password empty or no password complexity required.
return false;
}
$pcre = $mbstring = false;
// generic UTF-8 character types supported?
if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
{
$upp = '\p{Lu}';
$low = '\p{Ll}';
$num = '\p{N}';
$sym = '[^\p{Lu}\p{Ll}\p{N}]';
$pcre = true;
}
else if (function_exists('mb_ereg_match'))
{
mb_regex_encoding('UTF-8');
$upp = '[[:upper:]]';
$low = '[[:lower:]]';
$num = '[[:digit:]]';
$sym = '[^[:upper:][:lower:][:digit:]]';
$mbstring = true;
}
else
{
$upp = '[A-Z]';
$low = '[a-z]';
$num = '[0-9]';
$sym = '[^A-Za-z0-9]';
$pcre = true;
}
$chars = array();
switch ($config['pass_complex'])
{
// No break statements below ...
// We require strong passwords in case pass_complex is not set or is invalid
default:
// Require mixed case letters, numbers and symbols
case 'PASS_TYPE_SYMBOL':
$chars[] = $sym;
// Require mixed case letters and numbers
case 'PASS_TYPE_ALPHA':
$chars[] = $num;
// Require mixed case letters
case 'PASS_TYPE_CASE':
$chars[] = $low;
$chars[] = $upp;
}
if ($pcre)
{
foreach ($chars as $char)
{
if (!preg_match('#' . $char . '#u', $password))
{
return 'INVALID_CHARS';
}
}
}
else if ($mbstring)
{
foreach ($chars as $char)
{
if (mb_ereg($char, $password) === false)
{
return 'INVALID_CHARS';
}
}
}
return false;
}
/**
* Check to see if email address is banned or already present in the DB
*
* @param string $email The email to check
* @param string $allowed_email An allowed email, default being $user->data['user_email']
*
* @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function validate_email($email, $allowed_email = false)
{
global $config, $db, $user;
$email = strtolower($email);
$allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
if ($allowed_email == $email)
{
return false;
}
if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
{
return 'EMAIL_INVALID';
}
// Check MX record.
// The idea for this is from reading the UseBB blog/announcement. :)
if ($config['email_check_mx'])
{
list(, $domain) = explode('@', $email);
if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
{
return 'DOMAIN_NO_MX_RECORD';
}
}
if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
{
return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
}
if (!$config['allow_emailreuse'])
{
$sql = 'SELECT user_email_hash
FROM ' . USERS_TABLE . "
WHERE user_email_hash = " . $db->sql_escape(phpbb_email_hash($email));
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if ($row)
{
return 'EMAIL_TAKEN';
}
}
return false;
}
/**
* Validate jabber address
* Taken from the jabber class within flyspray (see author notes)
*
* @author flyspray.org
*/
function validate_jabber($jid)
{
if (!$jid)
{
return false;
}
$seperator_pos = strpos($jid, '@');
if ($seperator_pos === false)
{
return 'WRONG_DATA';
}
$username = substr($jid, 0, $seperator_pos);
$realm = substr($jid, $seperator_pos + 1);
if (strlen($username) == 0 || strlen($realm) < 3)
{
return 'WRONG_DATA';
}
$arr = explode('.', $realm);
if (sizeof($arr) == 0)
{
return 'WRONG_DATA';
}
foreach ($arr as $part)
{
if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
{
return 'WRONG_DATA';
}
if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
{
return 'WRONG_DATA';
}
}
$boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
// Prohibited Characters RFC3454 + RFC3920
$prohibited = array(
// Table C.1.1
array(0x0020, 0x0020), // SPACE
// Table C.1.2
array(0x00A0, 0x00A0), // NO-BREAK SPACE
array(0x1680, 0x1680), // OGHAM SPACE MARK
array(0x2000, 0x2001), // EN QUAD
array(0x2001, 0x2001), // EM QUAD
array(0x2002, 0x2002), // EN SPACE
array(0x2003, 0x2003), // EM SPACE
array(0x2004, 0x2004), // THREE-PER-EM SPACE
array(0x2005, 0x2005), // FOUR-PER-EM SPACE
array(0x2006, 0x2006), // SIX-PER-EM SPACE
array(0x2007, 0x2007), // FIGURE SPACE
array(0x2008, 0x2008), // PUNCTUATION SPACE
array(0x2009, 0x2009), // THIN SPACE
array(0x200A, 0x200A), // HAIR SPACE
array(0x200B, 0x200B), // ZERO WIDTH SPACE
array(0x202F, 0x202F), // NARROW NO-BREAK SPACE
array(0x205F, 0x205F), // MEDIUM MATHEMATICAL SPACE
array(0x3000, 0x3000), // IDEOGRAPHIC SPACE
// Table C.2.1
array(0x0000, 0x001F), // [CONTROL CHARACTERS]
array(0x007F, 0x007F), // DELETE
// Table C.2.2
array(0x0080, 0x009F), // [CONTROL CHARACTERS]
array(0x06DD, 0x06DD), // ARABIC END OF AYAH
array(0x070F, 0x070F), // SYRIAC ABBREVIATION MARK
array(0x180E, 0x180E), // MONGOLIAN VOWEL SEPARATOR
array(0x200C, 0x200C), // ZERO WIDTH NON-JOINER
array(0x200D, 0x200D), // ZERO WIDTH JOINER
array(0x2028, 0x2028), // LINE SEPARATOR
array(0x2029, 0x2029), // PARAGRAPH SEPARATOR
array(0x2060, 0x2060), // WORD JOINER
array(0x2061, 0x2061), // FUNCTION APPLICATION
array(0x2062, 0x2062), // INVISIBLE TIMES
array(0x2063, 0x2063), // INVISIBLE SEPARATOR
array(0x206A, 0x206F), // [CONTROL CHARACTERS]
array(0xFEFF, 0xFEFF), // ZERO WIDTH NO-BREAK SPACE
array(0xFFF9, 0xFFFC), // [CONTROL CHARACTERS]
array(0x1D173, 0x1D17A), // [MUSICAL CONTROL CHARACTERS]
// Table C.3
array(0xE000, 0xF8FF), // [PRIVATE USE, PLANE 0]
array(0xF0000, 0xFFFFD), // [PRIVATE USE, PLANE 15]
array(0x100000, 0x10FFFD), // [PRIVATE USE, PLANE 16]
// Table C.4
array(0xFDD0, 0xFDEF), // [NONCHARACTER CODE POINTS]
array(0xFFFE, 0xFFFF), // [NONCHARACTER CODE POINTS]
array(0x1FFFE, 0x1FFFF), // [NONCHARACTER CODE POINTS]
array(0x2FFFE, 0x2FFFF), // [NONCHARACTER CODE POINTS]
array(0x3FFFE, 0x3FFFF), // [NONCHARACTER CODE POINTS]
array(0x4FFFE, 0x4FFFF), // [NONCHARACTER CODE POINTS]
array(0x5FFFE, 0x5FFFF), // [NONCHARACTER CODE POINTS]
array(0x6FFFE, 0x6FFFF), // [NONCHARACTER CODE POINTS]
array(0x7FFFE, 0x7FFFF), // [NONCHARACTER CODE POINTS]
array(0x8FFFE, 0x8FFFF), // [NONCHARACTER CODE POINTS]
array(0x9FFFE, 0x9FFFF), // [NONCHARACTER CODE POINTS]
array(0xAFFFE, 0xAFFFF), // [NONCHARACTER CODE POINTS]
array(0xBFFFE, 0xBFFFF), // [NONCHARACTER CODE POINTS]
array(0xCFFFE, 0xCFFFF), // [NONCHARACTER CODE POINTS]
array(0xDFFFE, 0xDFFFF), // [NONCHARACTER CODE POINTS]
array(0xEFFFE, 0xEFFFF), // [NONCHARACTER CODE POINTS]
array(0xFFFFE, 0xFFFFF), // [NONCHARACTER CODE POINTS]
array(0x10FFFE, 0x10FFFF), // [NONCHARACTER CODE POINTS]
// Table C.5
array(0xD800, 0xDFFF), // [SURROGATE CODES]
// Table C.6
array(0xFFF9, 0xFFF9), // INTERLINEAR ANNOTATION ANCHOR
array(0xFFFA, 0xFFFA), // INTERLINEAR ANNOTATION SEPARATOR
array(0xFFFB, 0xFFFB), // INTERLINEAR ANNOTATION TERMINATOR
array(0xFFFC, 0xFFFC), // OBJECT REPLACEMENT CHARACTER
array(0xFFFD, 0xFFFD), // REPLACEMENT CHARACTER
// Table C.7
array(0x2FF0, 0x2FFB), // [IDEOGRAPHIC DESCRIPTION CHARACTERS]
// Table C.8
array(0x0340, 0x0340), // COMBINING GRAVE TONE MARK
array(0x0341, 0x0341), // COMBINING ACUTE TONE MARK
array(0x200E, 0x200E), // LEFT-TO-RIGHT MARK
array(0x200F, 0x200F), // RIGHT-TO-LEFT MARK
array(0x202A, 0x202A), // LEFT-TO-RIGHT EMBEDDING
array(0x202B, 0x202B), // RIGHT-TO-LEFT EMBEDDING
array(0x202C, 0x202C), // POP DIRECTIONAL FORMATTING
array(0x202D, 0x202D), // LEFT-TO-RIGHT OVERRIDE
array(0x202E, 0x202E), // RIGHT-TO-LEFT OVERRIDE
array(0x206A, 0x206A), // INHIBIT SYMMETRIC SWAPPING
array(0x206B, 0x206B), // ACTIVATE SYMMETRIC SWAPPING
array(0x206C, 0x206C), // INHIBIT ARABIC FORM SHAPING
array(0x206D, 0x206D), // ACTIVATE ARABIC FORM SHAPING
array(0x206E, 0x206E), // NATIONAL DIGIT SHAPES
array(0x206F, 0x206F), // NOMINAL DIGIT SHAPES
// Table C.9
array(0xE0001, 0xE0001), // LANGUAGE TAG
array(0xE0020, 0xE007F), // [TAGGING CHARACTERS]
// RFC3920
array(0x22, 0x22), // "
array(0x26, 0x26), // &
array(0x27, 0x27), // '
array(0x2F, 0x2F), // /
array(0x3A, 0x3A), // :
array(0x3C, 0x3C), // <
array(0x3E, 0x3E), // >
array(0x40, 0x40) // @
);
$pos = 0;
$result = true;
while ($pos < strlen($username))
{
$len = $uni = 0;
for ($i = 0; $i <= 5; $i++)
{
if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
{
$len = $i + 1;
$uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
for ($k = 1; $k < $len; $k++)
{
$uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
}
break;
}
}
if ($len == 0)
{
return 'WRONG_DATA';
}
foreach ($prohibited as $pval)
{
if ($uni >= $pval[0] && $uni <= $pval[1])
{
$result = false;
break 2;
}
}
$pos = $pos + $len;
}
if (!$result)
{
return 'WRONG_DATA';
}
return false;
}
/**
* Remove avatar
*/
function avatar_delete($mode, $row, $clean_db = false)
{
global $phpbb_root_path, $config, $db, $user;
// Check if the users avatar is actually *not* a group avatar
if ($mode == 'user')
{
if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
{
return false;
}
}
if ($clean_db)
{
avatar_remove_db($row[$mode . '_avatar']);
}
$filename = get_avatar_filename($row[$mode . '_avatar']);
if (file_exists($phpbb_root_path . $config['avatar_path'] . '/' . $filename))
{
@unlink($phpbb_root_path . $config['avatar_path'] . '/' . $filename);
return true;
}
return false;
}
/**
* Remote avatar linkage
*/
function avatar_remote($data, &$error)
{
global $config, $db, $user, $phpbb_root_path, $phpEx;
if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
{
$data['remotelink'] = 'http://' . $data['remotelink'];
}
if (!preg_match('#^(http|https|ftp)://(?:(.*?\.)*?[a-z0-9\-]+?\.[a-z]{2,4}|(?:\d{1,3}\.){3,5}\d{1,3}):?([0-9]*?).*?\.(gif|jpg|jpeg|png)$#i', $data['remotelink']))
{
$error[] = $user->lang['AVATAR_URL_INVALID'];
return false;
}
// Make sure getimagesize works...
if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
{
$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
return false;
}
if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
{
$error[] = $user->lang['AVATAR_NO_SIZE'];
return false;
}
$width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
$height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
if ($width < 2 || $height < 2)
{
$error[] = $user->lang['AVATAR_NO_SIZE'];
return false;
}
// Check image type
include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
$types = fileupload::image_types();
$extension = strtolower(filespec::get_extension($data['remotelink']));
if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
{
if (!isset($types[$image_data[2]]))
{
$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
}
else
{
$error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
}
return false;
}
if ($config['avatar_max_width'] || $config['avatar_max_height'])
{
if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
{
$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
return false;
}
}
if ($config['avatar_min_width'] || $config['avatar_min_height'])
{
if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
{
$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
return false;
}
}
return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
}
/**
* Avatar upload using the upload class
*/
function avatar_upload($data, &$error)
{
global $phpbb_root_path, $config, $db, $user, $phpEx;
// Init upload class
include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
$upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), $config['avatar_filesize'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], (isset($config['mime_triggers']) ? explode('|', $config['mime_triggers']) : false));
if (!empty($_FILES['uploadfile']['name']))
{
$file = $upload->form_upload('uploadfile');
}
else
{
$file = $upload->remote_upload($data['uploadurl']);
}
$prefix = $config['avatar_salt'] . '_';
$file->clean_filename('avatar', $prefix, $data['user_id']);
$destination = $config['avatar_path'];
// Adjust destination path (no trailing slash)
if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
{
$destination = substr($destination, 0, -1);
}
$destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
{
$destination = '';
}
// Move file and overwrite any existing image
$file->move_file($destination, true);
if (sizeof($file->error))
{
$file->remove();
$error = array_merge($error, $file->error);
}
return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
}
/**
* Generates avatar filename from the database entry
*/
function get_avatar_filename($avatar_entry)
{
global $config;
if ($avatar_entry[0] === 'g')
{
$avatar_group = true;
$avatar_entry = substr($avatar_entry, 1);
}
else
{
$avatar_group = false;
}
$ext = substr(strrchr($avatar_entry, '.'), 1);
$avatar_entry = intval($avatar_entry);
return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
}
/**
* Avatar Gallery
*/
function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
{
global $user, $cache, $template;
global $config, $phpbb_root_path;
$avatar_list = array();
$path = $phpbb_root_path . $config['avatar_gallery_path'];
if (!file_exists($path) || !is_dir($path))
{
$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
}
else
{
// Collect images
$dp = @opendir($path);
if (!$dp)
{
return array($user->lang['NO_AVATAR_CATEGORY'] => array());
}
while (($file = readdir($dp)) !== false)
{
if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
{
$avatar_row_count = $avatar_col_count = 0;
if ($dp2 = @opendir("$path/$file"))
{
while (($sub_file = readdir($dp2)) !== false)
{
if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
{
$avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
'file' => rawurlencode($file) . '/' . rawurlencode($sub_file),
'filename' => rawurlencode($sub_file),
'name' => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
);
$avatar_col_count++;
if ($avatar_col_count == $items_per_column)
{
$avatar_row_count++;
$avatar_col_count = 0;
}
}
}
closedir($dp2);
}
}
}
closedir($dp);
}
if (!sizeof($avatar_list))
{
$avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
}
@ksort($avatar_list);
$category = (!$category) ? key($avatar_list) : $category;
$avatar_categories = array_keys($avatar_list);
$s_category_options = '';
foreach ($avatar_categories as $cat)
{
$s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
}
$template->assign_vars(array(
'S_AVATARS_ENABLED' => true,
'S_IN_AVATAR_GALLERY' => true,
'S_CAT_OPTIONS' => $s_category_options)
);
$avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
foreach ($avatar_list as $avatar_row_ary)
{
$template->assign_block_vars($block_var, array());
foreach ($avatar_row_ary as $avatar_col_ary)
{
$template->assign_block_vars($block_var . '.avatar_column', array(
'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
'AVATAR_NAME' => $avatar_col_ary['name'],
'AVATAR_FILE' => $avatar_col_ary['filename'])
);
$template->assign_block_vars($block_var . '.avatar_option_column', array(
'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
'S_OPTIONS_AVATAR' => $avatar_col_ary['filename'])
);
}
}
return $avatar_list;
}
/**
* Tries to (re-)establish avatar dimensions
*/
function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
{
global $config, $phpbb_root_path, $user;
switch ($avatar_type)
{
case AVATAR_REMOTE :
break;
case AVATAR_UPLOAD :
$avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
break;
case AVATAR_GALLERY :
$avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
break;
}
// Make sure getimagesize works...
if (($image_data = @getimagesize($avatar)) === false)
{
$error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
return false;
}
if ($image_data[0] < 2 || $image_data[1] < 2)
{
$error[] = $user->lang['AVATAR_NO_SIZE'];
return false;
}
// try to maintain ratio
if (!(empty($current_x) && empty($current_y)))
{
if ($current_x != 0)
{
$image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
$image_data[1] = min($config['avatar_max_height'], $image_data[1]);
$image_data[1] = max($config['avatar_min_height'], $image_data[1]);
}
if ($current_y != 0)
{
$image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
$image_data[0] = min($config['avatar_max_width'], $image_data[1]);
$image_data[0] = max($config['avatar_min_width'], $image_data[1]);
}
}
return array($image_data[0], $image_data[1]);
}
/**
* Uploading/Changing user avatar
*/
function avatar_process_user(&$error, $custom_userdata = false, $can_upload = null)
{
global $config, $phpbb_root_path, $auth, $user, $db;
$data = array(
'uploadurl' => request_var('uploadurl', ''),
'remotelink' => request_var('remotelink', ''),
'width' => request_var('width', 0),
'height' => request_var('height', 0),
);
$error = validate_data($data, array(
'uploadurl' => array('string', true, 5, 255),
'remotelink' => array('string', true, 5, 255),
'width' => array('string', true, 1, 3),
'height' => array('string', true, 1, 3),
));
if (sizeof($error))
{
return false;
}
$sql_ary = array();
if ($custom_userdata === false)
{
$userdata = &$user->data;
}
else
{
$userdata = &$custom_userdata;
}
$data['user_id'] = $userdata['user_id'];
$change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
$avatar_select = basename(request_var('avatar_select', ''));
// Can we upload?
if (is_null($can_upload))
{
$can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && phpbb_is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
}
if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
{
list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
}
else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
{
list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
}
else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
{
$category = basename(request_var('category', ''));
$sql_ary['user_avatar_type'] = AVATAR_GALLERY;
$sql_ary['user_avatar'] = $avatar_select;
// check avatar gallery
if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
{
$sql_ary['user_avatar'] = '';
$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
}
else
{
list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . urldecode($sql_ary['user_avatar']));
$sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
}
}
else if (isset($_POST['delete']) && $change_avatar)
{
$sql_ary['user_avatar'] = '';
$sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
}
else if (!empty($userdata['user_avatar']))
{
// Only update the dimensions
if (empty($data['width']) || empty($data['height']))
{
if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
{
list($guessed_x, $guessed_y) = $dims;
if (empty($data['width']))
{
$data['width'] = $guessed_x;
}
if (empty($data['height']))
{
$data['height'] = $guessed_y;
}
}
}
if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
(($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
{
if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
{
$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
}
}
if (!sizeof($error))
{
if ($config['avatar_min_width'] || $config['avatar_min_height'])
{
if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
{
$error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
}
}
}
if (!sizeof($error))
{
$sql_ary['user_avatar_width'] = $data['width'];
$sql_ary['user_avatar_height'] = $data['height'];
}
}
if (!sizeof($error))
{
// Do we actually have any data to update?
if (sizeof($sql_ary))
{
$ext_new = $ext_old = '';
if (isset($sql_ary['user_avatar']))
{
$userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
$ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
$ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
{
// Delete old avatar if present
if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))