示例#1
0
 /**
  * {@inheritDoc}
  */
 public function validate_profile_field(&$field_value, $field_data)
 {
     $field_value = trim($field_value);
     if ($field_value === '' && !$field_data['field_required']) {
         return false;
     }
     if (!preg_match('#^' . get_preg_expression('url') . '$#iu', $field_value)) {
         return $this->user->lang('FIELD_INVALID_URL', $this->get_field_name($field_data['lang_name']));
     }
     return false;
 }
示例#2
0
function is_valid_flash_bbcode($cleaned_content, $uid)
{
    $regex = get_flash_regex($uid);
    $url_regex = get_preg_expression('url');
    $www_url_regex = get_preg_expression('www_url');
    if (preg_match_all($regex, $cleaned_content, $matches)) {
        foreach ($matches[3] as $flash_url) {
            if (!preg_match("#^({$url_regex}|{$www_url_regex})\$#i", $flash_url)) {
                return false;
            }
        }
    }
    return true;
}
示例#3
0
 /**
  * {inheritDoc}
  */
 public function submit(\messenger $messenger)
 {
     if (!$this->recipient_address || !preg_match('/^' . get_preg_expression('email') . '$/i', $this->recipient_address)) {
         $this->errors[] = $this->user->lang['EMPTY_ADDRESS_EMAIL'];
     }
     if (!$this->recipient_name) {
         $this->errors[] = $this->user->lang['EMPTY_NAME_EMAIL'];
     }
     $this->message->set_template('email_notify');
     $this->message->set_template_vars(array('TOPIC_NAME' => htmlspecialchars_decode($this->topic_row['topic_title']), 'U_TOPIC' => generate_srcrd_url() . '/viewtopic.' . $this->phpEx . '?f=' . $this->topic_row['forum_id'] . '&t=' . $this->topic_id));
     $this->message->set_body($this->body);
     $this->message->add_recipient($this->recipient_name, $this->recipient_address, $this->recipient_lang, NOTIFY_EMAIL);
     $this->message->set_sender_notify_type(NOTIFY_EMAIL);
     parent::submit($messenger);
 }
示例#4
0
function user_ipwhois($ip)
{
    $ipwhois = '';
    // Check IP
    // Only supporting IPv4 at the moment...
    if (empty($ip) || !preg_match(get_preg_expression('ipv4'), $ip)) {
        return '';
    }
    if ($fsk = @fsockopen('whois.arin.net', 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 ARIN 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 ARIN if we don't get any result here
        $ipwhois = empty($buffer) ? $ipwhois : $buffer;
    }
    return $ipwhois = htmlspecialchars($ipwhois);
}
 /**
  * Main ACP module
  *
  * @param int $id
  * @param string $mode
  * @return null
  * @access public
  */
 public function main($id, $mode)
 {
     $this->tpl_name = 'acp_teamsecurity';
     $this->page_title = $this->user->lang('ACP_TEAM_SECURITY_SETTINGS');
     // Only allow founders to view/manage these settings
     if ($this->user->data['user_type'] != USER_FOUNDER) {
         trigger_error($this->user->lang('ACP_FOUNDER_MANAGE_ONLY'), E_USER_WARNING);
     }
     $form_key = 'acp_teamsecurity';
     add_form_key($form_key);
     if ($this->request->is_set_post('submit')) {
         if (!check_form_key($form_key)) {
             trigger_error($this->user->lang('FORM_INVALID') . adm_back_link($this->u_action), E_USER_WARNING);
         }
         // Validate the email address submitted by the user
         $sec_contact = $this->request->variable('sec_contact', '');
         if ($sec_contact != '' && !preg_match('/^' . get_preg_expression('email') . '$/i', $sec_contact)) {
             trigger_error($this->user->lang('EMAIL_INVALID_EMAIL') . adm_back_link($this->u_action), E_USER_WARNING);
         }
         $this->config->set('sec_contact', $sec_contact);
         $this->config->set('sec_contact_name', $this->request->variable('sec_contact_name', '', true));
         $this->config->set('sec_login_email', $this->request->variable('sec_login_email', 0));
         $this->config->set('sec_login_attempts', $this->request->variable('sec_login_attempts', 0));
         $this->config->set('sec_email_changes', $this->request->variable('sec_email_changes', 0));
         $this->config->set('sec_strong_pass', $this->request->variable('sec_strong_pass', 0));
         $this->config->set('sec_min_pass_chars', $this->request->variable('sec_min_pass_chars', 0));
         $this->config->set('sec_usergroups', json_encode($this->request->variable('sec_usergroups', array(0))));
         $this->log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_TEAM_SEC_UPDATED');
         trigger_error($this->user->lang('CONFIG_UPDATED') . adm_back_link($this->u_action));
     }
     // Set template vars for usergroups multi-select box
     $group_id_ary = !$this->config['sec_usergroups'] ? array() : json_decode(trim($this->config['sec_usergroups']), true);
     $this->get_group_options($group_id_ary);
     // Set output vars for display in the template
     $this->template->assign_vars(array('S_ACP_LOGIN_EMAIL' => $this->config['sec_login_email'], 'ACP_CONTACT_EMAIL' => $this->config['sec_contact'], 'ACP_CONTACT_NAME' => $this->config['sec_contact_name'], 'S_ACP_LOGIN_ATTEMPTS' => $this->config['sec_login_attempts'], 'S_ACP_EMAIL_CHANGES' => $this->config['sec_email_changes'], 'S_ACP_STRONG_PASS' => $this->config['sec_strong_pass'], 'ACP_MIN_PASS_CHARS' => $this->config['sec_min_pass_chars'], 'U_ACTION' => $this->u_action));
 }
示例#6
0
 /**
  * Check admin data
  *
  * @param string	$username	Admin username
  * @param string	$pass1		Admin password
  * @param string	$pass2		Admin password confirmation
  * @param string	$email		Admin e-mail address
  *
  * @return bool	True if data is valid, false otherwise
  */
 protected function check_admin_data($username, $pass1, $pass2, $email)
 {
     $data_valid = true;
     // Check if none of admin data is empty
     if (in_array('', array($username, $pass1, $pass2, $email), true)) {
         $this->io_handler->add_error_message('INST_ERR_MISSING_DATA');
         $data_valid = false;
     }
     if (utf8_strlen($username) < 3) {
         $this->io_handler->add_error_message('INST_ERR_USER_TOO_SHORT');
         $data_valid = false;
     }
     if (utf8_strlen($username) > 20) {
         $this->io_handler->add_error_message('INST_ERR_USER_TOO_LONG');
         $data_valid = false;
     }
     if ($pass1 !== $pass2 && $pass1 !== '') {
         $this->io_handler->add_error_message('INST_ERR_PASSWORD_MISMATCH');
         $data_valid = false;
     }
     // Test against the default password rules
     if (utf8_strlen($pass1) < 6) {
         $this->io_handler->add_error_message('INST_ERR_PASSWORD_TOO_SHORT');
         $data_valid = false;
     }
     if (utf8_strlen($pass1) > 30) {
         $this->io_handler->add_error_message('INST_ERR_PASSWORD_TOO_LONG');
         $data_valid = false;
     }
     if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email)) {
         $this->io_handler->add_error_message('INST_ERR_EMAIL_INVALID');
         $data_valid = false;
     }
     return $data_valid;
 }
/**
* make_clickable function
*
* Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
* Cuts down displayed size of link if over 50 chars, turns absolute links
* into relative versions when the server/script path matches the link
*/
function make_clickable($text, $server_url = false, $class = 'postlink')
{
    if ($server_url === false) {
        $server_url = generate_board_url();
    }
    static $static_class;
    static $magic_url_match_args;
    if (!isset($magic_url_match_args[$server_url]) || $static_class != $class) {
        $static_class = $class;
        $class = $static_class ? ' class="' . $static_class . '"' : '';
        $local_class = $static_class ? ' class="' . $static_class . '-local"' : '';
        if (!is_array($magic_url_match_args)) {
            $magic_url_match_args = array();
        }
        // relative urls for this board
        $magic_url_match_args[$server_url][] = array('#(^|[\\n\\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#iu', MAGIC_URL_LOCAL, $local_class);
        // matches a xxxx://aaaaa.bbb.cccc. ...
        $magic_url_match_args[$server_url][] = array('#(^|[\\n\\t (>.])(' . get_preg_expression('url_inline') . ')#iu', MAGIC_URL_FULL, $class);
        // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
        $magic_url_match_args[$server_url][] = array('#(^|[\\n\\t (>])(' . get_preg_expression('www_url_inline') . ')#iu', MAGIC_URL_WWW, $class);
        // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
        $magic_url_match_args[$server_url][] = array('/(^|[\\n\\t (>])(' . get_preg_expression('email') . ')/iu', MAGIC_URL_EMAIL, '');
    }
    foreach ($magic_url_match_args[$server_url] as $magic_args) {
        if (preg_match($magic_args[0], $text, $matches)) {
            $text = preg_replace_callback($magic_args[0], function ($matches) use($magic_args) {
                $relative_url = isset($matches[3]) ? $matches[3] : '';
                return make_clickable_callback($magic_args[1], $matches[1], $matches[2], $relative_url, $magic_args[2]);
            }, $text);
        }
    }
    return $text;
}
示例#8
0
文件: ipv6.php 项目: Noxwizard/phpbb3
	public function setUp()
	{
		$this->regex = get_preg_expression('ipv6');
	}
/**
* Wrapper for inet_pton()
*
* Converts a human readable IP address to its packed in_addr representation
* inet_pton() is supported by PHP since 5.1.0, since 5.3.0 also on Windows.
*
* @param string $address	A human readable IPv4 or IPv6 address.
*
* @return mixed		false if address is invalid,
*					in_addr representation of the given address otherwise (string)
*/
function phpbb_inet_pton($address)
{
    $ret = '';
    if (preg_match(get_preg_expression('ipv4'), $address)) {
        foreach (explode('.', $address) as $part) {
            $ret .= ($part <= 0xf ? '0' : '') . dechex($part);
        }
        return pack('H*', $ret);
    }
    if (preg_match(get_preg_expression('ipv6'), $address)) {
        $parts = explode(':', $address);
        $missing_parts = 8 - sizeof($parts) + 1;
        if (substr($address, 0, 2) === '::') {
            ++$missing_parts;
        }
        if (substr($address, -2) === '::') {
            ++$missing_parts;
        }
        $embedded_ipv4 = false;
        $last_part = end($parts);
        if (preg_match(get_preg_expression('ipv4'), $last_part)) {
            $parts[sizeof($parts) - 1] = '';
            $last_part = phpbb_inet_pton($last_part);
            $embedded_ipv4 = true;
            --$missing_parts;
        }
        foreach ($parts as $i => $part) {
            if (strlen($part)) {
                $ret .= str_pad($part, 4, '0', STR_PAD_LEFT);
            } else {
                if ($i && $i < sizeof($parts) - 1) {
                    $ret .= str_repeat('0000', $missing_parts);
                }
            }
        }
        $ret = pack('H*', $ret);
        if ($embedded_ipv4) {
            $ret .= $last_part;
        }
        return $ret;
    }
    return false;
}
示例#10
0
 /**
  * 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('/(&amp;|\\?)sid=[0-9a-f]{32}&amp;/', '\\1', $url);
             $url = preg_replace('/(&amp;|\\?)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]';
 }
示例#11
0
 function make_clickable($text, $server_url = false, $class = 'postlink')
 {
     //$server_url is for phpBB3 only $class is for later phpBB3 only
     global $IN_WORDPRESS;
     if ($IN_WORDPRESS) {
         return wp_make_clickable($text);
         //WP version
     } else {
         //phpBB version
         global $wpuAbs;
         if ('PHPBB2' == $wpuAbs->ver) {
             $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1&#058;", $text);
             $ret = ' ' . $text;
             $ret = preg_replace("#(^|[\n ])([\\w]+?://[\\w\\#\$%&~/.\\-;:=,?@\\[\\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
             $ret = preg_replace("#(^|[\n ])((www|ftp)\\.[\\w\\#\$%&~/.\\-;:=,?@\\[\\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
             $ret = preg_replace("#(^|[\n ])([a-z0-9&\\-_.]+?)@([\\w\\-]+\\.([\\w\\-\\.]+\\.)*[\\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
             $ret = substr($ret, 1);
             return $ret;
         } else {
             //phpBB3 BRANCH:
             if ($server_url === false) {
                 $server_url = generate_board_url();
             }
             static $magic_url_match;
             static $magic_url_replace;
             static $static_class;
             if (!is_array($magic_url_match)) {
                 $magic_url_match = $magic_url_replace = array();
                 if (function_exists('make_clickable_callback')) {
                     //latest phpBB3s
                     $magic_url_match[] = '#(^|[\\n\\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
                     $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '{$local_class}')";
                     $magic_url_match[] = '#(^|[\\n\\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
                     $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '{$class}')";
                     $magic_url_match[] = '#(^|[\\n\\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
                     $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '{$class}')";
                     $magic_url_match[] = '/(^|[\\n\\t (>])(' . get_preg_expression('email') . ')/ie';
                     $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
                 } else {
                     // phpBB3 v1.0
                     $magic_url_match[] = '#(^|[\\n\\t (])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
                     $magic_url_replace[] = "'\$1<!-- l --><a href=\"\$2/' . preg_replace('/(&amp;|\\?)sid=[0-9a-f]{32}/', '\\\\1', '\$3') . '\">' . preg_replace('/(&amp;|\\?)sid=[0-9a-f]{32}/', '\\\\1', '\$3') . '</a><!-- l -->'";
                     $magic_url_match[] = '#(^|[\\n\\t (])(' . get_preg_expression('url_inline') . ')#ie';
                     $magic_url_replace[] = "'\$1<!-- m --><a href=\"\$2\">' . ((strlen('\$2') > 55) ? substr(str_replace('&amp;', '&', '\$2'), 0, 39) . ' ... ' . substr(str_replace('&amp;', '&', '\$2'), -10) : '\$2') . '</a><!-- m -->'";
                     $magic_url_match[] = '#(^|[\\n\\t (])(' . get_preg_expression('www_url_inline') . ')#ie';
                     $magic_url_replace[] = "'\$1<!-- w --><a href=\"http://\$2\">' . ((strlen('\$2') > 55) ? substr(str_replace('&amp;', '&', '\$2'), 0, 39) . ' ... ' . substr(str_replace('&amp;', '&', '\$2'), -10) : '\$2') . '</a><!-- w -->'";
                     $magic_url_match[] = '/(^|[\\n\\t )])(' . get_preg_expression('email') . ')/ie';
                     $magic_url_replace[] = "'\$1<!-- e --><a href=\"mailto:\$2\">' . ((strlen('\$2') > 55) ? substr('\$2', 0, 39) . ' ... ' . substr('\$2', -10) : '\$2') . '</a><!-- e -->'";
                 }
             }
             return preg_replace($magic_url_match, $magic_url_replace, $text);
         }
     }
 }
示例#12
0
 function build_regexp(&$bbcode_match, &$bbcode_tpl)
 {
     $bbcode_match = trim($bbcode_match);
     $bbcode_tpl = trim($bbcode_tpl);
     $utf8 = strpos($bbcode_match, 'INTTEXT') !== false;
     $utf8_pcre_properties = phpbb_pcre_utf8_support();
     $fp_match = preg_quote($bbcode_match, '!');
     $fp_replace = preg_replace('#^\\[(.*?)\\]#', '[$1:$uid]', $bbcode_match);
     $fp_replace = preg_replace('#\\[/(.*?)\\]$#', '[/$1:$uid]', $fp_replace);
     $sp_match = preg_quote($bbcode_match, '!');
     $sp_match = preg_replace('#^\\\\\\[(.*?)\\\\\\]#', '\\[$1:$uid\\]', $sp_match);
     $sp_match = preg_replace('#\\\\\\[/(.*?)\\\\\\]$#', '\\[/$1:$uid\\]', $sp_match);
     $sp_replace = $bbcode_tpl;
     // @todo Make sure to change this too if something changed in message parsing
     $tokens = array('URL' => array('!(?:(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('url')) . ')|(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('www_url')) . '))!ie' => "\$this->bbcode_specialchars(('\$1') ? '\$1' : 'http://\$2')"), 'LOCAL_URL' => array('!(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('relative_url')) . ')!e' => "\$this->bbcode_specialchars('\$1')"), 'RELATIVE_URL' => array('!(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('relative_url')) . ')!e' => "\$this->bbcode_specialchars('\$1')"), 'EMAIL' => array('!(' . get_preg_expression('email') . ')!ie' => "\$this->bbcode_specialchars('\$1')"), 'TEXT' => array('!(.*?)!es' => "str_replace(array(\"\\r\\n\", '\\\"', '\\'', '(', ')'), array(\"\\n\", '\"', '&#39;', '&#40;', '&#41;'), trim('\$1'))"), 'SIMPLETEXT' => array('!([a-zA-Z0-9-+.,_ ]+)!' => "\$1"), 'INTTEXT' => array($utf8_pcre_properties ? '!([\\p{L}\\p{N}\\-+,_. ]+)!u' : '!([a-zA-Z0-9\\-+,_. ]+)!u' => "\$1"), 'IDENTIFIER' => array('!([a-zA-Z0-9-_]+)!' => "\$1"), 'COLOR' => array('!([a-z]+|#[0-9abcdef]+)!i' => '$1'), 'NUMBER' => array('!([0-9]+)!' => '$1'));
     $sp_tokens = array('URL' => '(?i)((?:' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('url')) . ')|(?:' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('www_url')) . '))(?-i)', 'LOCAL_URL' => '(?i)(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('relative_url')) . ')(?-i)', 'RELATIVE_URL' => '(?i)(' . str_replace(array('!', '\\#'), array('\\!', '#'), get_preg_expression('relative_url')) . ')(?-i)', 'EMAIL' => '(' . get_preg_expression('email') . ')', 'TEXT' => '(.*?)', 'SIMPLETEXT' => '([a-zA-Z0-9-+.,_ ]+)', 'INTTEXT' => $utf8_pcre_properties ? '([\\p{L}\\p{N}\\-+,_. ]+)' : '([a-zA-Z0-9\\-+,_. ]+)', 'IDENTIFIER' => '([a-zA-Z0-9-_]+)', 'COLOR' => '([a-zA-Z]+|#[0-9abcdefABCDEF]+)', 'NUMBER' => '([0-9]+)');
     $pad = 0;
     $modifiers = 'i';
     $modifiers .= $utf8 && $utf8_pcre_properties ? 'u' : '';
     if (preg_match_all('/\\{(' . implode('|', array_keys($tokens)) . ')[0-9]*\\}/i', $bbcode_match, $m)) {
         foreach ($m[0] as $n => $token) {
             $token_type = $m[1][$n];
             reset($tokens[strtoupper($token_type)]);
             list($match, $replace) = each($tokens[strtoupper($token_type)]);
             // Pad backreference numbers from tokens
             if (preg_match_all('/(?<!\\\\)\\$([0-9]+)/', $replace, $repad)) {
                 $repad = $pad + sizeof(array_unique($repad[0]));
                 $replace = preg_replace('/(?<!\\\\)\\$([0-9]+)/e', "'\${' . (\$1 + \$pad) . '}'", $replace);
                 $pad = $repad;
             }
             // Obtain pattern modifiers to use and alter the regex accordingly
             $regex = preg_replace('/!(.*)!([a-z]*)/', '$1', $match);
             $regex_modifiers = preg_replace('/!(.*)!([a-z]*)/', '$2', $match);
             for ($i = 0, $size = strlen($regex_modifiers); $i < $size; ++$i) {
                 if (strpos($modifiers, $regex_modifiers[$i]) === false) {
                     $modifiers .= $regex_modifiers[$i];
                     if ($regex_modifiers[$i] == 'e') {
                         $fp_replace = "'" . str_replace("'", "\\'", $fp_replace) . "'";
                     }
                 }
                 if ($regex_modifiers[$i] == 'e') {
                     $replace = "'.{$replace}.'";
                 }
             }
             $fp_match = str_replace(preg_quote($token, '!'), $regex, $fp_match);
             $fp_replace = str_replace($token, $replace, $fp_replace);
             $sp_match = str_replace(preg_quote($token, '!'), $sp_tokens[$token_type], $sp_match);
             // Prepend the board url to local relative links
             $replace_prepend = $token_type === 'LOCAL_URL' ? generate_board_url() . '/' : '';
             $sp_replace = str_replace($token, $replace_prepend . '${' . ($n + 1) . '}', $sp_replace);
         }
         $fp_match = '!' . $fp_match . '!' . $modifiers;
         $sp_match = '!' . $sp_match . '!s' . ($utf8 ? 'u' : '');
         if (strpos($fp_match, 'e') !== false) {
             $fp_replace = str_replace("'.'", '', $fp_replace);
             $fp_replace = str_replace(".''.", '.', $fp_replace);
         }
     } else {
         // No replacement is present, no need for a second-pass pattern replacement
         // A simple str_replace will suffice
         $fp_match = '!' . $fp_match . '!' . $modifiers;
         $sp_match = $fp_replace;
         $sp_replace = '';
     }
     // Lowercase tags
     $bbcode_tag = preg_replace('/.*?\\[([a-z0-9_-]+=?).*/i', '$1', $bbcode_match);
     $bbcode_search = preg_replace('/.*?\\[([a-z0-9_-]+)=?.*/i', '$1', $bbcode_match);
     if (!preg_match('/^[a-zA-Z0-9_-]+=?$/', $bbcode_tag)) {
         global $user;
         trigger_error($user->lang['BBCODE_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING);
     }
     $fp_match = preg_replace('#\\[/?' . $bbcode_search . '#ie', "strtolower('\$0')", $fp_match);
     $fp_replace = preg_replace('#\\[/?' . $bbcode_search . '#ie', "strtolower('\$0')", $fp_replace);
     $sp_match = preg_replace('#\\[/?' . $bbcode_search . '#ie', "strtolower('\$0')", $sp_match);
     $sp_replace = preg_replace('#\\[/?' . $bbcode_search . '#ie', "strtolower('\$0')", $sp_replace);
     return array('bbcode_tag' => $bbcode_tag, 'first_pass_match' => $fp_match, 'first_pass_replace' => $fp_replace, 'second_pass_match' => $sp_match, 'second_pass_replace' => $sp_replace);
 }
示例#13
0
文件: memberlist.php 项目: html/PI
        if ($submit) {
            if (!check_form_key('memberlist_email')) {
                $error[] = 'FORM_INVALID';
            }
            if ($user_id) {
                if (!$subject) {
                    $error[] = $user->lang['EMPTY_SUBJECT_EMAIL'];
                }
                if (!$message) {
                    $error[] = $user->lang['EMPTY_MESSAGE_EMAIL'];
                }
                $name = $row['username'];
                $email_lang = $row['user_lang'];
                $email = $row['user_email'];
            } else {
                if (!$email || !preg_match('/^' . get_preg_expression('email') . '$/i', $email)) {
                    $error[] = $user->lang['EMPTY_ADDRESS_EMAIL'];
                }
                if (!$name) {
                    $error[] = $user->lang['EMPTY_NAME_EMAIL'];
                }
            }
            if (!sizeof($error)) {
                $sql = 'UPDATE ' . USERS_TABLE . '
					SET user_emailtime = ' . time() . '
					WHERE user_id = ' . $user->data['user_id'];
                $result = $db->sql_query($sql);
                include_once $phpbb_root_path . 'includes/functions_messenger.' . $phpEx;
                $messenger = new messenger(false);
                $email_tpl = $user_id ? 'profile_send_email' : 'email_notify';
                $mail_to_users = array();
示例#14
0
 /**
  */
 function format_message(&$text, $uid_param = '', $keep_bbcodes = true)
 {
     global $user;
     $uid = $uid_param ? $uid_param : '[0-9a-z]{5,}';
     // If there is a spoiler, remove the spoiler content.
     $search = '@\\[spoiler(?:=[^]]*)?:' . $uid . '\\](.*?)\\[/spoiler:' . $uid . '\\]@s';
     $replace = '[spoiler](' . $user->lang['NA'] . ')[/spoiler]';
     $text = preg_replace($search, $replace, $text);
     if ($keep_bbcodes) {
         // Strip unique ids out of BBCodes
         $text = preg_replace("#\\[(\\/?[a-z0-9\\*\\+\\-]+(?:=.*?)?(?::[a-z])?)(\\:?{$uid})\\]#", '[\\1]', $text);
         // If there is a URL between BBCode URL tags, then add spacing so
         // the email program won't think the BBCode is part of the URL.
         $text = preg_replace('@](http://.*?)\\[@', '] $1 [', $text);
     } else {
         // Change quotes
         $text = preg_replace('@\\[quote=(?:"|&quot;)([^"]*)(?:"|&quot;):' . $uid . '\\]@', "[quote=\"\$1\"]", $text);
         $text = preg_replace('@\\[code=([a-z]+):' . $uid . '\\]@', "[code=\$1]", $text);
         $text = preg_replace('@\\[(/)?(quote|code):' . $uid . '\\]@', "[\$1\$2]", $text);
         // Change lists (quick & dirty, no checking if we're actually in a list, much less if it's ordered or unordered)
         $text = str_replace('[*]', '* ', $text);
         $text = $uid_param ? str_replace('[*:' . $uid . ']', '* ', $text) : preg_replace('\\[\\*:' . $uid . ']', '* ', $text);
         // Change [url=http://www.example.com]Example[/url] to Example (http://www.example.com)
         $text = preg_replace('@\\[url=([^]]*):' . $uid . '\\]([^[]*)\\[/url:' . $uid . '\\]@', '$2 ($1)', $text);
         // Remove all remaining BBCodes
         //strip_bbcode($text, $uid_param); // This function replaces BBCodes with spaces, which we don't want
         $text = preg_replace("#\\[\\/?[a-z0-9\\*\\+\\-]+(?:=(?:&quot;.*&quot;|[^\\]]*))?(?::[a-z])?(\\:{$uid})\\]#", '', $text);
         $match = get_preg_expression('bbcode_htm');
         $replace = array('\\1', '\\1', '\\2', '\\1', '', '');
         $text = preg_replace($match, $replace, $text);
     }
     // Change HTML smiley images to text smilies
     $text = preg_replace('#<!-- s[^ >]* --><img src="[^"]*" alt="([^"]*)" title="[^"]*" /><!-- s[^ >]* -->#', ' $1 ', $text);
     // Change HTML links to text links
     $text = preg_replace('#<!-- [lmw] --><a .*?href="([^"]*)">.*?</a><!-- [lmw] -->#', '$1', $text);
     // Change HTML e-mail links to text links
     $text = preg_replace('#<!-- e --><a .*?href="[^"]*">(.*?)</a><!-- e -->#', '$1', $text);
     // Transform special BBCode characters into human-readable characters
     $transform = array('&lt;' => '<', '&gt;' => '>', '&#91;' => '[', '&#93;' => ']', '&#46;' => '.', '&#58;' => ':');
     $text = str_replace(array_keys($transform), array_values($transform), $text);
     // Remove backslashes that appear directly before single quotes
     $text = stripslashes(trim($text));
 }
示例#15
0
 /**
  * @dataProvider data_path_remove_dot_trailing_slash
  */
 public function test_path_remove_dot_trailing_slash($input, $replace, $expected)
 {
     $this->assertSame($expected, preg_replace(get_preg_expression('path_remove_dot_trailing_slash'), $replace, $input));
 }
示例#16
0
	/**
	* @dataProvider url_test_data
	*/
	public function test_url($url, $expected)
	{
		$this->assertEquals($expected, preg_match('#^' . get_preg_expression('url') . '$#i', $url));
	}
示例#17
0
文件: create.php 项目: phpbb/umil
/**
 * Generic validation of e-mail address
 *
 * @param string $email
 * @return mixed
 */
function validate_generic_email($email)
{
    if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email)) {
        return 'EMAIL_INVALID';
    }
    return false;
}
示例#18
0
 private function ip()
 {
     // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
     // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
     $this->ip = htmlspecialchars_decode($this->request->server('REMOTE_ADDR'));
     $this->ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->ip));
     // split the list of IPs
     $ips = explode(' ', trim($this->ip));
     // Default IP if REMOTE_ADDR is invalid
     $this->ip = '127.0.0.1';
     foreach ($ips as $ip) {
         if (function_exists('phpbb_ip_normalise')) {
             // Normalise IP address
             $ip = phpbb_ip_normalise($ip);
             if (empty($ip)) {
                 // IP address is invalid.
                 break;
             }
             // IP address is valid.
             $this->ip = $ip;
             // Skip legacy code.
             continue;
         }
         if (preg_match(get_preg_expression('ipv4'), $ip)) {
             $this->ip = $ip;
         } else {
             if (preg_match(get_preg_expression('ipv6'), $ip)) {
                 // Quick check for IPv4-mapped address in IPv6
                 if (stripos($ip, '::ffff:') === 0) {
                     $ipv4 = substr($ip, 7);
                     if (preg_match(get_preg_expression('ipv4'), $ipv4)) {
                         $ip = $ipv4;
                     }
                 }
                 $this->ip = $ip;
             } else {
                 // We want to use the last valid address in the chain
                 // Leave foreach loop when address is invalid
                 break;
             }
         }
     }
     return $this->ip;
 }
function strip_bbcode(&$text, $uid = '')
{
    if (!$uid) {
        $uid = '[0-9a-z]{5,}';
    }
    $text = preg_replace("#\\[\\/?[a-z0-9\\*\\+\\-]+(?:=.*?)?(?::[a-z])?(\\:?{$uid})\\]#", ' ', $text);
    $match = get_preg_expression('bbcode_htm');
    $replace = array('\\1', '\\2', '\\1', '', '');
    $text = preg_replace($match, $replace, $text);
}
示例#20
0
 public function setUp()
 {
     $this->regex = '#^' . get_preg_expression('email') . '$#i';
 }
示例#21
0
    /**
     * Start session management
     *
     * This is where all session activity begins. We gather various pieces of
     * information from the client and server. We test to see if a session already
     * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
     * new one ... pretty logical heh? We also examine the system load (if we're
     * running on a system which makes such information readily available) and
     * halt if it's above an admin definable limit.
     *
     * @param bool $update_session_page if true the session page gets updated.
     *			This can be set to circumvent certain scripts to update the users last visited page.
     */
    function session_begin($update_session_page = true)
    {
        global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
        // Give us some basic information
        $this->time_now = time();
        $this->cookie_data = array('u' => 0, 'k' => '');
        $this->update_session_page = $update_session_page;
        $this->browser = !empty($_SERVER['HTTP_USER_AGENT']) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
        $this->referer = !empty($_SERVER['HTTP_REFERER']) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
        $this->forwarded_for = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? (string) $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
        $this->host = $this->extract_current_hostname();
        $this->page = $this->extract_current_page($phpbb_root_path);
        // if the forwarded for header shall be checked we have to validate its contents
        if ($config['forwarded_for_check']) {
            $this->forwarded_for = preg_replace('#, +#', ', ', $this->forwarded_for);
            // split the list of IPs
            $ips = explode(', ', $this->forwarded_for);
            foreach ($ips as $ip) {
                // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
                if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip)) {
                    // contains invalid data, don't use the forwarded for header
                    $this->forwarded_for = '';
                    break;
                }
            }
        } else {
            $this->forwarded_for = '';
        }
        if (isset($_COOKIE[$config['cookie_name'] . '_sid']) || isset($_COOKIE[$config['cookie_name'] . '_u'])) {
            $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true);
            $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true);
            $this->session_id = request_var($config['cookie_name'] . '_sid', '', false, true);
            $SID = defined('NEED_SID') ? '?sid=' . $this->session_id : '?sid=';
            $_SID = defined('NEED_SID') ? $this->session_id : '';
            if (empty($this->session_id)) {
                $this->session_id = $_SID = request_var('sid', '');
                $SID = '?sid=' . $this->session_id;
                $this->cookie_data = array('u' => 0, 'k' => '');
            }
        } else {
            $this->session_id = $_SID = request_var('sid', '');
            $SID = '?sid=' . $this->session_id;
        }
        $_EXTRA_URL = array();
        // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
        // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
        $this->ip = !empty($_SERVER['REMOTE_ADDR']) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
        $this->load = false;
        // Load limit check (if applicable)
        if ($config['limit_load'] || $config['limit_search_load']) {
            if (function_exists('sys_getloadavg') && ($load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg')))) {
                $this->load = array_slice($load, 0, 1);
                $this->load = floatval($this->load[0]);
            } else {
                set_config('limit_load', '0');
                set_config('limit_search_load', '0');
            }
        }
        // Is session_id is set or session_id is set and matches the url param if required
        if (!empty($this->session_id) && (!defined('NEED_SID') || isset($_GET['sid']) && $this->session_id === $_GET['sid'])) {
            $sql = 'SELECT u.*, s.*
				FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u\n\t\t\t\tWHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'\n\t\t\t\t\tAND u.user_id = s.session_user_id";
            $result = $db->sql_query($sql);
            $this->data = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            // Did the session exist in the DB?
            if (isset($this->data['user_id'])) {
                // Validate IP length according to admin ... enforces an IP
                // check on bots if admin requires this
                //				$quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
                if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false) {
                    $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
                    $u_ip = short_ipv6($this->ip, $config['ip_check']);
                } else {
                    $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
                    $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
                }
                $s_browser = $config['browser_check'] ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
                $u_browser = $config['browser_check'] ? trim(strtolower(substr($this->browser, 0, 149))) : '';
                $s_forwarded_for = $config['forwarded_for_check'] ? substr($this->data['session_forwarded_for'], 0, 254) : '';
                $u_forwarded_for = $config['forwarded_for_check'] ? substr($this->forwarded_for, 0, 254) : '';
                // referer checks
                // The @ before $config['referer_validation'] suppresses notices present while running the updater
                $check_referer_path = @$config['referer_validation'] == REFERER_VALIDATE_PATH;
                $referer_valid = true;
                // we assume HEAD and TRACE to be foul play and thus only whitelist GET
                if (@$config['referer_validation'] && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) !== 'get') {
                    $referer_valid = $this->validate_referer($check_referer_path);
                }
                if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid) {
                    $session_expired = false;
                    // Check whether the session is still valid if we have one
                    $method = basename(trim($config['auth_method']));
                    include_once $phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx;
                    $method = 'validate_session_' . $method;
                    if (function_exists($method)) {
                        if (!$method($this->data)) {
                            $session_expired = true;
                        }
                    }
                    if (!$session_expired) {
                        // Check the session length timeframe if autologin is not enabled.
                        // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
                        if (!$this->data['session_autologin']) {
                            if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60)) {
                                $session_expired = true;
                            }
                        } else {
                            if (!$config['allow_autologin'] || $config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - 86400 * (int) $config['max_autologin_time'] + 60) {
                                $session_expired = true;
                            }
                        }
                    }
                    if (!$session_expired) {
                        // Only update session DB a minute or so after last update or if page changes
                        if ($this->time_now - $this->data['session_time'] > 60 || $this->update_session_page && $this->data['session_page'] != $this->page['page']) {
                            $sql_ary = array('session_time' => $this->time_now);
                            if ($this->update_session_page) {
                                $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
                                $sql_ary['session_forum_id'] = $this->page['forum'];
                            }
                            $db->sql_return_on_error(true);
                            $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\tWHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
                            $result = $db->sql_query($sql);
                            $db->sql_return_on_error(false);
                            // If the database is not yet updated, there will be an error due to the session_forum_id
                            // @todo REMOVE for 3.0.2
                            if ($result === false) {
                                unset($sql_ary['session_forum_id']);
                                $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "\n\t\t\t\t\t\t\t\t\tWHERE session_id = '" . $db->sql_escape($this->session_id) . "'";
                                $db->sql_query($sql);
                            }
                        }
                        $this->data['is_registered'] = $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER) ? true : false;
                        $this->data['is_bot'] = !$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS ? true : false;
                        $this->data['user_lang'] = basename($this->data['user_lang']);
                        return true;
                    }
                } else {
                    // Added logging temporarly to help debug bugs...
                    if (defined('DEBUG_EXTRA') && $this->data['user_id'] != ANONYMOUS) {
                        if ($referer_valid) {
                            add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for));
                        } else {
                            add_log('critical', 'LOG_REFERER_INVALID', $this->referer);
                        }
                    }
                }
            }
        }
        // If we reach here then no (valid) session exists. So we'll create a new one
        return $this->session_create();
    }
示例#22
0
文件: factory.php 项目: MrAdder/phpbb
 /**
  * Generate and return a new configured instance of s9e\TextFormatter\Configurator
  *
  * @return Configurator
  */
 public function get_configurator()
 {
     // Create a new Configurator
     $configurator = new Configurator();
     /**
      * Modify the s9e\TextFormatter configurator before the default settings are set
      *
      * @event core.text_formatter_s9e_configure_before
      * @var \s9e\TextFormatter\Configurator configurator Configurator instance
      * @since 3.2.0-a1
      */
     $vars = array('configurator');
     extract($this->dispatcher->trigger_event('core.text_formatter_s9e_configure_before', compact($vars)));
     // Reset the list of allowed schemes
     foreach ($configurator->urlConfig->getAllowedSchemes() as $scheme) {
         $configurator->urlConfig->disallowScheme($scheme);
     }
     foreach (explode(',', $this->config['allowed_schemes_links']) as $scheme) {
         $configurator->urlConfig->allowScheme(trim($scheme));
     }
     // Convert newlines to br elements by default
     $configurator->rootRules->enableAutoLineBreaks();
     // Don't automatically ignore text in places where text is not allowed
     $configurator->rulesGenerator->remove('IgnoreTextIfDisallowed');
     // Don't remove comments and instead convert them to xsl:comment elements
     $configurator->templateNormalizer->remove('RemoveComments');
     $configurator->templateNormalizer->add('TransposeComments');
     // Set the rendering engine and configure it to save to the cache dir
     $configurator->rendering->engine = 'PHP';
     $configurator->rendering->engine->cacheDir = $this->cache_dir;
     $configurator->rendering->engine->defaultClassPrefix = 's9e_renderer_';
     $configurator->rendering->engine->enableQuickRenderer = true;
     // Create custom filters for BBCode tokens that are supported in phpBB but not in
     // s9e\TextFormatter
     $filter = new RegexpFilter('#^' . get_preg_expression('relative_url') . '$#Du');
     $configurator->attributeFilters->add('#local_url', $filter);
     $configurator->attributeFilters->add('#relative_url', $filter);
     // INTTEXT regexp from acp_bbcodes
     $filter = new RegexpFilter('!^([\\p{L}\\p{N}\\-+,_. ]+)$!Du');
     $configurator->attributeFilters->add('#inttext', $filter);
     // Create custom filters for Flash restrictions, which use the same values as the image
     // restrictions but have their own error message
     $configurator->attributeFilters->add('#flashheight', __NAMESPACE__ . '\\parser::filter_flash_height')->addParameterByName('max_img_height')->addParameterByName('logger');
     $configurator->attributeFilters->add('#flashwidth', __NAMESPACE__ . '\\parser::filter_flash_width')->addParameterByName('max_img_width')->addParameterByName('logger');
     // Create a custom filter for phpBB's per-mode font size limits
     $configurator->attributeFilters->add('#fontsize', __NAMESPACE__ . '\\parser::filter_font_size')->addParameterByName('max_font_size')->addParameterByName('logger')->markAsSafeInCSS();
     // Create a custom filter for image URLs
     $configurator->attributeFilters->add('#imageurl', __NAMESPACE__ . '\\parser::filter_img_url')->addParameterByName('urlConfig')->addParameterByName('logger')->addParameterByName('max_img_height')->addParameterByName('max_img_width')->markAsSafeAsURL();
     // Add default BBCodes
     foreach ($this->get_default_bbcodes($configurator) as $bbcode) {
         $configurator->BBCodes->addCustom($bbcode['usage'], $bbcode['template']);
     }
     // Modify the template to disable images/flash depending on user's settings
     foreach (array('FLASH', 'IMG') as $name) {
         $tag = $configurator->tags[$name];
         $tag->template = '<xsl:choose><xsl:when test="$S_VIEW' . $name . '">' . $tag->template . '</xsl:when><xsl:otherwise><xsl:apply-templates/></xsl:otherwise></xsl:choose>';
     }
     // Load custom BBCodes
     foreach ($this->data_access->get_bbcodes() as $row) {
         // Insert the board's URL before {LOCAL_URL} tokens
         $tpl = preg_replace_callback('#\\{LOCAL_URL\\d*\\}#', function ($m) {
             return generate_board_url() . '/' . $m[0];
         }, $row['bbcode_tpl']);
         try {
             $configurator->BBCodes->addCustom($row['bbcode_match'], new UnsafeTemplate($tpl));
         } catch (\Exception $e) {
             /**
              * @todo log an error?
              */
         }
     }
     // Load smilies
     foreach ($this->data_access->get_smilies() as $row) {
         $configurator->Emoticons->add($row['code'], '<img class="smilies" src="{$T_SMILIES_PATH}/' . htmlspecialchars($row['smiley_url']) . '" alt="{.}" title="' . htmlspecialchars($row['emotion']) . '"/>');
     }
     if (isset($configurator->Emoticons)) {
         // Force emoticons to be rendered as text if $S_VIEWSMILIES is not set
         $configurator->Emoticons->notIfCondition = 'not($S_VIEWSMILIES)';
         // Only parse emoticons at the beginning of the text or if they're preceded by any
         // one of: a new line, a space, a dot, or a right square bracket
         $configurator->Emoticons->notAfter = '[^\\n .\\]]';
     }
     // Load the censored words
     $censor = $this->data_access->get_censored_words();
     if (!empty($censor)) {
         // Use a namespaced tag to avoid collisions
         $configurator->plugins->load('Censor', array('tagName' => 'censor:tag'));
         foreach ($censor as $row) {
             // NOTE: words are stored as HTML, we need to decode them to plain text
             $configurator->Censor->add(htmlspecialchars_decode($row['word']), htmlspecialchars_decode($row['replacement']));
         }
     }
     // Load the magic links plugins. We do that after BBCodes so that they use the same tags
     $configurator->plugins->load('Autoemail');
     $configurator->plugins->load('Autolink', array('matchWww' => true));
     // Register some vars with a default value. Those should be set at runtime by whatever calls
     // the parser
     $configurator->registeredVars['max_font_size'] = 0;
     $configurator->registeredVars['max_img_height'] = 0;
     $configurator->registeredVars['max_img_width'] = 0;
     // Load the Emoji plugin and modify its tag's template to obey viewsmilies
     $configurator->Emoji->setImageSize(18);
     $tag = $configurator->Emoji->getTag();
     $tag->template = '<xsl:choose><xsl:when test="$S_VIEWSMILIES">' . str_replace('class="emoji"', 'class="smilies"', $tag->template) . '</xsl:when><xsl:otherwise><xsl:value-of select="."/></xsl:otherwise></xsl:choose>';
     /**
      * Modify the s9e\TextFormatter configurator after the default settings are set
      *
      * @event core.text_formatter_s9e_configure_after
      * @var \s9e\TextFormatter\Configurator configurator Configurator instance
      * @since 3.2.0-a1
      */
     $vars = array('configurator');
     extract($this->dispatcher->trigger_event('core.text_formatter_s9e_configure_after', compact($vars)));
     return $configurator;
 }
示例#23
0
/**
* 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 . "\n\t\t\tWHERE user_email_hash = " . (crc32($email) . strlen($email));
        $result = $db->sql_query($sql);
        $row = $db->sql_fetchrow($result);
        $db->sql_freeresult($result);
        if ($row) {
            return 'EMAIL_TAKEN';
        }
    }
    return false;
}
示例#24
0
/**
* Going through a config array and validate values, writing errors to $error. The validation method  accepts parameters separated by ':' for string and int.
* The first parameter defines the type to be used, the second the lower bound and the third the upper bound. Only the type is required.
*/
function validate_config_vars($config_vars, &$cfg_array, &$error)
{
    global $phpbb_root_path, $user, $phpbb_dispatcher;
    $type = 0;
    $min = 1;
    $max = 2;
    foreach ($config_vars as $config_name => $config_definition) {
        if (!isset($cfg_array[$config_name]) || strpos($config_name, 'legend') !== false) {
            continue;
        }
        if (!isset($config_definition['validate'])) {
            continue;
        }
        $validator = explode(':', $config_definition['validate']);
        // Validate a bit. ;) (0 = type, 1 = min, 2= max)
        switch ($validator[$type]) {
            case 'string':
                $length = utf8_strlen($cfg_array[$config_name]);
                // the column is a VARCHAR
                $validator[$max] = isset($validator[$max]) ? min(255, $validator[$max]) : 255;
                if (isset($validator[$min]) && $length < $validator[$min]) {
                    $error[] = sprintf($user->lang['SETTING_TOO_SHORT'], $user->lang[$config_definition['lang']], $validator[$min]);
                } else {
                    if (isset($validator[$max]) && $length > $validator[2]) {
                        $error[] = sprintf($user->lang['SETTING_TOO_LONG'], $user->lang[$config_definition['lang']], $validator[$max]);
                    }
                }
                break;
            case 'bool':
                $cfg_array[$config_name] = $cfg_array[$config_name] ? 1 : 0;
                break;
            case 'int':
                $cfg_array[$config_name] = (int) $cfg_array[$config_name];
                if (isset($validator[$min]) && $cfg_array[$config_name] < $validator[$min]) {
                    $error[] = sprintf($user->lang['SETTING_TOO_LOW'], $user->lang[$config_definition['lang']], $validator[$min]);
                } else {
                    if (isset($validator[$max]) && $cfg_array[$config_name] > $validator[$max]) {
                        $error[] = sprintf($user->lang['SETTING_TOO_BIG'], $user->lang[$config_definition['lang']], $validator[$max]);
                    }
                }
                if (strpos($config_name, '_max') !== false) {
                    // Min/max pairs of settings should ensure that min <= max
                    // Replace _max with _min to find the name of the minimum
                    // corresponding configuration variable
                    $min_name = str_replace('_max', '_min', $config_name);
                    if (isset($cfg_array[$min_name]) && is_numeric($cfg_array[$min_name]) && $cfg_array[$config_name] < $cfg_array[$min_name]) {
                        // A minimum value exists and the maximum value is less than it
                        $error[] = sprintf($user->lang['SETTING_TOO_LOW'], $user->lang[$config_definition['lang']], (int) $cfg_array[$min_name]);
                    }
                }
                break;
            case 'email':
                if (!preg_match('/^' . get_preg_expression('email') . '$/i', $cfg_array[$config_name])) {
                    $error[] = $user->lang['EMAIL_INVALID_EMAIL'];
                }
                break;
                // Absolute path
            // Absolute path
            case 'script_path':
                if (!$cfg_array[$config_name]) {
                    break;
                }
                $destination = str_replace('\\', '/', $cfg_array[$config_name]);
                if ($destination !== '/') {
                    // Adjust destination path (no trailing slash)
                    if (substr($destination, -1, 1) == '/') {
                        $destination = substr($destination, 0, -1);
                    }
                    $destination = str_replace(array('../', './'), '', $destination);
                    if ($destination[0] != '/') {
                        $destination = '/' . $destination;
                    }
                }
                $cfg_array[$config_name] = trim($destination);
                break;
                // Absolute path
            // Absolute path
            case 'lang':
                if (!$cfg_array[$config_name]) {
                    break;
                }
                $cfg_array[$config_name] = basename($cfg_array[$config_name]);
                if (!file_exists($phpbb_root_path . 'language/' . $cfg_array[$config_name] . '/')) {
                    $error[] = $user->lang['WRONG_DATA_LANG'];
                }
                break;
                // Relative path (appended $phpbb_root_path)
            // Relative path (appended $phpbb_root_path)
            case 'rpath':
            case 'rwpath':
                if (!$cfg_array[$config_name]) {
                    break;
                }
                $destination = $cfg_array[$config_name];
                // 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 = '';
                }
                $cfg_array[$config_name] = trim($destination);
                // Absolute file path
            // Absolute file path
            case 'absolute_path':
            case 'absolute_path_writable':
                // Path being relative (still prefixed by phpbb_root_path), but with the ability to escape the root dir...
            // Path being relative (still prefixed by phpbb_root_path), but with the ability to escape the root dir...
            case 'path':
            case 'wpath':
                if (!$cfg_array[$config_name]) {
                    break;
                }
                $cfg_array[$config_name] = trim($cfg_array[$config_name]);
                // Make sure no NUL byte is present...
                if (strpos($cfg_array[$config_name], "") !== false || strpos($cfg_array[$config_name], '%00') !== false) {
                    $cfg_array[$config_name] = '';
                    break;
                }
                $path = in_array($config_definition['validate'], array('wpath', 'path', 'rpath', 'rwpath')) ? $phpbb_root_path . $cfg_array[$config_name] : $cfg_array[$config_name];
                if (!file_exists($path)) {
                    $error[] = sprintf($user->lang['DIRECTORY_DOES_NOT_EXIST'], $cfg_array[$config_name]);
                }
                if (file_exists($path) && !is_dir($path)) {
                    $error[] = sprintf($user->lang['DIRECTORY_NOT_DIR'], $cfg_array[$config_name]);
                }
                // Check if the path is writable
                if ($config_definition['validate'] == 'wpath' || $config_definition['validate'] == 'rwpath' || $config_definition['validate'] === 'absolute_path_writable') {
                    if (file_exists($path) && !phpbb_is_writable($path)) {
                        $error[] = sprintf($user->lang['DIRECTORY_NOT_WRITABLE'], $cfg_array[$config_name]);
                    }
                }
                break;
            default:
                /**
                 * Validate a config value
                 *
                 * @event core.validate_config_variable
                 * @var	array	cfg_array	Array with config values
                 * @var	string	config_name	Name of the config we validate
                 * @var	array	config_definition	Array with the options for
                 *									this config
                 * @var	array	error		Array of errors, the errors should
                 *							be strings only, language keys are
                 *							not replaced afterwards
                 * @since 3.1.0-a1
                 */
                $vars = array('cfg_array', 'config_name', 'config_definition', 'error');
                extract($phpbb_dispatcher->trigger_event('core.validate_config_variable', compact($vars)));
                break;
        }
    }
    return;
}
 /**
  * Opens a connection to send data (FTP fosck only function)
  * @access private
  */
 function _open_data_connection()
 {
     // Try to find out whether we have a IPv4 or IPv6 (control) connection
     if (function_exists('stream_socket_get_name')) {
         $socket_name = stream_socket_get_name($this->connection, true);
         $server_ip = substr($socket_name, 0, strrpos($socket_name, ':'));
     }
     if (!isset($server_ip) || preg_match(get_preg_expression('ipv4'), $server_ip)) {
         // Passive mode
         $this->_send_command('PASV', '', false);
         if (!($ip_port = $this->_check_command(true))) {
             return false;
         }
         // open the connection to start sending the file
         if (!preg_match('#[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+#', $ip_port, $temp)) {
             // bad ip and port
             return false;
         }
         $temp = explode(',', $temp[0]);
         $server_ip = $temp[0] . '.' . $temp[1] . '.' . $temp[2] . '.' . $temp[3];
         $server_port = $temp[4] * 256 + $temp[5];
     } else {
         // Extended Passive Mode - RFC2428
         $this->_send_command('EPSV', '', false);
         if (!($epsv_response = $this->_check_command(true))) {
             return false;
         }
         // Response looks like "229 Entering Extended Passive Mode (|||12345|)"
         // where 12345 is the tcp port for the data connection
         if (!preg_match('#\\(\\|\\|\\|([0-9]+)\\|\\)#', $epsv_response, $match)) {
             return false;
         }
         $server_port = (int) $match[1];
         // fsockopen expects IPv6 address in square brackets
         $server_ip = "[{$server_ip}]";
     }
     $errno = 0;
     $errstr = '';
     if (!($this->data_connection = @fsockopen($server_ip, $server_port, $errno, $errstr, $this->timeout))) {
         return false;
     }
     @stream_set_timeout($this->data_connection, $this->timeout);
     return true;
 }
示例#26
0
 /**
  * Generate a URL to a route
  *
  * @param string	$route		Name of the route to travel
  * @param array	$params		String or array of additional url parameters
  * @param bool	$is_amp		Is url using &amp; (true) or & (false)
  * @param string|bool		$session_id	Possibility to use a custom session id instead of the global one
  * @param bool|string		$reference_type The type of reference to be generated (one of the constants)
  * @return string The URL already passed through append_sid()
  */
 public function route($route, array $params = array(), $is_amp = true, $session_id = false, $reference_type = UrlGeneratorInterface::ABSOLUTE_PATH)
 {
     $anchor = '';
     if (isset($params['#'])) {
         $anchor = '#' . $params['#'];
         unset($params['#']);
     }
     $context = new RequestContext();
     $context->fromRequest($this->symfony_request);
     if ($this->config['force_server_vars']) {
         $context->setHost($this->config['server_name']);
         $context->setScheme(substr($this->config['server_protocol'], 0, -3));
         $context->setHttpPort($this->config['server_port']);
         $context->setHttpsPort($this->config['server_port']);
         $context->setBaseUrl(rtrim($this->config['script_path'], '/'));
     }
     $script_name = $this->symfony_request->getScriptName();
     $page_name = substr($script_name, -1, 1) == '/' ? '' : utf8_basename($script_name);
     $base_url = $context->getBaseUrl();
     // Append page name if base URL does not contain it
     if (!empty($page_name) && strpos($base_url, '/' . $page_name) === false) {
         $base_url .= '/' . $page_name;
     }
     // If enable_mod_rewrite is false we need to replace the current front-end by app.php, otherwise we need to remove it.
     $base_url = str_replace('/' . $page_name, empty($this->config['enable_mod_rewrite']) ? '/app.' . $this->php_ext : '', $base_url);
     // We need to update the base url to move to the directory of the app.php file if the current script is not app.php
     if ($page_name !== 'app.php' && !$this->config['force_server_vars']) {
         if (empty($this->config['enable_mod_rewrite'])) {
             $base_url = str_replace('/app.' . $this->php_ext, '/' . $this->phpbb_root_path . 'app.' . $this->php_ext, $base_url);
         } else {
             $base_url .= preg_replace(get_preg_expression('path_remove_dot_trailing_slash'), '$2', $this->phpbb_root_path);
         }
     }
     $base_url = $this->request->escape($this->filesystem->clean_path($base_url), true);
     $context->setBaseUrl($base_url);
     $this->router->setContext($context);
     $route_url = $this->router->generate($route, $params, $reference_type);
     if ($is_amp) {
         $route_url = str_replace(array('&amp;', '&'), array('&', '&amp;'), $route_url);
     }
     if ($reference_type === UrlGeneratorInterface::RELATIVE_PATH && empty($this->config['enable_mod_rewrite'])) {
         $route_url = 'app.' . $this->php_ext . '/' . $route_url;
     }
     return append_sid($route_url . $anchor, false, $is_amp, $session_id, true);
 }
示例#27
0
	/**
	* Obtain the administrator's name, password and email address
	*/
	function obtain_admin_settings($mode, $sub)
	{
		global $lang, $template, $phpEx;

		$this->page_title = $lang['STAGE_ADMINISTRATOR'];

		// Obtain any submitted data
		$data = $this->get_submitted_data();

		if ($data['dbms'] == '')
		{
			// Someone's been silly and tried calling this page direct
			// So we send them back to the start to do it again properly
			$this->p_master->redirect("index.$phpEx?mode=install");
		}

		$s_hidden_fields = ($data['img_imagick']) ? '<input type="hidden" name="img_imagick" value="' . addslashes($data['img_imagick']) . '" />' : '';
		$passed = false;

		$data['default_lang'] = ($data['default_lang'] !== '') ? $data['default_lang'] : $data['language'];

		if (isset($_POST['check']))
		{
			$error = array();

			// Check the entered email address and password
			if ($data['admin_name'] == '' || $data['admin_pass1'] == '' || $data['admin_pass2'] == '' || $data['board_email1'] == '' || $data['board_email2'] == '')
			{
				$error[] = $lang['INST_ERR_MISSING_DATA'];
			}

			if ($data['admin_pass1'] != $data['admin_pass2'] && $data['admin_pass1'] != '')
			{
				$error[] = $lang['INST_ERR_PASSWORD_MISMATCH'];
			}

			// Test against the default username rules
			if ($data['admin_name'] != '' && utf8_strlen($data['admin_name']) < 3)
			{
				$error[] = $lang['INST_ERR_USER_TOO_SHORT'];
			}

			if ($data['admin_name'] != '' && utf8_strlen($data['admin_name']) > 20)
			{
				$error[] = $lang['INST_ERR_USER_TOO_LONG'];
			}

			// Test against the default password rules
			if ($data['admin_pass1'] != '' && utf8_strlen($data['admin_pass1']) < 6)
			{
				$error[] = $lang['INST_ERR_PASSWORD_TOO_SHORT'];
			}

			if ($data['admin_pass1'] != '' && utf8_strlen($data['admin_pass1']) > 30)
			{
				$error[] = $lang['INST_ERR_PASSWORD_TOO_LONG'];
			}

			if ($data['board_email1'] != $data['board_email2'] && $data['board_email1'] != '')
			{
				$error[] = $lang['INST_ERR_EMAIL_MISMATCH'];
			}

			if ($data['board_email1'] != '' && !preg_match('/^' . get_preg_expression('email') . '$/i', $data['board_email1']))
			{
				$error[] = $lang['INST_ERR_EMAIL_INVALID'];
			}

			$template->assign_block_vars('checks', array(
				'S_LEGEND'			=> true,
				'LEGEND'			=> $lang['STAGE_ADMINISTRATOR'],
				'LEGEND_EXPLAIN'	=> false,
			));

			if (!sizeof($error))
			{
				$passed = true;
				$template->assign_block_vars('checks', array(
					'TITLE'		=> $lang['ADMIN_TEST'],
					'RESULT'	=> '<strong style="color:green">' . $lang['TESTS_PASSED'] . '</strong>',

					'S_EXPLAIN'	=> false,
					'S_LEGEND'	=> false,
				));
			}
			else
			{
				$template->assign_block_vars('checks', array(
					'TITLE'		=> $lang['ADMIN_TEST'],
					'RESULT'	=> '<strong style="color:red">' . implode('<br />', $error) . '</strong>',

					'S_EXPLAIN'	=> false,
					'S_LEGEND'	=> false,
				));
			}
		}

		if (!$passed)
		{
			foreach ($this->admin_config_options as $config_key => $vars)
			{
				if (!is_array($vars) && strpos($config_key, 'legend') === false)
				{
					continue;
				}

				if (strpos($config_key, 'legend') !== false)
				{
					$template->assign_block_vars('options', array(
						'S_LEGEND'		=> true,
						'LEGEND'		=> $lang[$vars])
					);

					continue;
				}

				$options = isset($vars['options']) ? $vars['options'] : '';

				$template->assign_block_vars('options', array(
					'KEY'			=> $config_key,
					'TITLE'			=> $lang[$vars['lang']],
					'S_EXPLAIN'		=> $vars['explain'],
					'S_LEGEND'		=> false,
					'TITLE_EXPLAIN'	=> ($vars['explain']) ? $lang[$vars['lang'] . '_EXPLAIN'] : '',
					'CONTENT'		=> $this->p_master->input_field($config_key, $vars['type'], $data[$config_key], $options),
					)
				);
			}
		}
		else
		{
			foreach ($this->admin_config_options as $config_key => $vars)
			{
				if (!is_array($vars))
				{
					continue;
				}
				$s_hidden_fields .= '<input type="hidden" name="' . $config_key . '" value="' . $data[$config_key] . '" />';
			}
		}

		$s_hidden_fields .= ($data['img_imagick']) ? '<input type="hidden" name="img_imagick" value="' . addslashes($data['img_imagick']) . '" />' : '';
		$s_hidden_fields .= '<input type="hidden" name="language" value="' . $data['language'] . '" />';

		foreach ($this->db_config_options as $config_key => $vars)
		{
			if (!is_array($vars))
			{
				continue;
			}
			$s_hidden_fields .= '<input type="hidden" name="' . $config_key . '" value="' . $data[$config_key] . '" />';
		}

		$submit = $lang['NEXT_STEP'];

		$url = ($passed) ? $this->p_master->module_url . "?mode=$mode&amp;sub=config_file" : $this->p_master->module_url . "?mode=$mode&amp;sub=administrator";
		$s_hidden_fields .= ($passed) ? '' : '<input type="hidden" name="check" value="true" />';

		$template->assign_vars(array(
			'L_SUBMIT'	=> $submit,
			'S_HIDDEN'	=> $s_hidden_fields,
			'U_ACTION'	=> $url,
		));
	}
示例#28
0
/**
* Check to see if email address is a valid address and contains a MX record
*
* @param string $email The email to check
*
* @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
*/
function phpbb_validate_email($email, $config = null)
{
    if ($config === null) {
        global $config;
    }
    $email = strtolower($email);
    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';
        }
    }
    return false;
}
示例#29
0
    /**
     * Start session management
     *
     * This is where all session activity begins. We gather various pieces of
     * information from the client and server. We test to see if a session already
     * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
     * new one ... pretty logical heh? We also examine the system load (if we're
     * running on a system which makes such information readily available) and
     * halt if it's above an admin definable limit.
     *
     * @param bool $update_session_page if true the session page gets updated.
     *			This can be set to circumvent certain scripts to update the users last visited page.
     */
    function session_begin($update_session_page = true)
    {
        global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
        global $request, $phpbb_container, $user, $phpbb_log;
        // Give us some basic information
        $this->time_now = time();
        $this->cookie_data = array('u' => 0, 'k' => '');
        $this->update_session_page = $update_session_page;
        $this->browser = $request->header('User-Agent');
        $this->referer = $request->header('Referer');
        $this->forwarded_for = $request->header('X-Forwarded-For');
        $this->host = $this->extract_current_hostname();
        $this->page = $this->extract_current_page($phpbb_root_path);
        // if the forwarded for header shall be checked we have to validate its contents
        if ($config['forwarded_for_check']) {
            $this->forwarded_for = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->forwarded_for));
            // split the list of IPs
            $ips = explode(' ', $this->forwarded_for);
            foreach ($ips as $ip) {
                // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
                if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip)) {
                    // contains invalid data, don't use the forwarded for header
                    $this->forwarded_for = '';
                    break;
                }
            }
        } else {
            $this->forwarded_for = '';
        }
        if ($request->is_set($config['cookie_name'] . '_sid', \phpbb\request\request_interface::COOKIE) || $request->is_set($config['cookie_name'] . '_u', \phpbb\request\request_interface::COOKIE)) {
            $this->cookie_data['u'] = $request->variable($config['cookie_name'] . '_u', 0, false, \phpbb\request\request_interface::COOKIE);
            $this->cookie_data['k'] = $request->variable($config['cookie_name'] . '_k', '', false, \phpbb\request\request_interface::COOKIE);
            $this->session_id = $request->variable($config['cookie_name'] . '_sid', '', false, \phpbb\request\request_interface::COOKIE);
            $SID = defined('NEED_SID') ? '?sid=' . $this->session_id : '?sid=';
            $_SID = defined('NEED_SID') ? $this->session_id : '';
            if (empty($this->session_id)) {
                $this->session_id = $_SID = $request->variable('sid', '');
                $SID = '?sid=' . $this->session_id;
                $this->cookie_data = array('u' => 0, 'k' => '');
            }
        } else {
            $this->session_id = $_SID = $request->variable('sid', '');
            $SID = '?sid=' . $this->session_id;
        }
        $_EXTRA_URL = array();
        // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
        // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
        $this->ip = htmlspecialchars_decode($request->server('REMOTE_ADDR'));
        $this->ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->ip));
        // split the list of IPs
        $ips = explode(' ', trim($this->ip));
        // Default IP if REMOTE_ADDR is invalid
        $this->ip = '127.0.0.1';
        foreach ($ips as $ip) {
            if (function_exists('phpbb_ip_normalise')) {
                // Normalise IP address
                $ip = phpbb_ip_normalise($ip);
                if (empty($ip)) {
                    // IP address is invalid.
                    break;
                }
                // IP address is valid.
                $this->ip = $ip;
                // Skip legacy code.
                continue;
            }
            if (preg_match(get_preg_expression('ipv4'), $ip)) {
                $this->ip = $ip;
            } else {
                if (preg_match(get_preg_expression('ipv6'), $ip)) {
                    // Quick check for IPv4-mapped address in IPv6
                    if (stripos($ip, '::ffff:') === 0) {
                        $ipv4 = substr($ip, 7);
                        if (preg_match(get_preg_expression('ipv4'), $ipv4)) {
                            $ip = $ipv4;
                        }
                    }
                    $this->ip = $ip;
                } else {
                    // We want to use the last valid address in the chain
                    // Leave foreach loop when address is invalid
                    break;
                }
            }
        }
        $this->load = false;
        // Load limit check (if applicable)
        if ($config['limit_load'] || $config['limit_search_load']) {
            if (function_exists('sys_getloadavg') && ($load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg')))) {
                $this->load = array_slice($load, 0, 1);
                $this->load = floatval($this->load[0]);
            } else {
                $config->set('limit_load', '0');
                $config->set('limit_search_load', '0');
            }
        }
        // if no session id is set, redirect to index.php
        $session_id = $request->variable('sid', '');
        if (defined('NEED_SID') && (empty($session_id) || $this->session_id !== $session_id)) {
            send_status_line(401, 'Unauthorized');
            redirect(append_sid("{$phpbb_root_path}index.{$phpEx}"));
        }
        // if session id is set
        if (!empty($this->session_id)) {
            $sql = 'SELECT u.*, s.*
				FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u\n\t\t\t\tWHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'\n\t\t\t\t\tAND u.user_id = s.session_user_id";
            $result = $db->sql_query($sql);
            $this->data = $db->sql_fetchrow($result);
            $db->sql_freeresult($result);
            // Did the session exist in the DB?
            if (isset($this->data['user_id'])) {
                // Validate IP length according to admin ... enforces an IP
                // check on bots if admin requires this
                //				$quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
                if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false) {
                    $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
                    $u_ip = short_ipv6($this->ip, $config['ip_check']);
                } else {
                    $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
                    $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
                }
                $s_browser = $config['browser_check'] ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
                $u_browser = $config['browser_check'] ? trim(strtolower(substr($this->browser, 0, 149))) : '';
                $s_forwarded_for = $config['forwarded_for_check'] ? substr($this->data['session_forwarded_for'], 0, 254) : '';
                $u_forwarded_for = $config['forwarded_for_check'] ? substr($this->forwarded_for, 0, 254) : '';
                // referer checks
                // The @ before $config['referer_validation'] suppresses notices present while running the updater
                $check_referer_path = @$config['referer_validation'] == REFERER_VALIDATE_PATH;
                $referer_valid = true;
                // we assume HEAD and TRACE to be foul play and thus only whitelist GET
                if (@$config['referer_validation'] && strtolower($request->server('REQUEST_METHOD')) !== 'get') {
                    $referer_valid = $this->validate_referer($check_referer_path);
                }
                if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid) {
                    $session_expired = false;
                    // Check whether the session is still valid if we have one
                    /* @var $provider_collection \phpbb\auth\provider_collection */
                    $provider_collection = $phpbb_container->get('auth.provider_collection');
                    $provider = $provider_collection->get_provider();
                    if (!$provider instanceof \phpbb\auth\provider\provider_interface) {
                        throw new \RuntimeException($provider . ' must implement \\phpbb\\auth\\provider\\provider_interface');
                    }
                    $ret = $provider->validate_session($this->data);
                    if ($ret !== null && !$ret) {
                        $session_expired = true;
                    }
                    if (!$session_expired) {
                        // Check the session length timeframe if autologin is not enabled.
                        // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
                        if (!$this->data['session_autologin']) {
                            if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60)) {
                                $session_expired = true;
                            }
                        } else {
                            if (!$config['allow_autologin'] || $config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - 86400 * (int) $config['max_autologin_time'] + 60) {
                                $session_expired = true;
                            }
                        }
                    }
                    if (!$session_expired) {
                        // Only update session DB a minute or so after last update or if page changes
                        if ($this->time_now - $this->data['session_time'] > 60 || $this->update_session_page && $this->data['session_page'] != $this->page['page']) {
                            $sql_ary = array('session_time' => $this->time_now);
                            // Do not update the session page for ajax requests, so the view online still works as intended
                            if ($this->update_session_page && !$request->is_ajax()) {
                                $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
                                $sql_ary['session_forum_id'] = $this->page['forum'];
                            }
                            $db->sql_return_on_error(true);
                            $this->update_session($sql_ary);
                            $db->sql_return_on_error(false);
                            // If the database is not yet updated, there will be an error due to the session_forum_id
                            // @todo REMOVE for 3.0.2
                            if ($result === false) {
                                unset($sql_ary['session_forum_id']);
                                $this->update_session($sql_ary);
                            }
                            if ($this->data['user_id'] != ANONYMOUS && !empty($config['new_member_post_limit']) && $this->data['user_new'] && $config['new_member_post_limit'] <= $this->data['user_posts']) {
                                $this->leave_newly_registered();
                            }
                        }
                        $this->data['is_registered'] = $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER) ? true : false;
                        $this->data['is_bot'] = !$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS ? true : false;
                        $this->data['user_lang'] = basename($this->data['user_lang']);
                        return true;
                    }
                } else {
                    // Added logging temporarly to help debug bugs...
                    if (defined('DEBUG') && $this->data['user_id'] != ANONYMOUS) {
                        if ($referer_valid) {
                            $phpbb_log->add('critical', $user->data['user_id'], $user->ip, 'LOG_IP_BROWSER_FORWARDED_CHECK', false, array($u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for)));
                        } else {
                            $phpbb_log->add('critical', $user->data['user_id'], $user->ip, 'LOG_REFERER_INVALID', false, array($this->referer));
                        }
                    }
                }
            }
        }
        // If we reach here then no (valid) session exists. So we'll create a new one
        return $this->session_create();
    }
/**
* make_clickable function
*
* Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
* Cuts down displayed size of link if over 50 chars, turns absolute links
* into relative versions when the server/script path matches the link
*/
function make_clickable($text, $server_url = false, $class = 'postlink')
{
    if ($server_url === false) {
        $server_url = generate_board_url();
    }
    static $magic_url_match;
    static $magic_url_replace;
    static $static_class;
    if (!is_array($magic_url_match) || $static_class != $class) {
        $static_class = $class;
        $class = $static_class ? ' class="' . $static_class . '"' : '';
        $local_class = $static_class ? ' class="' . $static_class . '-local"' : '';
        $magic_url_match = $magic_url_replace = array();
        // Be sure to not let the matches cross over. ;)
        // relative urls for this board
        $magic_url_match[] = '#(^|[\\n\\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
        $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '{$local_class}')";
        // matches a xxxx://aaaaa.bbb.cccc. ...
        $magic_url_match[] = '#(^|[\\n\\t (>.])(' . get_preg_expression('url_inline') . ')#ie';
        $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '{$class}')";
        // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
        $magic_url_match[] = '#(^|[\\n\\t (>])(' . get_preg_expression('www_url_inline') . ')#ie';
        $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '{$class}')";
        // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
        $magic_url_match[] = '/(^|[\\n\\t (>])(' . get_preg_expression('email') . ')/ie';
        $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
    }
    return preg_replace($magic_url_match, $magic_url_replace, $text);
}