Example #1
0
 /**
  * Standard modular run function for snippet hooks. Generates XHTML to insert into a page using AJAX.
  *
  * @return tempcode  The snippet
  */
 function run()
 {
     if (has_actual_page_access(get_member(), 'admin_themes')) {
         require_code('tempcode_compiler');
         return template_to_tempcode(post_param('css'));
     }
     return new ocp_tempcode();
 }
/**
 * A template has not been structurally cached, so compile it and store in the cache.
 *
 * @param  ID_TEXT			The theme the template is in the context of
 * @param  PATH				The path to the template file
 * @param  ID_TEXT			The codename of the template (e.g. foo)
 * @param  ID_TEXT			The actual codename to use for the template (e.g. thin_foo)
 * @param  LANGUAGE_NAME	The language the template is in the context of
 * @param  string				File type suffix of template file
 * @param  ?ID_TEXT			The theme to cache in (NULL: main theme)
 * @return tempcode			The compiled tempcode
 */
function _do_template($theme, $path, $codename, $_codename, $lang, $suffix, $theme_orig = NULL)
{
    if (is_null($theme_orig)) {
        $theme_orig = $theme;
    }
    $base_dir = ($theme == 'default' && ($suffix != '.css' || strpos($path, '/css_custom') === false) ? get_file_base() : get_custom_file_base()) . '/themes/';
    global $CACHE_TEMPLATES, $FILE_ARRAY, $TEMPLATE_PREVIEW_OP, $MEM_CACHE;
    if (isset($FILE_ARRAY)) {
        $html = unixify_line_format(file_array_get('themes/' . $theme . $path . $codename . $suffix));
    } else {
        $html = unixify_line_format(file_get_contents($base_dir . filter_naughty($theme . $path . $codename) . $suffix, FILE_TEXT));
    }
    if (strpos($html, '{$,Parser hint: pure}') !== false) {
        return make_string_tempcode(preg_replace('#\\{\\$,.*\\}#U', '/*no minify*/', $html));
    }
    if ($GLOBALS['SEMI_DEBUG_MODE'] && strpos($html, '.innerHTML') !== false && strpos($html, 'Parser hint: .innerHTML okay') === false) {
        require_code('site');
        attach_message('Do not use the .innerHTML property in your Javascript because it will not work in true XHTML (when the browsers real XML parser is in action). Use ocPortal\'s global setInnerHTML/getInnerHTML functions.', 'warn');
    }
    // Strip off trailing final lines from single lines templates. Editors often put these in, and it causes annoying "visible space" issues
    if (substr($html, -1, 1) == chr(10) && substr_count($html, chr(10)) == 1) {
        $html = substr($html, 0, strlen($html) - 1);
    }
    if ($TEMPLATE_PREVIEW_OP) {
        $test = post_param($codename, NULL);
        if (!is_null($test)) {
            $html = post_param($test . '_new');
        }
    }
    $result = template_to_tempcode($html, 0, false, $codename, $theme, $lang);
    if ($CACHE_TEMPLATES && ($suffix == '.tpl' || $codename == 'no_cache')) {
        if (!is_null($MEM_CACHE)) {
            persistant_cache_set(array('TEMPLATE', $theme, $lang, $_codename), $result->to_assembly(), strpos($path, 'default/templates/') !== false);
        } else {
            $path2 = get_custom_file_base() . '/themes/' . $theme_orig . '/templates_cached/' . filter_naughty($lang) . '/';
            $myfile = @fopen($path2 . filter_naughty($_codename) . $suffix . '.tcd', 'wb');
            if ($myfile === false) {
                if (@mkdir($path2, 0777)) {
                    require_code('files');
                    fix_permissions($path2, 0777);
                } else {
                    if (file_exists($path2 . filter_naughty($_codename) . $suffix . '.tcd')) {
                        warn_exit(do_lang_tempcode('WRITE_ERROR', $path2 . filter_naughty($_codename) . $suffix . '.tcd'));
                    } else {
                        warn_exit(do_lang_tempcode('WRITE_ERROR_CREATE', $path2 . filter_naughty($_codename) . $suffix . '.tcd'));
                    }
                }
            } else {
                fwrite($myfile, $result->to_assembly($lang));
                fclose($myfile);
                fix_permissions($path2 . filter_naughty($_codename) . $suffix . '.tcd');
            }
        }
    }
    return $result;
}
Example #3
0
 /**
  * Standard modular run function for preview hooks.
  *
  * @return array			A pair: The preview, the updated post Comcode
  */
 function run()
 {
     require_code('comcode_text');
     $tag = post_param('tag');
     $replace = post_param('replace');
     $parameters = '';
     foreach ($_POST as $key => $val) {
         if (substr($key, 0, 11) != 'parameters_') {
             continue;
         }
         if ($val == '') {
             continue;
         }
         if ($parameters != '') {
             $parameters .= ',';
         }
         $parameters .= $val;
     }
     $_parameters = $parameters == '' ? array() : explode(',', $parameters);
     $example = post_param('example');
     $content = do_lang_tempcode('EXAMPLE');
     $matches = array();
     if (preg_match('#\\](.*)\\[#', $example, $matches) != 0) {
         $content = make_string_tempcode($matches[1]);
     }
     $binding = array('CONTENT' => $content);
     foreach ($_parameters as $parameter) {
         $parameter = trim($parameter);
         $parts = explode('=', $parameter);
         if (count($parts) == 1) {
             $parts[] = '';
         }
         if (count($parts) != 2) {
             continue;
         }
         list($parameter, $default) = $parts;
         $binding[strtoupper($parameter)] = $default;
         $replace = str_replace('{' . $parameter . '}', '{' . strtoupper($parameter) . '*}', $replace);
     }
     require_code('tempcode_compiler');
     $replace = str_replace('{content}', array_key_exists($tag, $GLOBALS['TEXTUAL_TAGS']) ? '{CONTENT}' : '{CONTENT*}', $replace);
     $temp_tpl = template_to_tempcode($replace);
     $temp_tpl = $temp_tpl->bind($binding, '(custom comcode: ' . $tag . ')');
     return array($temp_tpl, NULL);
 }
Example #4
0
/**
 * Make some Comcode more readable.
 *
 * @param  string			Comcode text to change
 * @return string			Clean text
 */
function comcode_to_clean_text($message_plain)
{
    //$message_plain=str_replace("\n",'',$message_plain);
    if (strpos($message_plain, '[') === false && strpos($message_plain, '{') === false) {
        return $message_plain;
    }
    require_code('tempcode_compiler');
    if (strpos($message_plain, '[code') === false && strpos($message_plain, '[no_parse') === false && strpos($message_plain, '[tt') === false) {
        // Change username links to plain username namings
        $message_plain = preg_replace('#\\{\\{([^\\}\\{]*)\\}\\}#', '\\1', $message_plain);
        // Remove directives etc
        do {
            $before = $message_plain;
            $message_plain = preg_replace('#\\{([^\\}\\{]*)\\}#', '', $message_plain);
        } while ($message_plain != $before);
        if (strpos($message_plain, '{') !== false) {
            $message_plain = static_evaluate_tempcode(template_to_tempcode($message_plain, 0, false, '', NULL, NULL, true));
        }
    }
    $match = array();
    if (preg_match("#\\[semihtml\\](.*)\\[\\/semihtml\\]#Us", $message_plain, $match) != 0) {
        require_code('comcode_from_html');
        $message_plain = str_replace($match[0], semihtml_to_comcode($match[0]), $message_plain);
    }
    if (preg_match("#^\\s*\\[html\\](.*)\\[\\/html\\]\\s*\$#Us", $message_plain, $match) != 0) {
        require_code('comcode_from_html');
        $message_plain = str_replace($match[0], semihtml_to_comcode($match[0]), $message_plain);
    }
    $message_plain = array_key_exists(1, $match) ? $match[1] : $message_plain;
    $message_plain = preg_replace("#\\[url=\"([^\"]*)\"(.*)\\]([^\\[\\]]*)\\[/url\\]#", '${1}', $message_plain);
    $message_plain = preg_replace("#\\[img(.*)\\]([^\\[\\]]*)\\[/img\\]#", '', $message_plain);
    $message_plain = @html_entity_decode(strip_tags($message_plain), ENT_QUOTES, get_charset());
    $message_plain = str_replace(']http', ']' . chr(10) . 'http', str_replace('[/url]', chr(10) . '[/url]', $message_plain));
    $message_plain = preg_replace('#\\[random [^=]*="([^"]*)"[^\\]]*\\].*\\[/random\\]#Us', '${1}', $message_plain);
    $message_plain = preg_replace('#\\[abbr="([^"]*)"[^\\]]*\\].*\\[/abbr\\]#Us', '${1}', $message_plain);
    $message_plain = preg_replace_callback('#\\[indent[^\\]]*\\](.*)\\[/indent\\]#Us', '_indent_callback', $message_plain);
    $message_plain = preg_replace_callback('#\\[title([^\\]])*\\](.*)\\[/title\\]#Us', '_title_callback', $message_plain);
    $message_plain = preg_replace_callback('#\\[box="([^"]*)"[^\\]]*\\](.*)\\[/box\\]#Us', '_box_callback', $message_plain);
    $tags_to_strip_inards = array('if_in_group', 'snapback', 'post', 'thread', 'topic', 'include', 'staff_note', 'attachment', 'attachment2', 'attachment_safe', 'contents', 'block', 'random');
    foreach ($tags_to_strip_inards as $s) {
        $message_plain = preg_replace('#\\[' . $s . '[^\\]]*\\].*\\[/' . $s . '\\]#Us', '', $message_plain);
    }
    $message_plain = preg_replace('#\\[surround="accessibility_hidden"\\].*\\[/surround\\]#Us', '', $message_plain);
    $tags_to_strip = array('surround', 'ticker', 'jumping', 'right', 'center', 'left', 'align', 'list', 'concepts', 'html', 'semihtml', 'concept', 'size', 'color', 'font', 'tt', 'address', 'sup', 'sub', 'box');
    foreach ($tags_to_strip as $s) {
        $message_plain = preg_replace('#\\[' . $s . '[^\\]]*\\](.*)\\[/' . $s . '\\]#U', '${1}', $message_plain);
    }
    $message_plain = str_replace(array('[/*]', '[*]', '[list]' . chr(10), chr(10) . '[/list]', '[list]', '[/list]', '[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[highlight]', '[/highlight]'), array('', ' - ', '', '', '', '', '**', '**', '*', '*', '__', '__', '***', '***'), $message_plain);
    $message_plain = preg_replace('#\\[list[^\\[\\]]*\\]#', '', $message_plain);
    $message_plain = preg_replace('#\\{\\$,[^\\{\\}]*\\}#', '', $message_plain);
    return trim($message_plain);
}
Example #5
0
/**
 * Render a menu branch to tempcode.
 *
 * @param  array			The menu branch map
 * @param  SHORT_TEXT	An identifier for the menu (will be used as a unique id by menu javascript code)
 * @param  MEMBER			The member the menu is being built as
 * @param  integer		The depth into the menu that this branch resides at
 * @param  ID_TEXT		The menu type (determines what templates get used)
 * @param  boolean		Whether to generate Comcode with admin privilege
 * @param  array			Array of all other branches
 * @param  integer		The level
 * @return array			A pair: array of parameters of the menu branch (or NULL if unrenderable, or Tempcode of something to attach), and whether it is expanded
 */
function render_menu_branch($branch, $codename, $source_member, $level, $type, $as_admin, $all_branches, $the_level = 1)
{
    global $REDIRECTED_TO;
    $caption = mixed();
    // Initialise type to mixed
    if (is_string($branch['caption']) && strpos($branch['caption'], '[') !== false) {
        $caption = comcode_to_tempcode($branch['caption'], $source_member, $as_admin);
    } else {
        $caption = $branch['caption'];
    }
    if (!is_null($branch['only_on_page']) && $branch['only_on_page'] != '') {
        if (strpos($branch['only_on_page'], '{') !== false) {
            require_code('tempcode_compiler');
            $branch['only_on_page'] = static_evaluate_tempcode(template_to_tempcode($branch['only_on_page']));
        }
        if ($branch['only_on_page'] != '' && !match_key_match($branch['only_on_page'])) {
            return array(NULL, false);
        }
        // We are not allowed to render this on this page
    }
    $current_zone = false;
    $current_page = false;
    $expand_this = false;
    $tooltip = array_key_exists('caption_long', $branch) ? $branch['caption_long'] : '';
    if (is_null($tooltip)) {
        $tooltip = '';
    }
    // Caused by corrupt in DB. translate table join failed due to corrupt lang string reference
    $dp = $GLOBALS['ZONE']['zone_default_page'];
    $url = mixed();
    // Spacers
    if ($branch['type'] == 'blank') {
        return array(do_template('MENU_SPACER_' . filter_naughty_harsh($type), array('MENU' => $codename, 'TOP_LEVEL' => $the_level == 1, 'THE_LEVEL' => strval($the_level), 'CURRENT' => $current_page, 'CURRENT_ZONE' => $current_zone), NULL, false, 'MENU_SPACER_tree'), false);
    }
    // Normal branches...
    $users_current_zone = get_zone_name();
    // Work out the final URL to use
    $url = $branch['special'];
    if (is_object($url)) {
        if (isset($url->seq_parts) && isset($url->seq_parts[0]) && $url->seq_parts[0][3] == 'PAGE_LINK') {
            $url = $url->seq_parts[0][1][0];
            if (is_object($url)) {
                $url = $url->evaluate();
            }
        } elseif (isset($url->bits) && isset($url->bits[0]) && $url->bits[0][2] == 'PAGE_LINK') {
            $url = $url->bits[0][3][0];
            if (is_object($url)) {
                $url = $url->evaluate();
            }
        } elseif (substr($url->evaluate(), 0, strlen(get_base_url())) == get_base_url()) {
            $page_link = url_to_pagelink($url->evaluate(), true, true);
            if ($page_link != '') {
                $url = $page_link;
            }
        }
    }
    if (!is_object($url)) {
        $parts = array();
        if (preg_match('#([\\w-]*):([\\w-]+|[^/]|$)((:(.*))*)#', $url, $parts) != 0 && $parts[1] != 'mailto') {
            $page_link = $url;
            list($zone_name, $map, $hash) = page_link_decode($url);
            if ($zone_name == 'forum' && get_forum_type() != 'ocf') {
                return array(NULL, false);
            }
            if (!isset($map['page'])) {
                $map['page'] = get_zone_default_page($zone_name);
            }
            // If we need to check access
            if (array_key_exists('check_perms', $branch['modifiers'])) {
                if (!has_zone_access(get_member(), $zone_name)) {
                    return array(NULL, false);
                }
                if (!has_page_access(get_member(), $map['page'], $zone_name)) {
                    return array(NULL, false);
                }
            }
            // Scan for Tempcode symbols etc
            foreach ($map as $key => $val) {
                if (strpos($val, '{') !== false) {
                    require_code('tempcode_compiler');
                    $map[$key] = template_to_tempcode($val);
                }
            }
            $url = build_url($map, $zone_name, NULL, false, false, false, $hash);
            // See if this is current page
            $somewhere_definite = false;
            $_parts = array();
            foreach ($all_branches as $_branch) {
                if (!is_string($_branch['special'])) {
                    continue;
                }
                if (preg_match('#([\\w-]*):([\\w-]+|[^/]|$)((:(.*))*)#', $_branch['special'], $_parts) != 0) {
                    if ($_parts[1] == $users_current_zone) {
                        $somewhere_definite = true;
                    }
                }
            }
            $current_zone = $zone_name == $users_current_zone || !is_null($REDIRECTED_TO) && $zone_name == $REDIRECTED_TO['r_to_zone'] && !$somewhere_definite;
            // This code is a bit smart, as zone menus usually have a small number of zones on them - redirects will be counted into the zone redirected to, so long as there is no more suitable zone and so long as it is not a transparent redirect
            if ($zone_name == $users_current_zone || !is_null($REDIRECTED_TO) && $zone_name == $REDIRECTED_TO['r_to_zone'] && array_key_exists('page', $map) && $map['page'] == $REDIRECTED_TO['r_to_page']) {
                $current_page = true;
                foreach ($map as $k => $v) {
                    if (is_integer($v)) {
                        $v = strval($v);
                    }
                    if (is_object($v)) {
                        $v = $v->evaluate();
                    }
                    if ($v == '' && $k == 'page') {
                        $v = 'start';
                        if ($zone_name == $users_current_zone) {
                            global $ZONE;
                            $v = $ZONE['zone_default_page'];
                        }
                    }
                    $pv = get_param($k, $k == 'page' ? $dp : NULL, true);
                    if ($pv !== $v && ($k != 'page' || is_null($REDIRECTED_TO) || !is_null($REDIRECTED_TO) && ($v !== $REDIRECTED_TO['r_to_page'] || $zone_name != $REDIRECTED_TO['r_to_zone'])) && ($k != 'type' || $v != 'misc') && ($v != $dp || $k != 'page' || get_param('page', '') != '') && substr($k, 0, 5) != 'keep_') {
                        $current_page = false;
                        break;
                    }
                }
            }
        } else {
            $page_link = '';
            $sym_pos = mixed();
            $sym_pos = is_null($url) ? false : strpos($url, '{$');
            if ($sym_pos !== false) {
                $_url = new ocp_tempcode();
                $len = strlen($url);
                $prev = 0;
                do {
                    $p_len = $sym_pos + 1;
                    $balance = 1;
                    while ($p_len < $len && $balance != 0) {
                        if ($url[$p_len] == '{') {
                            $balance++;
                        } elseif ($url[$p_len] == '}') {
                            $balance--;
                        }
                        $p_len++;
                    }
                    $_url->attach(substr($url, $prev, $sym_pos - $prev));
                    $_ret = new ocp_tempcode();
                    $_ret->parse_from($url, $sym_pos, $p_len);
                    $_url->attach($_ret);
                    $prev = $p_len;
                    $sym_pos = strpos($url, '{$', $sym_pos + 1);
                } while ($sym_pos !== false);
                $_url->attach(substr($url, $prev));
                $url = $_url;
            }
        }
    } else {
        $page_link = NULL;
    }
    // Children
    $children = new ocp_tempcode();
    $display = 'block';
    if ($branch['type'] == 'drawer') {
        $new_children = array();
        foreach ($branch['children'] as $i => $child) {
            list($children2, $_expand_this) = render_menu_branch($child, $codename, $source_member, $level + 1, $type, $as_admin, $all_branches, $the_level + 1);
            if ($_expand_this) {
                $expand_this = true;
            }
            if ($children2 !== '' && !is_null($children2)) {
                $new_children[] = $children2;
            }
        }
        $num = count($new_children);
        foreach ($new_children as $i => $child) {
            if (is_object($child)) {
                $children->attach($child);
            } else {
                $children->attach(do_template('MENU_BRANCH_' . filter_naughty_harsh($type), $child + array('POSITION' => strval($i), 'LAST' => $i == $num - 1, 'BRETHREN_COUNT' => strval($num)), NULL, false, 'MENU_BRANCH_tree'));
            }
        }
        if ($children->is_empty()) {
            return array(NULL, false);
        }
        // Nothing here!
        if (!array_key_exists('expanded', $branch['modifiers']) && !$expand_this && !$current_page) {
            $display = has_js() ? 'none' : 'block';
            // We remap to 'none' using JS. If no JS, it remains visible. Once we have learn't we have JS, we don't need to do it again
        } else {
            $display = 'block';
        }
    }
    // Data cleanups
    $escape = is_string($caption) && !array_key_exists('comcode', $branch['modifiers']);
    if ($escape) {
        $caption = escape_html($caption);
    }
    // Access key
    if ($page_link === '_SEARCH:help') {
        $accesskey = '6';
    } elseif ($page_link === '_SEARCH:rules') {
        $accesskey = '7';
    } elseif ($page_link === '_SEARCH:staff:type=misc') {
        $accesskey = '5';
    } else {
        $accesskey = '';
    }
    // Other properties
    $popup = array_key_exists('popup', $branch['modifiers']);
    $popup_width = '';
    $popup_height = '';
    if ($popup) {
        $popup_width = strval($branch['width']);
        $popup_height = strval($branch['height']);
    }
    $new_window = array_key_exists('new_window', $branch['modifiers']);
    // Render!
    $rendered_branch = array('RANDOM' => substr(md5(uniqid('')), 0, 7), 'CAPTION' => $caption, 'IMG' => array_key_exists('img', $branch) ? $branch['img'] : '', 'URL' => $url, 'PAGE_LINK' => $page_link, 'ACCESSKEY' => $accesskey, 'POPUP' => $popup, 'POPUP_WIDTH' => $popup_width, 'POPUP_HEIGHT' => $popup_height, 'NEW_WINDOW' => $new_window, 'TOOLTIP' => $tooltip, 'CHILDREN' => $children, 'DISPLAY' => $display, 'MENU' => $codename, 'TOP_LEVEL' => $the_level == 1, 'THE_LEVEL' => strval($the_level), 'CURRENT' => $current_page, 'CURRENT_ZONE' => $current_zone);
    return array($rendered_branch, $current_page || $expand_this);
}
Example #6
0
 /**
  * Get a list of post templates that apply to a certain forum.
  *
  * @param  AUTO_LINK The ID of the forum.
  * @return array 		The list of applicable post templates.
  */
 function ocf_get_post_templates($forum_id)
 {
     if (!addon_installed('ocf_post_templates')) {
         return array();
     }
     $all_templates = $GLOBALS['FORUM_DB']->query_select('f_post_templates', array('*'));
     $apply = array();
     foreach ($all_templates as $template) {
         require_code('ocfiltering');
         $idlist = ocfilter_to_idlist_using_db($template['t_forum_multi_code'], 'id', 'f_forums', 'f_forums', 'f_parent_forum', 'f_parent_forum', 'id', true, true, $GLOBALS['FORUM_DB']);
         if (in_array($forum_id, $idlist)) {
             if (strpos($template['t_text'], '{') !== false) {
                 require_code('tempcode_compiler');
                 $e = template_to_tempcode($template['t_text']);
                 $template['t_text'] = $e->evaluate();
             }
             $apply[] = array($template['t_title'], $template['t_text'], $template['t_use_default_forums']);
         }
     }
     return $apply;
 }
Example #7
0
/**
 * A template has not been structurally cached, so compile it and store in the cache.
 *
 * @param  ID_TEXT			The theme the template is in the context of
 * @param  PATH				The path to the template file
 * @param  ID_TEXT			The codename of the template (e.g. foo)
 * @param  ID_TEXT			The actual codename to use for the template (e.g. foo_mobile)
 * @param  LANGUAGE_NAME	The language the template is in the context of
 * @param  string				File type suffix of template file (e.g. .tpl)
 * @param  ?ID_TEXT			The theme to cache in (NULL: main theme)
 * @return tempcode			The compiled tempcode
 */
function _do_template($theme, $path, $codename, $_codename, $lang, $suffix, $theme_orig = NULL)
{
    if (is_null($theme_orig)) {
        $theme_orig = $theme;
    }
    if (is_null($GLOBALS['CURRENT_SHARE_USER'])) {
        $base_dir = ($theme == 'default' && ($suffix != '.css' || strpos($path, '/css_custom') === false) ? get_file_base() : get_custom_file_base()) . '/themes/';
    } else {
        $base_dir = get_custom_file_base() . '/themes/';
        if (!is_file($base_dir . $theme . $path . $codename . $suffix)) {
            $base_dir = get_file_base() . '/themes/';
        }
    }
    global $CACHE_TEMPLATES, $FILE_ARRAY, $TEMPLATE_PREVIEW_OP, $MEM_CACHE;
    if (isset($FILE_ARRAY)) {
        $html = unixify_line_format(file_array_get('themes/' . $theme . $path . $codename . $suffix));
    } else {
        $html = unixify_line_format(file_get_contents($base_dir . filter_naughty($theme . $path . $codename) . $suffix, FILE_TEXT));
    }
    if ($GLOBALS['SEMI_DEBUG_MODE'] && strpos($html, '.innerHTML') !== false && !running_script('install') && strpos($html, 'Parser hint: .innerHTML okay') === false) {
        attach_message('Do not use the .innerHTML property in your Javascript because it will not work in true XHTML (when the browsers real XML parser is in action). Use ocPortal\'s global setInnerHTML/getInnerHTML functions.', 'warn');
    }
    // Strip off trailing final lines from single lines templates. Editors often put these in, and it causes annoying "visible space" issues
    if (substr($html, -1, 1) == chr(10) && substr_count($html, chr(10)) == 1) {
        $html = substr($html, 0, strlen($html) - 1);
    }
    if ($TEMPLATE_PREVIEW_OP) {
        $test = post_param($codename, NULL);
        if (!is_null($test)) {
            $html = post_param($test . '_new');
        }
    }
    $result = template_to_tempcode($html, 0, false, $suffix != '.tpl' ? '' : $codename, $theme_orig, $lang);
    if ($CACHE_TEMPLATES && !$TEMPLATE_PREVIEW_OP && ($suffix == '.tpl' || $codename == 'no_cache')) {
        $path2 = get_custom_file_base() . '/themes/' . $theme_orig . '/templates_cached/' . filter_naughty($lang) . '/';
        $myfile = @fopen($path2 . filter_naughty($_codename) . $suffix . '.tcp', 'wb');
        if ($myfile === false) {
            @mkdir(dirname($path2), 0777);
            fix_permissions(dirname($path2), 0777);
            sync_file(dirname($path2));
            if (@mkdir($path2, 0777)) {
                fix_permissions($path2, 0777);
                sync_file($path2);
            } else {
                if ($codename == 'SCREEN_TITLE') {
                    critical_error('PASSON', do_lang('WRITE_ERROR', escape_html($path2 . filter_naughty($_codename) . $suffix . '.tcp')));
                }
                // Bail out hard if would cause a loop
                intelligent_write_error($path2 . filter_naughty($_codename) . $suffix . '.tcp');
            }
        } else {
            $data_to_write = '<' . '?php' . chr(10) . $result->to_assembly($lang) . chr(10) . '?' . '>';
            if (fwrite($myfile, $data_to_write) >= strlen($data_to_write)) {
                // Success
                fclose($myfile);
                require_code('files');
                fix_permissions($path2 . filter_naughty($_codename) . $suffix . '.tcp');
            } else {
                // Failure
                fclose($myfile);
                @unlink($path2 . filter_naughty($_codename) . $suffix . '.tcp');
                // Can't leave this around, would cause problems
            }
        }
    }
    return $result;
}
Example #8
0
/**
 * Evaluate a conventional tempcode variable, handling escaping
 *
 * @param  LANGUAGE_NAME	The language to evaluate this symbol in (some symbols refer to language elements)
 * @param  array				Array of escaping operations
 * @param  integer			The type of symbol this is (TC_SYMBOL, TC_LANGUAGE_REFERENCE)
 * @set    0 2
 * @param  ID_TEXT			The name of the symbol
 * @param  array				Parameters to the symbol. For all but directive it is an array of strings. For directives it is an array of Tempcode objects. Actually there may be template-style parameters in here, as an influence of singular_bind and these may be Tempcode, but we ignore them.
 * @return mixed				The result. Either tempcode, or a string.
 */
function ecv($lang, $escaped, $type, $name, $param)
{
    global $TEMPCODE_SETGET, $CYCLES, $PREPROCESSABLE_SYMBOLS, $DISPLAYED_TITLE;
    //echo '<!--'.$name.'-->'."\n";
    if ($type == TC_SYMBOL) {
        $escaped_codes = $name . ($escaped == array() ? '' : serialize($escaped));
        $cacheable = $param == array() && !isset($GLOBALS['NON_CACHEABLE_SYMBOLS'][$name]);
        if ($cacheable) {
            global $SYMBOL_CACHE;
            if (isset($SYMBOL_CACHE[$escaped_codes])) {
                return $SYMBOL_CACHE[$escaped_codes];
            }
        }
        $value = '';
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($value);
        }
        $temp_array = array();
        if (isset($PREPROCESSABLE_SYMBOLS[$name]) && $name != 'PAGE_LINK') {
            handle_symbol_preprocessing(array($escaped, $type, $name, $param), $temp_array);
        }
        // Late preprocessing. Should not be needed in case of full screen output (as this was properly preprocessed), but is in other cases
        switch ($name) {
            case 'PAGE_LINK':
                if (isset($param[0])) {
                    list($zone, $map, $hash) = page_link_decode(is_object($param[0]) ? $param[0]->evaluate() : $param[0]);
                    $skip = NULL;
                    if (isset($param[4])) {
                        $skip = array_flip(explode('|', $param[4]));
                    }
                    $avoid_remap = isset($param[1]) && $param[1] == '1';
                    $skip_keep = isset($param[2]) && $param[2] == '1';
                    $keep_all = isset($param[3]) && $param[3] == '1';
                    foreach ($map as $key => $val) {
                        if (is_object($val)) {
                            $map[$key] = $val->evaluate();
                        }
                    }
                    $value = _build_url($map, $zone, $skip, $keep_all, $avoid_remap, $skip_keep, $hash);
                } else {
                    $value = get_zone_name() . ':' . get_page_name();
                    foreach ($_GET as $key => $val) {
                        if ($key == 'page') {
                            continue;
                        }
                        if (is_array($val)) {
                            continue;
                        }
                        if (substr($key, 0, 5) == 'keep_' && !skippable_keep($key, $val)) {
                            continue;
                        }
                        $value .= ':' . $key . '=' . $val;
                    }
                }
                break;
            case 'SET':
                if (isset($param[1])) {
                    if (isset($param[1]) && is_object($param[1])) {
                        $TEMPCODE_SETGET[$param[0]] = $param[1];
                    } else {
                        $param_copy = $param;
                        unset($param_copy[0]);
                        $TEMPCODE_SETGET[$param[0]] = implode(',', $param_copy);
                    }
                }
                break;
            case 'GET':
                if (isset($param[0])) {
                    if (isset($TEMPCODE_SETGET[$param[0]])) {
                        if (is_object($TEMPCODE_SETGET[$param[0]])) {
                            $TEMPCODE_SETGET[$param[0]] = $TEMPCODE_SETGET[$param[0]]->evaluate();
                        }
                        $value = $TEMPCODE_SETGET[$param[0]];
                    }
                }
                break;
            case 'EQ':
                if (isset($param[1])) {
                    $first = array_shift($param);
                    $count = 0;
                    foreach ($param as $test) {
                        if ($first == $test) {
                            $count++;
                            break;
                        }
                    }
                    $value = $count != 0 ? '1' : '0';
                }
                break;
            case 'NEQ':
                if (isset($param[1])) {
                    $first = array_shift($param);
                    $count = 0;
                    foreach ($param as $test) {
                        if ($first == $test) {
                            $count++;
                        }
                    }
                    $value = $count == 0 ? '1' : '0';
                }
                break;
            case 'NOT':
                if (isset($param[0])) {
                    $value = $param[0] == '1' || $param[0] == '1' ? '0' : '1';
                }
                break;
            case 'OR':
                $count = 0;
                foreach ($param as $test) {
                    if ($test == '1' || $test == '1') {
                        $count++;
                    }
                }
                $value = $count > 0 ? '1' : '0';
                break;
            case 'AND':
                $count = 0;
                foreach ($param as $test) {
                    if ($test == '1' || $test == '1') {
                        $count++;
                    }
                }
                $value = $count == count($param) ? '1' : '0';
                break;
            case 'HAS_ACTUAL_PAGE_ACCESS':
                if (isset($param[0])) {
                    $value = has_actual_page_access($param !== NULL && isset($param[2]) ? intval($param[2]) : get_member(), $param[0], isset($param[1]) ? $param[1] : NULL) ? '1' : '0';
                }
                break;
            case '?':
                if (isset($param[1])) {
                    $value = $param[0] == '1' || $param[0] == '1' ? $param[1] : (isset($param[2]) ? $param[2] : $value);
                }
                break;
            case 'IMG':
                if (isset($param[0]) && isset($GLOBALS['SITE_DB']) && function_exists('find_theme_image') && $GLOBALS['IN_MINIKERNEL_VERSION'] == 0) {
                    $value = find_theme_image($param[0], isset($param[3]) && $param[3] == '1', false, array_key_exists(2, $param) && $param[2] != '' ? $param[2] : NULL, NULL, isset($param[1]) && $param[1] == '1' ? $GLOBALS['FORUM_DB'] : $GLOBALS['SITE_DB']);
                }
                break;
            case '':
                break;
            case 'META_DATA':
                if (isset($param[0])) {
                    global $META_DATA;
                    if (isset($param[1])) {
                        $matches = array();
                        if ($param[0] == 'image' && preg_match('#^' . preg_quote(find_script('attachment'), '#') . '\\?id=(\\d+)#', $param[1], $matches) != 0) {
                            require_code('attachments');
                            if (!has_attachment_access($GLOBALS['FORUM_DRIVER']->get_guest_id(), intval($matches[1]))) {
                                break;
                            }
                        }
                        $META_DATA[$param[0]] = $param[1];
                    } else {
                        $value = isset($META_DATA[$param[0]]) ? strip_comcode($META_DATA[$param[0]]) : '';
                        if ($value === NULL) {
                            $value = '';
                        }
                    }
                }
                break;
            case 'SPECIAL_CLICK_TO_EDIT':
                $_value = do_lang_tempcode('SPECIAL_CLICK_TO_EDIT');
                $value = $_value->evaluate();
                break;
            case 'KEEP':
                // What needs preserving in the URL
                $value = keep_symbol($param);
                break;
            case 'BROWSER':
                if (isset($param[1])) {
                    $q = false;
                    foreach (explode('|', $param[0]) as $browser) {
                        $q = browser_matches($browser);
                        if ($q) {
                            break;
                        }
                    }
                    $value = $q ? $param[1] : (isset($param[2]) ? $param[2] : '');
                    if ($GLOBALS['XSS_DETECT']) {
                        ocp_mark_as_escaped($value);
                    }
                }
                break;
            case 'JAVASCRIPT_INCLUDE':
                if (isset($param[0])) {
                    require_javascript($param[0]);
                    /*// Has to do this inline, as you're not allowed to reference scripts outside head
                    		if (!array_key_exists($param[0],$GLOBALS['JAVASCRIPTS']))
                    		{
                    			$GLOBALS['JAVASCRIPTS'][$param[0]]=1;
                    			$file=javascript_enforce($param[0]);
                    			$_value=do_template('JAVASCRIPT_NEED_INLINE',array('_GUID'=>'d6c907e26c5a8dd8c65f1d36a1a674a9','CODE'=>file_get_contents($file,FILE_TEXT)));
                    			$value=$_value->evaluate();
                    		}*/
                }
                break;
            case 'FACILITATE_AJAX_BLOCK_CALL':
                if (isset($param[0])) {
                    require_javascript('javascript_ajax');
                    require_code('blocks');
                    $_block_constraints = block_params_to_block_signature(block_params_str_to_arr($param[0]));
                    if (array_key_exists(1, $param)) {
                        $_block_constraints = array_merge($_block_constraints, block_params_str_to_arr($param[1]));
                        ksort($_block_constraints);
                    }
                    $block_constraints = block_params_arr_to_str($_block_constraints);
                    // Store permissions
                    $_auth_key = $GLOBALS['SITE_DB']->query_select('temp_block_permissions', array('id', 'p_time'), array('p_session_id' => get_session_id(), 'p_block_constraints' => $block_constraints), '', 1);
                    if (!array_key_exists(0, $_auth_key)) {
                        $auth_key = $GLOBALS['SITE_DB']->query_insert('temp_block_permissions', array('p_session_id' => get_session_id(), 'p_block_constraints' => $block_constraints, 'p_time' => time()), true);
                    } else {
                        $auth_key = $_auth_key[0]['id'];
                        if (time() - $_auth_key[0]['p_time'] > 100) {
                            $GLOBALS['SITE_DB']->query_update('temp_block_permissions', array('p_time' => time()), array('p_session_id' => get_session_id(), 'p_block_constraints' => $block_constraints), '', 1);
                        }
                    }
                    $keep = symbol_tempcode('KEEP');
                    $value = find_script('snippet') . '?snippet=block&auth_key=' . urlencode(strval($auth_key)) . '&block_map=' . urlencode($param[0]) . $keep->evaluate();
                }
                break;
            case 'LANG':
                $value = user_lang();
                break;
            case '_GET':
                if (isset($param[0])) {
                    $value = get_param($param[0], isset($param[1]) ? $param[1] : '', true);
                }
                break;
            case 'QUERY_STRING':
                $value = ocp_srv('QUERY_STRING');
                break;
            case 'USER_AGENT':
                $value = ocp_srv('HTTP_USER_AGENT');
                break;
            case 'STRIP_TAGS':
                if (isset($param[0])) {
                    if (isset($param[1]) && $param[1] == '1') {
                        $value = strip_tags(str_replace('))', ')', str_replace('((', '(', str_replace('<em>', '(', str_replace('</em>', ')', $param[0])))));
                    } else {
                        $value = strip_tags($param[0], array_key_exists(2, $param) ? $param[2] : '');
                    }
                    if (isset($param[1]) && $param[1] == '1') {
                        $value = @html_entity_decode($value, ENT_QUOTES, get_charset());
                    }
                }
                break;
            case 'CONFIG_OPTION':
                if (isset($param[0])) {
                    if (!isset($GLOBALS['OPTIONS'])) {
                        $value = '0';
                    } else {
                        $value = get_option($param[0], true);
                        if ($value === NULL) {
                            $value = '';
                        }
                    }
                }
                break;
            case 'TRUNCATE_LEFT':
                // Truncate the left length of a string. 0: text to truncate, 1: the truncate length, 2: whether to use a tooltip mouse-over if it is truncated, 3: whether it is encoded as HTML (0=no [default, plain-text], 1=yes)
                $value = symbol_truncator($param, 'left');
                break;
            case 'TRUNCATE_RIGHT':
                $value = symbol_truncator($param, 'right');
                break;
            case 'TRUNCATE_SPREAD':
                $value = symbol_truncator($param, 'spread');
                break;
            case 'TRUNCATE_EXPAND':
                $value = symbol_truncator($param, 'expand');
                break;
            case 'THEME':
                if (isset($GLOBALS['FORUM_DRIVER'])) {
                    $value = $GLOBALS['FORUM_DRIVER']->get_theme();
                } else {
                    $value = 'default';
                }
                break;
            case 'REVERSE':
                if (isset($param[0])) {
                    $value = implode(',', array_reverse(explode(',', $param[0])));
                }
                break;
            case 'COMMA_LIST_GET':
                if (isset($param[1])) {
                    require_code('blocks');
                    $values = block_params_str_to_arr($param[0]);
                    $value = isset($values[$param[1]]) ? $values[$param[1]] : '';
                }
                break;
            case 'COMMA_LIST_SET':
                if (isset($param[2])) {
                    require_code('blocks');
                    $values = block_params_str_to_arr($param[0]);
                    $values[$param[1]] = $param[2];
                    $value = block_params_arr_to_str($values);
                }
                break;
            case 'IS_EMPTY':
                if (isset($param[0])) {
                    $value = $param[0] == '' ? '1' : '0';
                }
                break;
            case 'IS_NON_EMPTY':
                if (isset($param[0])) {
                    $value = $param[0] != '' ? '1' : '0';
                }
                break;
            case 'CUSTOM_BASE_URL':
                $value = get_custom_base_url(isset($param[0]) && $param[0] != '' ? $param[0] == '1' : NULL);
                if (isset($param[1]) && $param[1] == '1') {
                    $value = cdn_filter($value);
                }
                break;
            case 'LOAD_PANEL':
                foreach ($param as $i => $p) {
                    if (is_object($p)) {
                        $param[$i] = $p->evaluate();
                    }
                }
                global $LOADED_PANELS;
                if (strpos($param[0], ':') !== false) {
                    $param = array_reverse(explode(':', $param[0], 2));
                }
                if (substr($param[0], 0, 6) == 'panel_') {
                    $param[0] = substr($param[0], 6);
                }
                $sr = serialize($param);
                $value = array_key_exists($sr, $LOADED_PANELS) ? $LOADED_PANELS[$sr] : '';
                break;
            case 'HAS_JS':
            case 'JS_ON':
                if (isset($param[1])) {
                    $value = has_js() ? $param[0] : $param[1];
                } else {
                    $value = has_js() ? '1' : '0';
                }
                break;
            case 'BASE_URL_NOHTTP':
                $value = preg_replace('#^https?://[^/]+#', '', get_base_url());
                if (substr($value, 0, 2) == '//') {
                    $value = substr($value, 1);
                }
                if (!$GLOBALS['DEBUG_MODE']) {
                    break;
                }
                // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            case 'CUSTOM_BASE_URL_NOHTTP':
                $value = preg_replace('#^https?://[^/]+/#', '/', get_custom_base_url());
                if (substr($value, 0, 2) == '//') {
                    $value = substr($value, 1);
                }
                if (!$GLOBALS['DEBUG_MODE']) {
                    break;
                }
                // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            case 'BASE_URL':
                $value = get_base_url(isset($param[0]) ? $param[0] == '1' : NULL);
                break;
            case 'ZONE':
                $value = get_zone_name();
                break;
            case 'PAGE':
                $value = get_page_name();
                break;
            case 'SITE_NAME':
                $value = get_site_name();
                break;
            case 'HEADER_TEXT':
                global $ZONE;
                $value = $ZONE['zone_header_text_trans'];
                break;
            case 'PANEL_WIDTH':
                if (isset($TEMPCODE_SETGET['PANEL_WIDTH']) && $TEMPCODE_SETGET['PANEL_WIDTH'] != '') {
                    $value = $TEMPCODE_SETGET['PANEL_WIDTH'];
                } else {
                    $value = get_option('panel_width', true);
                    if ($value === NULL) {
                        $value = '13.3em';
                    }
                }
                break;
            case 'PANEL_WIDTH_SPACED':
                if (isset($TEMPCODE_SETGET['PANEL_WIDTH_SPACED']) && $TEMPCODE_SETGET['PANEL_WIDTH_SPACED'] != '') {
                    $value = $TEMPCODE_SETGET['PANEL_WIDTH_SPACED'];
                } else {
                    $value = get_option('panel_width_spaced', true);
                    if (is_null($value)) {
                        $value = '14.3em';
                    }
                }
                break;
            case 'TRIM':
                if (isset($param[0])) {
                    $value = preg_replace(array('#^\\s+#', '#^(<br\\s*/?' . '>\\s*)+#', '#^(&nbsp;)+#', '#\\s+$#', '#(<br\\s*/?' . '>\\s*)+$#', '#(&nbsp;)+$#'), array('', '', '', '', '', ''), $param[0]);
                }
                break;
            case 'CPF_VALUE':
                if (isset($param[0])) {
                    if (is_numeric($param[0])) {
                        require_code('ocf_members');
                        $fields = ocf_get_custom_fields_member(isset($param[1]) ? intval($param[1]) : get_member());
                        if (array_key_exists(intval($param[0]), $fields)) {
                            $_value = $fields[intval($param[0])];
                        }
                    } elseif (substr($param[0], 0, 2) == 'm_' && strpos(strtolower($param[0]), 'hash') === false && strpos(strtolower($param[0]), 'salt') === false) {
                        $_value = $GLOBALS['FORUM_DRIVER']->get_member_row_field(isset($param[1]) ? intval($param[1]) : get_member(), $param[0]);
                    } else {
                        $_value = get_ocp_cpf($param[0], isset($param[1]) ? intval($param[1]) : NULL);
                    }
                    if (!is_string($_value)) {
                        $value = is_null($_value) ? '' : strval($_value);
                    } else {
                        $value = $_value;
                    }
                }
                break;
            case 'BANNER':
                if (addon_installed('banners')) {
                    global $SITE_INFO;
                    $is_on_banners = get_option('is_on_banners') == '1' && (!has_specific_permission(get_member(), 'banner_free') || $GLOBALS['FORUM_DRIVER']->is_super_admin(get_member()) && get_option('admin_banners') == '1' || !is_null($GLOBALS['CURRENT_SHARE_USER']));
                    if (array_key_exists('throttle_bandwidth_registered', $SITE_INFO)) {
                        $views_till_now = intval(get_value('page_views'));
                        $bandwidth_allowed = $SITE_INFO['throttle_bandwidth_registered'];
                        $total_bandwidth = intval(get_value('download_bandwidth'));
                        if ($bandwidth_allowed * 1024 * 1024 >= $total_bandwidth) {
                            $is_on_banners = false;
                        }
                    }
                    if ($is_on_banners && !is_page_https(get_zone_name(), get_page_name())) {
                        require_code('banners');
                        $b_type = isset($param[0]) ? $param[0] : '';
                        $internal_only = isset($param[1]) ? intval($param[1]) : ($b_type == '' ? 0 : 1);
                        if (isset($GLOBALS['NON_CACHEABLE_SYMBOLS']['SET_RAND'])) {
                            $_value = banners_script(true, '', '', $b_type, $internal_only, '');
                            $value = $_value->evaluate();
                        } else {
                            $value = 'Banner goes here';
                        }
                    }
                }
                break;
            case 'AVATAR':
                $value = $GLOBALS['FORUM_DRIVER']->get_member_avatar_url(isset($param[0]) ? intval($param[0]) : get_member());
                if (url_is_local($value) && $value != '') {
                    $value = get_custom_base_url() . '/' . $value;
                }
                break;
            case 'IS_GUEST':
                if (isset($param[0])) {
                    $value = is_guest(intval($param[0])) ? '1' : '0';
                } else {
                    $value = is_guest() ? '1' : '0';
                }
                break;
            case 'MEMBER':
                $value = strval(get_member());
                break;
            case 'USER':
                if (!isset($param[0])) {
                    $value = strval(get_member());
                } else {
                    $member_id = $GLOBALS['FORUM_DRIVER']->get_member_from_username($param[0]);
                    $value = is_null($member_id) ? '' : strval($member_id);
                }
                break;
            case 'CSS_INCLUDE':
                if (isset($param[0])) {
                    require_css($param[0]);
                    /*// Has to do this inline, as you're not allowed to reference sheets outside head
                    		if (!array_key_exists($param[0],$GLOBALS['CSSS']))
                    		{
                    			$GLOBALS['CSSS'][$param[0]]=1;
                    			$file=css_enforce($param[0]);
                    			$_value=do_template('CSS_NEED_INLINE',array('_GUID'=>'9de994d2f6d47a622d49347feb7ebe96','CSS'=>str_replace('../../../../',get_base_url().'/',file_get_contents($file,FILE_TEXT))));
                    			$value=$_value->evaluate();
                    		}*/
                }
                break;
            case 'USER_OVERIDE':
                $value = get_param('id', '');
                if (!is_numeric($value) || $value == '') {
                    $value = strval(get_member());
                }
                break;
            case 'IS_HTTPAUTH_LOGIN':
                $value = is_httpauth_login() ? '1' : '0';
                break;
            case 'MEMBER_PROFILE_LINK':
                $value = $GLOBALS['FORUM_DRIVER']->member_profile_url(!is_null($param) && isset($param[0]) ? intval($param[0]) : get_member(), false, true);
                if (is_null($value)) {
                    $value = '';
                }
                break;
            case 'USERNAME':
                $value = $GLOBALS['FORUM_DRIVER']->get_username(!is_null($param) && isset($param[0]) ? intval($param[0]) : get_member());
                if (is_null($value)) {
                    $value = do_lang('UNKNOWN');
                }
                break;
            case 'CYCLE':
                if (isset($param[0])) {
                    if (!isset($CYCLES[$param[0]])) {
                        $CYCLES[$param[0]] = 0;
                    }
                    if (!isset($param[1])) {
                        $value = strval($CYCLES[$param[0]]);
                    } else {
                        if (count($param) == 2) {
                            $param = array_merge(array($param[0]), explode(',', $param[1]));
                        }
                        ++$CYCLES[$param[0]];
                        if (!array_key_exists($CYCLES[$param[0]], $param)) {
                            $CYCLES[$param[0]] = 1;
                        }
                        $value = $param[$CYCLES[$param[0]]];
                    }
                }
                break;
            case 'THUMBNAIL':
                require_code('images');
                $value = _symbol_thumbnail($param);
                break;
            case 'IMAGE_WIDTH':
                require_code('images');
                list($value, ) = _symbol_image_dims($param);
                break;
            case 'IMAGE_HEIGHT':
                require_code('images');
                list(, $value) = _symbol_image_dims($param);
                break;
            case 'IS_IN_GROUP':
                if (isset($param[0])) {
                    if (in_array($param[count($param) - 1], array('', 'primary', 'secondary'))) {
                        $last_param = $param[count($param) - 1];
                        unset($param[count($param) - 1]);
                    } else {
                        $last_param = '';
                    }
                    $member_id = get_member();
                    $new_param = '';
                    $param_2 = array();
                    foreach ($param as $group) {
                        if (substr($group, 0, 1) == '!' && is_numeric(substr($group, 1))) {
                            $member_id = intval(substr($group, 1));
                        } else {
                            $param_2 = array_merge($param_2, explode(',', $group));
                        }
                    }
                    foreach ($param_2 as $group) {
                        if ($new_param != '') {
                            $new_param .= ',';
                        }
                        $new_param .= $group;
                    }
                    if ($last_param == 'primary') {
                        $member_row = $GLOBALS['FORUM_DRIVER']->get_member_row($member_id);
                        $real_group_list = array($GLOBALS['FORUM_DRIVER']->pname_group($member_row));
                    } elseif ($last_param == 'secondary') {
                        $real_group_list = $GLOBALS['FORUM_DRIVER']->get_members_groups($member_id);
                        $member_row = $GLOBALS['FORUM_DRIVER']->get_member_row($member_id);
                        $real_group_list = array_diff($real_group_list, array($GLOBALS['FORUM_DRIVER']->pname_group($member_row)));
                    } else {
                        $real_group_list = $GLOBALS['FORUM_DRIVER']->get_members_groups($member_id);
                    }
                    require_code('ocfiltering');
                    $value = count(array_intersect(ocfilter_to_idlist_using_memory($new_param, $GLOBALS['FORUM_DRIVER']->get_usergroup_list()), $real_group_list)) != 0 ? '1' : '0';
                }
                break;
            case 'IS_STAFF':
                if (isset($GLOBALS['FORUM_DRIVER'])) {
                    $value = $GLOBALS['FORUM_DRIVER']->is_staff(!is_null($param) && isset($param[0]) ? intval($param[0]) : get_member()) ? '1' : '0';
                } else {
                    $value = '0';
                }
                break;
            case 'IS_SUPER_ADMIN':
                if (isset($GLOBALS['FORUM_DRIVER'])) {
                    $value = $GLOBALS['FORUM_DRIVER']->is_super_admin(!is_null($param) && isset($param[0]) ? intval($param[0]) : get_member()) ? '1' : '0';
                } else {
                    $value = '0';
                }
                break;
            case 'PHOTO':
                if (isset($param[0])) {
                    $value = $GLOBALS['FORUM_DRIVER']->get_member_photo_url(intval($param[0]));
                    if (url_is_local($value) && $value != '') {
                        $value = get_custom_base_url() . '/' . $value;
                    }
                }
                break;
            case 'OCF_RANK_IMAGE':
                if (addon_installed('ocf_forum')) {
                    require_code('ocf_groups');
                    $rank_images = new ocp_tempcode();
                    $member_id = isset($param[0]) ? intval($param[0]) : get_member();
                    $posters_groups = $GLOBALS['FORUM_DRIVER']->get_members_groups($member_id, true);
                    foreach ($posters_groups as $group) {
                        $rank_image = ocf_get_group_property($group, 'rank_image');
                        $group_leader = ocf_get_group_property($group, 'group_leader');
                        $group_name = ocf_get_group_name($group);
                        $rank_image_pri_only = ocf_get_group_property($group, 'rank_image_pri_only');
                        if ($rank_image != '' && ($rank_image_pri_only == 0 || $group == $GLOBALS['FORUM_DRIVER']->get_member_row_field($member_id, 'm_primary_group'))) {
                            $rank_images->attach(do_template('OCF_RANK_IMAGE', array('USERNAME' => $GLOBALS['FORUM_DRIVER']->get_username($member_id), 'GROUP_NAME' => $group_name, 'IMG' => $rank_image, 'IS_LEADER' => $group_leader == $member_id)));
                        }
                    }
                    $value = $rank_images->evaluate();
                }
                break;
            case 'TOTAL_POINTS':
                if (addon_installed('points')) {
                    require_code('points');
                    $value = strval(total_points(isset($param[0]) ? intval($param[0]) : get_member()));
                }
                break;
            case 'POINTS_USED':
                if (addon_installed('points')) {
                    require_code('points');
                    $value = strval(points_used(isset($param[0]) ? intval($param[0]) : get_member()));
                }
                break;
            case 'AVAILABLE_POINTS':
                if (addon_installed('points')) {
                    require_code('points');
                    $value = strval(available_points(isset($param[0]) ? intval($param[0]) : get_member()));
                }
                break;
            case 'URL_FOR_GET_FORM':
                if (isset($param[0])) {
                    $url_bits = parse_url($param[0]);
                    if (array_key_exists('scheme', $url_bits)) {
                        $value = $url_bits['scheme'] . '://' . (array_key_exists('host', $url_bits) ? $url_bits['host'] : 'localhost');
                        if (array_key_exists('port', $url_bits) && $url_bits['port'] != 80) {
                            $value .= ':' . strval($url_bits['port']);
                        }
                    }
                    if (array_key_exists('path', $url_bits)) {
                        $value .= $url_bits['path'];
                    }
                }
                break;
            case 'HIDDENS_FOR_GET_FORM':
                $_value = new ocp_tempcode();
                $url_bits = parse_url($param[0]);
                if (array_key_exists('query', $url_bits) && $url_bits['query'] != '') {
                    foreach (explode('&', $url_bits['query']) as $exp) {
                        $parts = explode('=', $exp, 2);
                        if (count($parts) == 2) {
                            if (!in_array($parts[0], $param)) {
                                $_value->attach(form_input_hidden($parts[0], urldecode($parts[1])));
                            }
                        }
                    }
                }
                $value = $_value->evaluate();
                break;
            case 'NOTIFICATIONS_ENABLED':
                $value = '';
                if (array_key_exists(0, $param)) {
                    require_code('notifications');
                    $value = notifications_enabled(array_key_exists(1, $param) ? $param[1] : get_page_name(), $param[0]) ? '1' : '0';
                }
                break;
            case 'DOCUMENT_HELP':
                global $DOCUMENT_HELP, $HELPER_PANEL_TUTORIAL;
                $value = $DOCUMENT_HELP;
                if ($value == '' && $HELPER_PANEL_TUTORIAL != '') {
                    $value = brand_base_url() . '/docs' . strval(ocp_version()) . '/pg/' . $HELPER_PANEL_TUTORIAL;
                }
                break;
            case 'HTTP_STATUS_CODE':
                global $HTTP_STATUS_CODE;
                $value = $HTTP_STATUS_CODE;
                break;
            case 'TEMPCODE':
                if (isset($param[0])) {
                    require_code('tempcode_compiler');
                    $_value = template_to_tempcode($param[0]);
                    $value = $_value->evaluate();
                }
                break;
            case 'COMCODE':
                if (isset($param[0])) {
                    $_value = comcode_to_tempcode($param[0], NULL, true);
                    $value = $_value->evaluate();
                }
                break;
            case 'FLAGRANT':
                $_value = get_flagrant();
                $value = $_value->evaluate();
                break;
            case 'IMG_WIDTH':
            case 'IMG_HEIGHT':
                if (isset($param[0]) && isset($GLOBALS['SITE_DB']) && function_exists('find_theme_image') && $GLOBALS['IN_MINIKERNEL_VERSION'] == 0) {
                    global $THEME_IMG_DIMS_CACHE;
                    if (!isset($THEME_IMG_DIMS_CACHE)) {
                        $THEME_IMG_DIMS_CACHE = function_exists('persistant_cache_get') ? persistant_cache_get('THEME_IMG_DIMS') : array();
                    }
                    if (isset($THEME_IMG_DIMS_CACHE[$param[0]])) {
                        list($width, $height) = $THEME_IMG_DIMS_CACHE[$param[0]];
                        $value = $name == 'IMG_WIDTH' ? $width : $height;
                    } else {
                        if (strpos($param[0], '://') === false) {
                            $img_url = find_theme_image($param[0], false, false, array_key_exists(2, $param) ? $param[2] : NULL, NULL, isset($param[1]) && $param[1] == '1' ? $GLOBALS['FORUM_DB'] : $GLOBALS['SITE_DB']);
                        } else {
                            $img_url = $param[0];
                        }
                        require_code('images');
                        list($width, $height) = _symbol_image_dims(array($img_url));
                        $value = $name == 'IMG_WIDTH' ? $width : $height;
                        $THEME_IMG_DIMS_CACHE[$param[0]] = array($width, $height);
                        if (function_exists('persistant_cache_set')) {
                            persistant_cache_set('THEME_IMG_DIMS', $THEME_IMG_DIMS_CACHE);
                        }
                    }
                }
                break;
            case 'CLEAN_FILE_SIZE':
                if (isset($param[0])) {
                    $bytes = is_numeric($param[0]) ? intval($param[0]) : NULL;
                    require_code('files');
                    $value = clean_file_size($bytes);
                }
                break;
            case 'TIME_PERIOD':
                if (isset($param[0])) {
                    $value = display_time_period(intval($param[0]));
                }
                break;
            case 'MAKE_RELATIVE_DATE':
                if (isset($param[0])) {
                    if (get_option('use_contextual_dates') == '0' && (!array_key_exists(1, $param) || $param[1] != '1')) {
                        $value = get_timezoned_date(intval($param[0]));
                    } else {
                        $value = display_time_period(time() - intval($param[0]));
                    }
                }
                break;
            case 'TIMEZONE':
                $value = make_nice_timezone_name(get_site_timezone());
                break;
            case 'LOAD_PAGE':
                foreach ($param as $i => $p) {
                    if (is_object($p)) {
                        $param[$i] = $p->evaluate();
                    }
                }
                global $LOADED_PAGES;
                if (strpos($param[0], ':') !== false) {
                    $param = array_reverse(explode(':', $param[0], 2));
                }
                $_value = $LOADED_PAGES[serialize($param)];
                $value = $_value->evaluate();
                break;
            case 'RUNNING_SCRIPT':
                if (isset($param[0])) {
                    $value = running_script($param[0]) ? '1' : '0';
                }
                break;
            case 'MATCH_KEY_MATCH':
                $value = '0';
                foreach ($param as $match_key) {
                    if ($match_key == '1' || $match_key == '0' || $match_key == '') {
                        continue;
                    }
                    if (match_key_match($match_key, isset($param[1]) && $match_key == '1')) {
                        $value = '1';
                    }
                }
                break;
            case 'VERSION':
                $value = strval(ocp_version());
                break;
            case 'PREVIEW_VALIDATION':
                $value = get_option('is_on_preview_validation') == '1' ? '1' : '0';
                break;
            case 'BLOCK':
                if (isset($GLOBALS['NON_CACHEABLE_SYMBOLS']['SET_RAND'])) {
                    foreach ($param as $i => $p) {
                        if (is_object($p)) {
                            $param[$i] = $p->evaluate();
                        }
                    }
                    if (count($param) == 1 && strpos($param[0], ',') !== false) {
                        $param = preg_split('#((?<!\\\\)|(?<=\\\\\\\\)|(?<=^)),#', $param[0]);
                        foreach ($param as $key => $val) {
                            $param[$key] = str_replace('\\,', ',', $val);
                        }
                    }
                    global $LOADED_BLOCKS;
                    if (isset($LOADED_BLOCKS[serialize($param)])) {
                        // Will always be set
                        $value = $LOADED_BLOCKS[serialize($param)]->evaluate();
                    }
                }
                break;
            case 'CURRENCY':
                if (addon_installed('ecommerce')) {
                    if (isset($param[0])) {
                        require_code('currency');
                        $value = currency_convert(floatval(str_replace(',', '', $param[0])), isset($param[1]) && $param[1] != '' ? $param[1] : get_option('currency'), isset($param[2]) && $param[2] != '' ? $param[2] : NULL, isset($param[3]) && $param[3] == '1');
                        if (is_null($value)) {
                            $value = do_lang('INTERNAL_ERROR');
                        }
                    } else {
                        $value = get_option('currency');
                    }
                }
                break;
            case 'CURRENCY_SYMBOL':
                if (addon_installed('ecommerce')) {
                    require_code('ecommerce');
                    $value = ecommerce_get_currency_symbol();
                }
                break;
            case 'GEOLOCATE':
                $value = geolocate_ip(isset($param[0]) ? $param[0] : NULL);
                break;
            case 'NO_SAFE_MODE':
                $value = str_replace(array('on', 'true', 'yes'), array('1', '1', '1'), strtolower(ini_get('safe_mode'))) == '1' ? '0' : '1';
                break;
            case 'FORCE_PREVIEWS':
                if (get_option('forced_preview_option') == '1') {
                    if (get_forum_type() == 'ocf') {
                        if (is_guest() && get_option('default_preview_guests') == '0') {
                            $value = '0';
                        } else {
                            $value = $GLOBALS['FORUM_DRIVER']->get_member_row_field(get_member(), 'm_preview_posts') == 1 ? '1' : '0';
                        }
                    } else {
                        $value = get_option('default_preview_guests') == '0' ? '0' : '1';
                    }
                } else {
                    $value = '0';
                }
                break;
            case 'PREVIEW_URL':
                $value = find_script('preview');
                $value .= '?page=' . get_page_name();
                $value .= '&type=' . get_param('type', '', true);
                break;
            case 'ADDON_INSTALLED':
                if (isset($param[0]) && !running_script('install')) {
                    $value = addon_installed($param[0]) ? '1' : '0';
                }
                break;
            case 'VALUE_OPTION':
                if (isset($param[0])) {
                    $value = function_exists('get_value') ? get_value($param[0]) : '';
                    if (is_null($value)) {
                        $value = function_exists('get_long_value') ? get_long_value($param[0]) : '';
                        if (is_null($value)) {
                            $value = isset($param[1]) ? $param[1] : '';
                            if ($param[0] == 'textmate' && (ocp_srv('HTTP_HOST') == 'localhost' && strpos(ocp_srv('HTTP_USER_AGENT'), 'Macintosh') !== false)) {
                                $value = '1';
                            }
                        }
                    }
                }
                break;
            case 'KEEP_INDEX':
                // What needs preserving in the URL
                $value = 'index.php';
                if (count($_GET) > 0) {
                    foreach ($_GET as $key => $val) {
                        if (is_array($val)) {
                            continue;
                        }
                        if (get_magic_quotes_gpc()) {
                            $val = stripslashes($val);
                        }
                        if (substr($key, 0, 5) == 'keep_' && !skippable_keep($key, $val) && strpos($key, '_expand_') === false) {
                            $value .= ($value == 'index.php' ? '?' : '&') . urlencode($key) . '=' . ocp_url_encode($val);
                        }
                    }
                }
                break;
            case 'HIDE_HELP_PANEL':
                $value = array_key_exists('hide_help_panel', $_COOKIE) && $_COOKIE['hide_help_panel'] == '1' ? '1' : '0';
                break;
            case 'URLISE_LANG':
                if (isset($param[1])) {
                    $_value = urlise_lang($param[0], $param[1], isset($param[2]) ? $param[2] : '', isset($param[3]) ? $param[3] == '1' : false);
                    $value = $_value->evaluate();
                }
                break;
            case 'FIND_SCRIPT_NOHTTP':
                if (isset($param[0]) && function_exists('find_script')) {
                    $value = preg_replace('#^https?://[^/]+#', '', find_script($param[0], false, isset($param[1]) ? intval($param[1]) : 0));
                }
                if (!$GLOBALS['DEBUG_MODE']) {
                    break;
                }
                // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            // Debug mode changes base domain so we need to actually use it in full (fine, we don't have HTTPS in debug mode). Bubble on...
            case 'FIND_SCRIPT':
                if (isset($param[0]) && function_exists('find_script')) {
                    $value = find_script($param[0], false, isset($param[1]) ? intval($param[1]) : 0);
                }
                break;
            case 'MOBILE':
                $value = is_mobile(NULL, array_key_exists(0, $param) ? $param[0] == '1' : false) ? '1' : '0';
                break;
            case 'VALID_FILE_TYPES':
                $value = get_option('valid_types');
                $types = array_flip(explode(',', $value));
                $value = '';
                ksort($types);
                foreach (array_flip($types) as $val) {
                    $value .= $val . ',';
                }
                $value = substr($value, 0, strlen($value) - 1);
                break;
            case 'BROWSER_UA':
                $browser = get_browser_string();
                $value = $browser;
                break;
            case 'OS':
                $os = get_os_string();
                if (is_null($os)) {
                    $os = '';
                }
                $value = $os;
                break;
            case 'ANCHOR':
                if (isset($param[0])) {
                    $_value = do_template('ANCHOR', array('_GUID' => '8795c70c9dd7c6217bb765264ac24092', 'NAME' => $param[0]));
                    $value = $_value->evaluate();
                }
                break;
            case 'CSS_TEMPCODE':
                $_value = css_tempcode();
                $value = $_value->evaluate();
                break;
            case 'JS_TEMPCODE':
                $_value = javascript_tempcode(isset($param[0]) ? $param[0] : NULL);
                $value = $_value->evaluate();
                break;
            case 'PAD_LEFT':
                if (array_key_exists(1, $param)) {
                    $value = str_pad($param[0], intval($param[1]), array_key_exists(2, $param) ? $param[2] : '', STR_PAD_LEFT);
                }
                break;
            case 'PAD_RIGHT':
                if (array_key_exists(1, $param)) {
                    $value = str_pad($param[0], intval($param[1]), array_key_exists(2, $param) ? $param[2] : '', STR_PAD_RIGHT);
                }
                break;
            case 'PAGE_TITLE':
                $value = is_null($DISPLAYED_TITLE) ? '' : $DISPLAYED_TITLE->evaluate();
                break;
            case 'SET_TITLE':
                if (array_key_exists(0, $param)) {
                    get_page_title($param[0], false);
                }
                break;
            case 'EXTRA_HEAD':
                $_value = $GLOBALS['EXTRA_HEAD'];
                if ($_value === NULL) {
                    $_value = new ocp_tempcode();
                }
                $value = $_value->evaluate();
                break;
            case 'EXTRA_FOOT':
                if ($GLOBALS['EXTRA_FOOT'] === NULL) {
                    $GLOBALS['EXTRA_FOOT'] = new ocp_tempcode();
                }
                $_value = $GLOBALS['EXTRA_FOOT'];
                if (array_key_exists(0, $param)) {
                    $GLOBALS['EXTRA_FOOT']->attach($param[0]);
                } else {
                    $value = $_value->evaluate();
                }
                break;
            case 'RAND':
                if (isset($GLOBALS['NON_CACHEABLE_SYMBOLS']['RAND'])) {
                    $GLOBALS['NO_EVAL_CACHE'] = true;
                    $value = strval(mt_rand(0, 32000));
                } else {
                    $value = '4';
                }
                break;
            case 'SET_RAND':
                if (isset($param[0])) {
                    if (isset($GLOBALS['NON_CACHEABLE_SYMBOLS']['SET_RAND'])) {
                        $GLOBALS['NO_EVAL_CACHE'] = true;
                        $value = $param[mt_rand(0, count($param) - 1)];
                    } else {
                        $value = $param[0];
                    }
                }
                break;
            case 'COPYRIGHT':
                $value = str_replace('$CURRENT_YEAR', date('Y'), get_option('copyright'));
                break;
            case 'KEYWORDS_SPACED':
                $value = str_replace(',', ' ', get_option('keywords'));
                break;
            case 'STAFF_ADDRESS_PURE':
                $value = get_option('staff_address');
                break;
            case 'STAFF_ADDRESS':
                require_code('obfuscate');
                $value = obfuscate_email_address(get_option('staff_address'));
                break;
            case 'DOMAIN':
                $value = get_domain();
                break;
            case 'BRAND_NAME':
                $value = function_exists('get_value') ? get_value('rebrand_name') : NULL;
                if (is_null($value)) {
                    $value = 'ocPortal';
                }
                break;
            case 'BRAND_BASE_URL':
                $value = brand_base_url();
                break;
            case 'SHOW_DOCS':
                $value = get_option('show_docs') === '0' ? '0' : '1';
                break;
            case 'MEMBER_EMAIL':
                $value = $GLOBALS['FORUM_DRIVER']->get_member_email_address(isset($param[0]) ? intval($param[0]) : get_member());
                break;
            case 'OCF_MEMBER_HTML':
                if (get_forum_type() == 'ocf') {
                    require_code('ocf_members');
                    require_code('ocf_members2');
                    $_value = ocf_show_member_box(isset($param[0]) ? intval($param[0]) : get_member());
                    $value = $_value->evaluate();
                }
                break;
            case 'HAS_SPECIFIC_PERMISSION':
                if (isset($param[0])) {
                    $value = has_specific_permission(!is_null($param) && isset($param[1]) ? intval($param[1]) : get_member(), $param[0]) ? '1' : '0';
                }
                break;
            case 'HAS_ZONE_ACCESS':
                if (isset($param[0])) {
                    $value = has_zone_access(!is_null($param) && isset($param[1]) ? intval($param[1]) : get_member(), $param[0]) ? '1' : '0';
                }
                break;
            case 'HAS_PAGE_ACCESS':
                if (isset($param[0]) && isset($param[1])) {
                    $value = has_page_access(!is_null($param) && isset($param[2]) ? intval($param[2]) : get_member(), $param[0], $param[1], !is_null($param) && isset($param[3]) ? $param[3] == '1' : false) ? '1' : '0';
                }
                break;
            case 'HAS_CATEGORY_ACCESS':
                if (isset($param[0])) {
                    $value = has_category_access(!is_null($param) && isset($param[2]) ? intval($param[2]) : get_member(), $param[0], $param[1]) ? '1' : '0';
                }
                break;
            case 'HAS_ATTACHMENT_ACCESS':
                if (isset($param[0])) {
                    require_code('attachments');
                    $value = has_attachment_access(!is_null($param) && isset($param[1]) ? intval($param[1]) : get_member(), $param[0]) ? '1' : '0';
                }
                break;
            case 'HAS_SUBMIT_PERMISSION':
                if (isset($param[0]) && (strtolower($param[0]) == 'low' || strtolower($param[0]) == 'mid' || strtolower($param[0]) == 'high')) {
                    $value = has_submit_permission(strtolower($param[0]), !is_null($param) && isset($param[1]) ? intval($param[1]) : get_member(), !is_null($param) && isset($param[2]) ? $param[2] : get_ip_address(), !is_null($param) && isset($param[3]) ? $param[3] : get_page_name()) ? '1' : '0';
                }
                break;
            case 'HAS_DELETE_PERMISSION':
                if (isset($param[0]) && (strtolower($param[0]) == 'low' || strtolower($param[0]) == 'mid' || strtolower($param[0]) == 'high') && isset($param[1])) {
                    $value = has_delete_permission(strtolower($param[0]), !is_null($param) && isset($param[2]) ? intval($param[2]) : get_member(), intval($param[1]), !is_null($param) && isset($param[3]) ? $param[3] : get_page_name()) ? '1' : '0';
                }
                break;
            case 'HAS_EDIT_PERMISSION':
                if (isset($param[0]) && (strtolower($param[0]) == 'low' || strtolower($param[0]) == 'mid' || strtolower($param[0]) == 'high') && isset($param[1])) {
                    $value = has_edit_permission(strtolower($param[0]), !is_null($param) && isset($param[2]) ? intval($param[2]) : get_member(), intval($param[1]), !is_null($param) && isset($param[3]) ? $param[3] : get_page_name()) ? '1' : '0';
                }
                break;
            case 'ENTITY_DECODE':
                if (isset($param[0])) {
                    $value = @html_entity_decode($param[0], ENT_QUOTES, get_charset());
                }
                break;
            case 'RESET_CYCLE':
                if (isset($param[0])) {
                    $CYCLES[$param[0]] = 0;
                }
                break;
            case 'SITE_SCOPE':
                $value = get_option('site_scope');
                break;
            case 'LAST_VISIT_TIME':
                if (get_forum_type() == 'ocf') {
                    $member_info = ocf_read_in_member_profile(get_member(), true);
                    $value = strval($member_info['last_visit_time']);
                }
                break;
            case 'NUM_NEW_TOPICS':
                if (get_forum_type() == 'ocf') {
                    $member_info = ocf_read_in_member_profile(get_member(), true);
                    $_new_topics = $GLOBALS['FORUM_DB']->query('SELECT COUNT(*) AS mycnt FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_topics WHERE NOT t_forum_id IS NULL AND t_cache_first_time>' . strval((int) $member_info['last_visit_time']));
                    $new_topics = $_new_topics[0]['mycnt'];
                    $value = strval($new_topics);
                }
                break;
            case 'NUM_NEW_POSTS':
                if (get_forum_type() == 'ocf') {
                    $member_info = ocf_read_in_member_profile(get_member(), true);
                    $_new_posts = $GLOBALS['FORUM_DB']->query('SELECT COUNT(*) AS mycnt FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_posts WHERE NOT p_cache_forum_id IS NULL AND p_time>' . strval((int) $member_info['last_visit_time']));
                    $new_posts = $_new_posts[0]['mycnt'];
                    $value = strval($new_posts);
                }
                break;
            case 'HAS_FORUM':
                $value = has_no_forum() ? '0' : '1';
                break;
            case 'OCF':
                $value = get_forum_type() == 'ocf' ? '1' : '0';
                break;
            case 'BOARD_PREFIX':
                $value = get_forum_base_url();
                break;
            case 'DATE_AND_TIME':
                $use_contextual_dates = isset($param[0]) && $param[0] == '1';
                $verbose = isset($param[1]) && $param[1] == '1';
                $server_time = isset($param[2]) && $param[2] == '1';
                $time = isset($param[3]) ? intval($param[3]) : time();
                $value = get_timezoned_date($time, true, $verbose, $server_time, !$use_contextual_dates);
                break;
            case 'DATE':
                $use_contextual_dates = isset($param[0]) && $param[0] == '1';
                $verbose = isset($param[1]) && $param[1] == '1';
                $server_time = isset($param[2]) && $param[2] == '1';
                $time = isset($param[3]) ? intval($param[3]) : time();
                $value = get_timezoned_date($time, false, $verbose, $server_time, !$use_contextual_dates);
                break;
            case 'TIME':
                $time = isset($param[0]) ? intval($param[0]) : time();
                $value = get_timezoned_time($time);
                break;
            case 'SECONDS_PERIOD':
                if (array_key_exists(0, $param)) {
                    $value = display_seconds_period(intval($param[0]));
                }
                break;
            case 'FROM_TIMESTAMP':
                if (isset($param[0])) {
                    $timestamp = isset($param[1]) ? intval($param[1]) : time();
                    if (!array_key_exists(2, $param) || $param[2] == '1') {
                        $timestamp = utctime_to_usertime($timestamp);
                    }
                    $value = locale_filter(my_strftime($param[0], $timestamp));
                    if ($value == $param[0]) {
                        // If no conversion happened then the syntax must have been for 'date' not 'strftime'
                        $value = date($param[0], $timestamp);
                    }
                } else {
                    $timestamp = time();
                    $value = strval($timestamp);
                }
                break;
            case 'TO_TIMESTAMP':
                if (isset($param[0])) {
                    $value = strval(strtotime($param[0]));
                    if (array_key_exists(1, $param) && $param[1] == '1') {
                        $value = strval(usertime_to_utctime(intval($value)));
                    }
                    // '1' means date was in user-time so needs converting to a UTC timestamp
                } else {
                    $value = strval(time());
                }
                break;
            case 'SESSION_HASHED':
                $value = md5(strval(get_session_id()));
                break;
            case 'SESSION':
                $value = strval(get_session_id());
                break;
            case 'IN_ARRAY':
                if (isset($param[1])) {
                    $array = array_slice($param, 1);
                    $value = in_array($param[0], $array) ? '1' : '0';
                }
                break;
            case 'MULT':
                if (isset($param[1])) {
                    $value = float_to_raw_string(floatval($param[0]) * floatval($param[1]), 2, true);
                }
                break;
            case 'ROUND':
                if (isset($param[0])) {
                    $amount = isset($param[1]) ? intval($param[1]) : 0;
                    if ($amount > 0) {
                        $value = float_format(floatval($param[0]), $amount);
                    } else {
                        $value = strval(intval(round(floatval($param[0]), $amount)));
                    }
                }
                break;
            case 'DEV_MODE':
                $value = $GLOBALS['DEBUG_MODE'] ? '1' : '0';
                break;
            case 'BROWSER_MATCHES':
                if (isset($param[0])) {
                    $q = false;
                    foreach (explode('|', $param[0]) as $browser) {
                        $q = browser_matches($browser);
                        if ($q) {
                            break;
                        }
                    }
                    $value = $q ? '1' : '0';
                }
                break;
            case 'ISSET':
                if (isset($param[0])) {
                    $value = isset($TEMPCODE_SETGET[$param[0]]) ? '1' : '0';
                }
                break;
            case 'INIT':
                if (isset($param[1])) {
                    if (!isset($TEMPCODE_SETGET[$param[0]])) {
                        $TEMPCODE_SETGET[$param[0]] = $param[1];
                    }
                }
                break;
            case 'INC':
                if (isset($param[0])) {
                    if (!isset($TEMPCODE_SETGET[$param[0]])) {
                        $TEMPCODE_SETGET[$param[0]] = '0';
                    }
                    $TEMPCODE_SETGET[$param[0]] = strval(intval($TEMPCODE_SETGET[$param[0]]) + 1);
                }
                break;
            case 'DEC':
                if (isset($param[0])) {
                    if (!isset($TEMPCODE_SETGET[$param[0]])) {
                        $TEMPCODE_SETGET[$param[0]] = '0';
                    }
                    $TEMPCODE_SETGET[$param[0]] = strval(intval($TEMPCODE_SETGET[$param[0]]) - 1);
                }
                break;
            case 'PREG_MATCH':
                if (isset($param[1])) {
                    $value = preg_match('#' . str_replace('#', '\\#', $param[0]) . '#' . (isset($param[2]) ? str_replace('e', '', $param[2]) : ''), $param[1]) != 0 ? '1' : '0';
                }
                break;
            case 'PREG_REPLACE':
                if (isset($param[2])) {
                    $value = preg_replace('#' . str_replace('#', '\\#', $param[0]) . '#' . (isset($param[3]) ? str_replace('e', '', $param[3]) : ''), $param[1], $param[2]);
                }
                break;
            case 'MAX':
                if (isset($param[0])) {
                    $value = strval(max(intval($param[0]), intval($param[1])));
                }
                break;
            case 'MIN':
                if (isset($param[0])) {
                    $value = strval(min(intval($param[0]), intval($param[1])));
                }
                break;
            case 'MOD':
                if (isset($param[0])) {
                    $value = strval(max(intval($param[0]), -intval($param[0])));
                }
                break;
            case 'REM':
                if (isset($param[1])) {
                    $value = strval(intval($param[0]) % intval($param[1]));
                }
                break;
            case 'DIV_FLOAT':
                if (isset($param[1])) {
                    $value = float_to_raw_string(floatval($param[0]) / floatval($param[1]), 2, true);
                }
                break;
            case 'DIV':
                if (isset($param[1])) {
                    $value = strval(intval(floor(floatval($param[0]) / floatval($param[1]))));
                }
                break;
            case 'SUBTRACT':
                if (isset($param[1])) {
                    $value = float_to_raw_string(floatval(str_replace(',', '', $param[0])) - floatval(str_replace(',', '', $param[1])), 2, true);
                }
                break;
            case 'ADD':
                if (isset($param[1])) {
                    $value = float_to_raw_string(floatval(str_replace(',', '', $param[0])) + floatval(str_replace(',', '', $param[1])), 2, true);
                }
                break;
            case 'WCASE':
                if (isset($param[0])) {
                    $value = ucwords($param[0]);
                }
                break;
            case 'LCASE':
                if (isset($param[0])) {
                    $value = ocp_mb_strtolower($param[0]);
                }
                break;
            case 'UCASE':
                if (isset($param[0])) {
                    $value = ocp_mb_strtoupper($param[0]);
                }
                break;
            case '_POST':
                if (isset($param[0])) {
                    $value = post_param($param[0], isset($param[1]) ? $param[1] : '');
                }
                break;
            case 'REPLACE':
                if (isset($param[2])) {
                    $value = str_replace($param[0], $param[1], $param[2]);
                    if ($GLOBALS['XSS_DETECT'] && ocp_is_escaped($param[0])) {
                        ocp_mark_as_escaped($value);
                    }
                }
                break;
            case 'AT':
                if (isset($param[1])) {
                    $value = ocp_mb_substr($param[0], intval($param[1]), 1);
                }
                break;
            case 'STRPOS':
                if (isset($param[1])) {
                    $t_value = strpos($param[0], $param[1]);
                    $value = $t_value === false ? '0' : strval($t_value);
                }
                break;
            case 'IN_STR':
                if (isset($param[1])) {
                    if ($param[1] == '') {
                        $value = '0';
                    } else {
                        $value = '0';
                        foreach ($param as $i => $check) {
                            if (is_integer($i) && $i != 0 && $check != '') {
                                if (strpos($param[0], $check) !== false) {
                                    $value = '1';
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
            case 'SUBSTR_COUNT':
                if (isset($param[1])) {
                    $value = strval(substr_count($param[0], $param[1]));
                }
                break;
            case 'SUBSTR':
                if (isset($param[1])) {
                    $value = ocp_mb_substr($param[0], intval($param[1]), isset($param[2]) ? intval($param[2]) : strlen($param[0]));
                }
                break;
            case 'LENGTH':
                if (isset($param[0])) {
                    $value = strval(ocp_mb_strlen($param[0]));
                }
                break;
            case 'WORDWRAP':
                if (isset($param[1])) {
                    $cut = isset($param[3]) && $param[3] == '1';
                    $value = wordwrap($param[0], intval($param[1]), isset($param[2]) ? $param[2] : '<br />', $cut);
                    if ($GLOBALS['XSS_DETECT'] && ocp_is_escaped($param[0])) {
                        ocp_mark_as_escaped($value);
                    }
                }
                break;
            case 'ALTERNATOR_TRUNCATED':
                // Alternate values according to whether some given text WOULD have been truncated. 0: text to check against, 1: the truncate length, 2:IF would not be do this, 3: if it would be do this, 4: whether given text is encoded as HTML (0=no [default, plain-text], 1=yes)
                if (isset($param[3])) {
                    $amount = intval($param[1]);
                    $is_html = isset($param[4]) && $param[4] == '1';
                    if (strlen($is_html ? strip_tags($param[0]) : $param[0]) > $amount) {
                        $value = $param[3];
                    } else {
                        $value = $param[2];
                    }
                }
                break;
            case 'ESCAPE':
                if (isset($param[0])) {
                    $d_escaping = array(isset($param[1]) ? constant($param[1]) : ENTITY_ESCAPED);
                    if (is_string($param[0])) {
                        apply_tempcode_escaping($d_escaping, $param[0]);
                    }
                    $value = $param[0];
                }
                break;
            case 'COOKIE_PATH':
                $value = function_exists('get_cookie_path') ? get_cookie_path() : '/';
                break;
            case 'COOKIE_DOMAIN':
                $s_value = function_exists('get_cookie_domain') ? get_cookie_domain() : '';
                $value = is_null($s_value) ? '' : $s_value;
                break;
            case 'IS_A_COOKIE_LOGIN':
                global $IS_A_COOKIE_LOGIN;
                $value = $IS_A_COOKIE_LOGIN && ini_get('suhosin.cookie.max_name_length') !== '64' ? '1' : '0';
                break;
            case 'GROUP_ID':
                if (isset($param[0])) {
                    $groups = $GLOBALS['FORUM_DRIVER']->get_members_groups(isset($param[1]) ? intval($param[1]) : get_member());
                    $value = array_key_exists(intval($param[0]), $groups) ? strval($groups[intval($param[0])]) : '';
                }
                break;
            case 'GROUP_NAME':
                if (isset($param[0])) {
                    $groups = $GLOBALS['FORUM_DRIVER']->get_members_groups(isset($param[1]) ? intval($param[1]) : get_member());
                    if (array_key_exists(intval($param[0]), $groups)) {
                        $all_usergroups = $GLOBALS['FORUM_DRIVER']->get_usergroup_list();
                        $value = $all_usergroups[$groups[intval($param[0])]];
                    }
                    if ($GLOBALS['XSS_DETECT'] && ocp_is_escaped($param[0])) {
                        ocp_mark_as_escaped($value);
                    }
                }
                break;
            case 'NEGATE':
                if (isset($param[0])) {
                    $value = strval(-intval($param[0]));
                }
                break;
            case 'XOR':
                $count = 0;
                foreach ($param as $test) {
                    if ($test == '1' || $test == '1') {
                        $count++;
                    }
                }
                $value = $count == 1 ? '1' : '0';
                break;
            case 'NOR':
                $count = 0;
                foreach ($param as $test) {
                    if ($test == '1' || $test == '1') {
                        $count++;
                    }
                }
                $value = $count > 0 ? '0' : '1';
                break;
            case 'NAND':
                $count = 0;
                foreach ($param as $test) {
                    if ($test == '1' || $test == '1') {
                        $count++;
                    }
                }
                $value = $count == count($param) ? '0' : '1';
                break;
            case 'LT':
                if (isset($param[1])) {
                    $value = intval($param[0]) < intval($param[1]) ? '1' : '0';
                }
                break;
            case 'GT':
                if (isset($param[1])) {
                    $value = intval($param[0]) > intval($param[1]) ? '1' : '0';
                }
                break;
            case 'COPPA_ON':
                $value = get_option('is_on_coppa') == '1' ? '1' : '0';
                break;
            case 'OBFUSCATE':
                if (isset($param[0])) {
                    require_code('obfuscate');
                    $value = obfuscate_entities($param[0]);
                }
                break;
            case 'FIX_ID':
                if (isset($param[0])) {
                    $value = fix_id($param[0]);
                    if ($GLOBALS['XSS_DETECT']) {
                        ocp_mark_as_escaped($value);
                    }
                }
                break;
            case 'MAILTO':
                require_code('obfuscate');
                $value = mailto_obfuscated();
                break;
            case 'INLINE_STATS':
                $value = get_option('show_inline_stats') == '1' ? '1' : '0';
                break;
            case 'ATTACHMENT_DOWNLOADS':
                if (isset($param[0])) {
                    $db = $GLOBALS['SITE_DB'];
                    if (isset($param[1]) && $param[1] == '1') {
                        $db = $GLOBALS['FORUM_DB'];
                    }
                    $_value = $db->query_value_null_ok('attachments', 'a_num_downloads', array('id' => intval($param[0])));
                    $value = is_null($_value) ? '?' : strval($_value);
                }
                break;
            case 'CSS_DIMENSION_REDUCE':
                if (isset($param[1])) {
                    $value = $param[0];
                    if (substr($value, -2) == 'px') {
                        $b = $param[1];
                        $value = strval(intval(substr($value, 0, -2)) - intval($b)) . 'px';
                    }
                    if ($value == '') {
                        $value = '0px';
                    }
                }
                break;
            case 'COMMENT_COUNT':
                if (isset($param[1])) {
                    if (get_option('is_on_comments') == '1') {
                        $count = 0;
                        $_comments = $GLOBALS['FORUM_DRIVER']->get_forum_topic_posts($GLOBALS['FORUM_DRIVER']->find_topic_id_for_topic_identifier(get_option('comments_forum_name'), $param[0] . '_' . $param[1]), $count, 0, 0, false);
                        $_value = do_lang_tempcode('_COMMENTS', integer_format(0));
                        if (is_array($_comments)) {
                            $_value = do_lang_tempcode('_COMMENTS', escape_html(integer_format($count)));
                        }
                        $value = $_value->evaluate();
                    } else {
                        $value = do_lang('VIEW');
                    }
                }
                break;
            case 'CAN_SPELLCHECK':
                $value = function_exists('pspell_check') ? '1' : '0';
                break;
            case 'AWARD_ID':
                if (array_key_exists(0, $param)) {
                    $value = $GLOBALS['SITE_DB']->query_value_null_ok('award_archive', 'content_id', array('a_type_id' => intval($param[0])), 'ORDER BY date_and_time DESC');
                    if (is_null($value)) {
                        $value = '';
                    }
                }
                break;
            case 'SELF_PAGE_LINK':
                $value = '';
                if (running_script('index') || running_script('iframe')) {
                    $value = get_zone_name() . ':' . get_page_name();
                    foreach ($_GET as $key => $val) {
                        if ($key == 'page') {
                            continue;
                        }
                        if (is_array($val)) {
                            continue;
                        }
                        if (substr($key, 0, 5) == 'keep_') {
                            continue;
                        }
                        $value .= ':' . $key . '=' . $val;
                    }
                }
                break;
            case 'SET_TUTORIAL_LINK':
                $value = '';
                if (array_key_exists(1, $param) && $param[1] != '' && $param[1][0] != '#') {
                    set_tutorial_link($param[0], $param[1]);
                }
                break;
            case 'DISPLAY_CONCEPT':
                $value = '';
                if (array_key_exists(0, $param)) {
                    $key = $param[0];
                    $page_link = get_tutorial_link('concept___' . preg_replace('#[^\\w_]#', '_', $key));
                    if (is_null($page_link)) {
                        $temp_tpl = make_string_tempcode($key);
                    } else {
                        list($zone, $attributes, $hash) = page_link_decode($page_link);
                        $_url = build_url($attributes, $zone, NULL, false, false, false, $hash);
                        $temp_tpl = do_template('COMCODE_CONCEPT', array('_GUID' => 'ee0cd05f87329923f05145180004d8a8', 'TEXT' => $key, 'URL' => $_url));
                    }
                    $value = $temp_tpl->evaluate();
                }
                break;
            case 'SELF_URL':
                $extra_params = NULL;
                if (isset($param[3])) {
                    $extra_params = array();
                    $i = 3;
                    while (isset($param[$i])) {
                        $bits = explode('=', $param[$i], 2);
                        if ($bits[1] == '<null>') {
                            $bits[1] = NULL;
                        }
                        $extra_params[$bits[0]] = $bits[1];
                        $i++;
                    }
                }
                $value = get_self_url(true, isset($param[0]) && $param[0] == '1', $extra_params, isset($param[1]) && $param[1] == '1', isset($param[2]) && $param[2] == '1');
                break;
            case 'SHIFT_DECODE':
                if (isset($param[0])) {
                    global $SHIFT_VARIABLES;
                    $key = $param[0];
                    $value = isset($SHIFT_VARIABLES[$key]) ? $SHIFT_VARIABLES[$key]->evaluate() : '';
                }
                break;
            case 'NUMBER_FORMAT':
                if (isset($param[0])) {
                    $value = integer_format(intval($param[0]));
                }
                break;
            case 'FLOAT_FORMAT':
                if (isset($param[0])) {
                    $value = float_format(floatval($param[0]));
                }
                break;
            case 'CURRENTLY_INVISIBLE':
                $value = is_invisible() ? '1' : '0';
                break;
            case 'IS_FRIEND':
                if (isset($param[0])) {
                    $test = $GLOBALS['SITE_DB']->query_value_null_ok('chat_buddies', 'member_likes', array('member_likes' => isset($param[1]) ? intval($param[1]) : get_member(), 'member_liked' => intval($param[0])));
                    $value = is_null($test) ? '0' : '1';
                }
                break;
            case 'SSW':
                $value = get_option('ssw') == '1' ? '1' : '0';
                break;
            case 'RATING':
                if (isset($param[1])) {
                    require_code('feedback');
                    $rating = get_rating_simple_array(array_key_exists(3, $param) ? $param[3] : get_self_url(true), array_key_exists(4, $param) ? $param[4] : (is_null($DISPLAYED_TITLE) ? '' : $DISPLAYED_TITLE->evaluate()), $param[0], $param[1], array_key_exists(5, $param) ? $param[5] : 'RATING_FORM', array_key_exists(2, $param) ? $param[2] : NULL);
                    if ($rating !== NULL) {
                        if (!array_key_exists(2, $param) || $param[2] == '0') {
                            $value = isset($rating['ALL_RATING_CRITERIA'][0]['RATING']) ? $rating['ALL_RATING_CRITERIA'][0]['RATING'] : '';
                        } else {
                            $value = do_template('RATING_INLINE_STATIC', $rating);
                        }
                        if (is_object($value)) {
                            $value = $value->evaluate();
                        }
                    }
                }
                break;
            case 'VIEWS':
                if (isset($param[2])) {
                    $id_field = 'id';
                    // Not allowed for security reasons
                    if (preg_match('#^\\w*views\\w*$#', $param[1]) != 0) {
                        $test = $GLOBALS['SITE_DB']->query_value_null_ok($param[0], $param[1], array($id_field => $param[2]));
                        if (!is_null($test)) {
                            $value = integer_format($test);
                        }
                    }
                }
                break;
            default:
                global $EXTRA_SYMBOLS;
                if (is_null($EXTRA_SYMBOLS)) {
                    $EXTRA_SYMBOLS = array();
                    $hooks = find_all_hooks('systems', 'symbols');
                    foreach (array_keys($hooks) as $hook) {
                        $EXTRA_SYMBOLS[$hook] = array();
                    }
                }
                if (array_key_exists($name, $EXTRA_SYMBOLS)) {
                    if (!array_key_exists('ob', $EXTRA_SYMBOLS[$name])) {
                        require_code('hooks/systems/symbols/' . filter_naughty_harsh($name));
                        $EXTRA_SYMBOLS[$name]['ob'] = object_factory('Hook_symbol_' . filter_naughty_harsh($name));
                    }
                    $value = $EXTRA_SYMBOLS[$name]['ob']->run($param);
                    break;
                }
                if (defined($name)) {
                    $value = @strval(constant($name));
                    break;
                }
                $value = '';
                require_code('site');
                attach_message(do_lang_tempcode('MISSING_SYMBOL', escape_html($name)), 'warn');
        }
        if ($escaped != array()) {
            if (is_object($value)) {
                $value = $value->evaluate();
            }
            apply_tempcode_escaping($escaped, $value);
        }
        if ($cacheable) {
            $SYMBOL_CACHE[$escaped_codes] = $value;
        }
        return $value;
    }
    // Is it a directive?
    if ($type == TC_DIRECTIVE) {
        $value = '';
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($value);
        }
        // In our param we should have a map of bubbled template parameters (under 'vars') and our numbered directive parameters
        if ($param === NULL) {
            $param = array();
        }
        // Closure-based Tempcode parser may send in strings, so we need to adapt...
        foreach ($param as $key => $val) {
            if (is_string($val)) {
                $param[$key] = make_string_tempcode($val);
            }
        }
        if (!isset($param['vars'])) {
            $param['vars'] = array();
        }
        switch ($name) {
            case 'SHIFT_ENCODE':
                break;
            case 'PARAM_INFO':
                $_value = do_template('PARAM_INFO', array('MAP' => $param['vars']));
                $value = $_value->evaluate();
                break;
            case 'CSS_INHERIT':
                // e.g. {+START,CSS_INHERIT,global,default,#886aa9}{+END}
                if (isset($param[0])) {
                    require_code('css_and_js');
                    $css_file = $param[0]->evaluate();
                    $theme = isset($param[1]) ? $param[1]->evaluate() : 'default';
                    $seed = isset($param[2]) ? $param[2]->evaluate() : NULL;
                    if ($seed == '') {
                        $seed = NULL;
                    }
                    $dark = isset($param[3]) ? $param[3]->evaluate() == '1' : false;
                    $algorithm = isset($param[4]) ? $param[4]->evaluate() : 'equations';
                    $value = css_inherit($css_file, $theme, $GLOBALS['FORUM_DRIVER']->get_theme(), $seed, $dark, $algorithm);
                }
                break;
            case 'FRACTIONAL_EDITABLE':
                foreach (array_keys($param) as $key) {
                    if (!is_numeric($key)) {
                        unset($param[$key]);
                    }
                }
                if (isset($param[3])) {
                    $edit_text = $param[0]->evaluate();
                    $edit_param_name = $param[1]->evaluate();
                    $edit_pagelink = $param[2]->evaluate();
                    $supports_comcode = (isset($param[4]) ? $param[3]->evaluate() : '0') == '1';
                    list($zone, $attributes, ) = page_link_decode($edit_pagelink);
                    if ($zone == '_SEARCH') {
                        $zone = get_module_zone($attributes['page']);
                    }
                    if (has_actual_page_access(get_member(), $attributes['page'], $zone) && has_zone_access(get_member(), 'adminzone')) {
                        $keep = symbol_tempcode('KEEP');
                        $url = find_script('fractional_edit') . '?edit_param_name=' . urlencode($edit_param_name) . '&supports_comcode=' . ($supports_comcode ? '1' : '0') . '&zone=' . urlencode($zone) . $keep->evaluate();
                        foreach ($attributes as $key => $val) {
                            $url .= '&' . $key . '=' . urlencode($val);
                        }
                        $_value = $param[count($param) - 1];
                        $_value = do_template('FRACTIONAL_EDIT', array('_GUID' => '075ac126c427d28b309004bc67b32b08', 'VALUE' => $_value, 'URL' => $url, 'EDIT_TEXT' => $edit_text, 'EDIT_PARAM_NAME' => $edit_param_name));
                        $value = $_value->evaluate();
                    } else {
                        $value = $param[count($param) - 1]->evaluate();
                    }
                }
                break;
            case 'SET':
                if (isset($param[1])) {
                    $var = $param[0]->evaluate();
                    $set_val = '';
                    $i = 1;
                    while (isset($param[$i])) {
                        if ($i != 1) {
                            $set_val .= ',';
                        }
                        $set_val .= $param[1]->evaluate();
                        $i++;
                    }
                    $TEMPCODE_SETGET[$var] = $set_val;
                }
                break;
            case 'IN_ARRAY':
                if (isset($param[1])) {
                    $key = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $value = in_array($param[0]->evaluate(), $array) ? '1' : '0';
                }
                break;
            case 'NOT_IN_ARRAY':
                if (isset($param[1])) {
                    $key = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $value = in_array($param[0]->evaluate(), $array) ? '0' : '1';
                }
                break;
            case 'IF_IN_ARRAY':
                if (isset($param[2])) {
                    $key = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $value = in_array($param[0]->evaluate(), $array) ? $param[2]->evaluate() : '';
                }
                break;
            case 'IF_NOT_IN_ARRAY':
                if (isset($param[2])) {
                    $key = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $value = in_array($param[0]->evaluate(), $array) ? '' : $param[2]->evaluate();
                }
                break;
            case 'IMPLODE':
                if (isset($param[1])) {
                    $key = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    if (isset($param[2]) && $param[2]->evaluate() == '1') {
                        $delim = $param[0]->evaluate();
                        foreach ($array as $key => $val) {
                            if ($value != '') {
                                $value .= $delim;
                            }
                            $value .= (is_integer($key) ? integer_format($key) : $key) . ' = ' . $val;
                        }
                    } else {
                        $value = implode($param[0]->evaluate(), $array);
                    }
                }
                break;
            case 'COUNT':
                if (isset($param[0])) {
                    $key = $param[0]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $value = strval(count($array));
                }
                break;
            case 'BOX':
                unset($param['vars']);
                $title = isset($param[1]) ? $param[0]->evaluate() : '';
                $dimensions = isset($param[2]) ? $param[1]->evaluate() : '100%';
                if ($dimensions == '') {
                    $dimensions = '100%';
                }
                $box_type = isset($param[3]) ? $param[2]->evaluate() : 'classic';
                $options = isset($param[4]) ? $param[3]->evaluate() : '';
                $meta = isset($param[5]) ? $param[4]->evaluate() : '';
                $links = isset($param[6]) ? $param[5]->evaluate() : '';
                $expand = isset($param[7]) ? $param[6]->evaluate() == '1' : false;
                $toplink = isset($param[8]) ? $param[7]->evaluate() : '';
                $tmp = put_in_standard_box(array_pop($param), $title, $dimensions, $box_type, $options, $meta, $links, $expand, $toplink);
                $value = $tmp->evaluate();
                break;
            case 'IF_NON_EMPTY':
                if (isset($param[1])) {
                    if (!$param[0]->is_really_empty()) {
                        $value = $param[1]->evaluate();
                    }
                }
                break;
            case 'IF_PASSED':
                if (isset($param[1])) {
                    $t = $param[0]->evaluate();
                    if (isset($param['vars'][$t])) {
                        $value = $param[1]->evaluate();
                    }
                }
                break;
            case 'IF_NON_PASSED':
                if (isset($param[1])) {
                    $t = $param[0]->evaluate();
                    if (!isset($param['vars'][$t])) {
                        $value = $param[1]->evaluate();
                    }
                }
                break;
            case 'IF_EMPTY':
                if (isset($param[1])) {
                    if ($param[0]->is_really_empty()) {
                        $value = $param[1]->evaluate();
                    }
                }
                break;
            case 'IF_ARRAY_EMPTY':
                if (isset($param[0])) {
                    $looking_at = $param[0]->evaluate();
                    if (array_key_exists($looking_at, $param['vars'])) {
                        if (count($param['vars'][$looking_at]) == 0) {
                            $value = $param[1]->evaluate();
                        }
                    }
                }
                break;
            case 'IF_ARRAY_NON_EMPTY':
                if (isset($param[0])) {
                    $looking_at = $param[0]->evaluate();
                    if (array_key_exists($looking_at, $param['vars'])) {
                        if (count($param['vars'][$looking_at]) != 0) {
                            $value = $param[1]->evaluate();
                        }
                    }
                }
                break;
            case 'OF':
                if (isset($param[1])) {
                    $key = $param[0]->evaluate();
                    $x = $param[1]->evaluate();
                    $array = array_key_exists($key, $param['vars']) ? $param['vars'][$key] : array();
                    $x2 = is_numeric($x) ? intval($x) : $x;
                    if (is_integer($x2)) {
                        if ($x2 < 0) {
                            $x2 = count($array) - 1;
                        } elseif ($x2 >= count($array)) {
                            $x2 -= count($array);
                        }
                    }
                    $value = array_key_exists($x2, $array) ? $array[$x2] : '';
                    if (is_object($value)) {
                        $value = $value->evaluate();
                    }
                }
                break;
            case 'INCLUDE':
                if (isset($param[1])) {
                    $tpl_params = $param['vars'];
                    $explode = explode(chr(10), $param[1]->evaluate());
                    foreach ($explode as $val) {
                        $bits = explode('=', $val, 2);
                        if (count($bits) == 2) {
                            $tpl_params[ltrim($bits[0])] = $bits[1];
                        }
                    }
                    $td = isset($param[3]) ? $param[2]->evaluate() : '';
                    if ($td == '') {
                        $td = 'templates';
                    }
                    $ex = isset($param[2]) ? $param[1]->evaluate() : '';
                    if ($ex == '') {
                        $ex = '.tpl';
                    }
                    $_value = do_template($param[0]->evaluate(), $tpl_params, NULL, false, NULL, $ex, $td);
                    $value = $_value->evaluate();
                }
                break;
            case 'WHILE':
                if (isset($param[1])) {
                    $_p = $param[0]->evaluate();
                    if ($_p == '1' || $_p == '1') {
                        $value = '';
                        $value .= $param[1]->evaluate();
                        $value .= ecv($lang, $escaped, $type, $name, $param);
                    }
                }
                break;
            case 'IF':
                if (isset($param[1])) {
                    $_p = $param[0]->evaluate();
                    if ($_p == '1' || $_p == '1') {
                        $value = $param[1]->evaluate();
                    }
                }
                break;
            case 'LOOP':
                if (isset($param[0])) {
                    if (!array_key_exists($param[0]->evaluate(), $param['vars'])) {
                        require_code('site');
                        attach_message(do_lang_tempcode('MISSING_TEMPLATE_PARAMETER', $param[0]->evaluate(), '???'), 'warn');
                        return '';
                    }
                    $array_key = $param[0]->evaluate();
                    if (is_numeric($array_key) || strpos($array_key, ',') !== false) {
                        $array = explode(',', $array_key);
                    } else {
                        $array = array_key_exists($array_key, $param['vars']) ? $param['vars'][$array_key] : array();
                        if (!is_array($array)) {
                            $array = array();
                        }
                    }
                    $value = '';
                    if (array_key_exists(1 + 1, $param)) {
                        $columns = $param[1]->evaluate();
                        $row_starter = array_key_exists(2 + 1, $param) ? $param[2]->evaluate() : '<tr>';
                        $row_terminator = array_key_exists(3 + 1, $param) ? $param[3]->evaluate() : '</tr>';
                        $value .= $row_starter;
                        // Sorting
                        if (array_key_exists(4 + 1, $param)) {
                            $sort_key = $param[4]->evaluate();
                            $rev = array_key_exists(5 + 1, $param) && $param[5]->evaluate() == 'DESC';
                            if ($sort_key != '') {
                                global $M_SORT_KEY;
                                $M_SORT_KEY = $sort_key;
                                uasort($array, 'multi_sort');
                            }
                            if ($rev) {
                                $array = array_reverse($array);
                            }
                        }
                    }
                    $last = count($param) - 2;
                    $col = 0;
                    $first = true;
                    foreach ($array as $go_key => $go) {
                        if (!is_array($go)) {
                            $go = array('_loop_key' => make_string_tempcode(is_integer($go_key) ? strval($go_key) : $go_key), '_loop_var' => make_string_tempcode($go));
                        }
                        // In case it's not a list of maps, but just a list
                        if (isset($param[2]) && $col % $columns == 0 && $col != 0) {
                            $value .= $row_starter;
                        }
                        $ps = $go + $param['vars'] + array('_loop_key' => make_string_tempcode(is_integer($go_key) ? strval($go_key) : $go_key), '_i' => strval($col), '_first' => $first, '_last' => $col == count($array) - 1);
                        $bound = $param[$last]->bind($ps, '');
                        $value .= $bound->evaluate();
                        ++$col;
                        if (isset($param[3]) && $col % $columns == 0) {
                            $value .= $row_terminator;
                        }
                        $first = false;
                    }
                    if (isset($param[2]) && $col % $columns != 0) {
                        $value .= $row_terminator;
                    }
                }
                break;
            default:
                require_code('site');
                attach_message(do_lang_tempcode('UNKNOWN_DIRECTIVE', escape_html($name)), 'warn');
        }
        if ($escaped != array()) {
            apply_tempcode_escaping($escaped, $value);
        }
        return $value;
    }
    // By elimination, it's language
    $a = isset($param[0]) ? is_object($param[0]) ? $param[0]->evaluate() : $param[0] : NULL;
    $b = isset($param[1]) ? is_object($param[1]) ? $param[1]->evaluate() : $param[1] : NULL;
    $c = isset($param[2]) ? array_splice($param, 2) : NULL;
    if ($c !== NULL) {
        foreach ($c as $i => $cc) {
            if (is_object($cc)) {
                $c[$i] = $cc->evaluate();
            }
        }
    }
    static $dle = false;
    if (!$dle) {
        $dle = function_exists('do_lang');
    }
    $ret = $dle ? do_lang($name, $a, $b, $c, $lang, false) : escape_html($name . ':' . (!is_null($a) ? $a : '') . ',' . (!is_null($b) ? $b : ''));
    if ($ret === NULL) {
        if ($type != TC_PARAMETER) {
            require_code('site');
            attach_message(do_lang_tempcode('MISSING_LANG_ENTRY', escape_html($name)), 'warn');
        }
        $value = '';
        if ($GLOBALS['XSS_DETECT']) {
            ocp_mark_as_escaped($value);
        }
        return $value;
    }
    if ($escaped != array() && $escaped != array(ENTITY_ESCAPED)) {
        apply_tempcode_escaping(array_diff($escaped, array(ENTITY_ESCAPED)), $ret);
    }
    // Escape but without ENTITY_ESCAPED because we don't do that on lang strings
    return $ret;
}
Example #9
0
 /**
  * Parse a single symbol from an input stream and append it.
  *
  * @param  string				Code string (input stream)
  * @param  integer			Read position
  * @param  integer			Length of input string
  */
 function parse_from(&$code, &$pos, &$len)
 {
     $temp = template_to_tempcode(substr($code, $pos, $len - $pos), 0, false, '');
     $this->bits = $temp->bits;
 }
Example #10
0
 /**
  * Standard modular run function for CRON hooks. Searches for tasks to perform.
  */
 function run()
 {
     //if (!running_script('execute_temp')) return;
     $time_now = time();
     //$time_now=1335726076;
     $last_cron_time = intval(get_value('last_welcome_mail_time'));
     if ($last_cron_time == 0) {
         $last_cron_time = $time_now - 24 * 60 * 60 * 7;
     }
     set_value('last_welcome_mail_time', strval($time_now));
     //$last_cron_time=$time_now-60*60*1;
     require_code('mail');
     $GLOBALS['NO_DB_SCOPE_CHECK'] = true;
     $mails = $GLOBALS['SITE_DB']->query_select('f_welcome_emails', array('*'));
     $GLOBALS['NO_DB_SCOPE_CHECK'] = false;
     foreach ($mails as $mail) {
         $send_seconds_after_joining = $mail['w_send_time'] * 60 * 60;
         $newsletter_style = get_value('welcome_nw_choice') === '1' && !is_null($mail['w_newsletter']) || get_value('welcome_nw_choice') !== '1' && ($mail['w_newsletter'] == 1 || get_forum_type() != 'ocf');
         if ($newsletter_style) {
             if (addon_installed('newsletter')) {
                 // Think of it like this, m_join_time (members join time) must between $last_cron_time and $time_now, but offset back by $send_seconds_after_joining
                 $where = ' WHERE join_time>' . strval($last_cron_time - $send_seconds_after_joining) . ' AND join_time<=' . strval($time_now - $send_seconds_after_joining) . ' AND (the_level=3 OR the_level=4)';
                 if (get_value('welcome_nw_choice') === '1') {
                     $where .= ' AND newsletter_id=' . strval($mail['w_newsletter']);
                 }
                 $members = $GLOBALS['SITE_DB']->query('SELECT s.email AS m_email_address,the_password,n_forename,n_surname,n.id,join_time AS m_join_time FROM ' . get_table_prefix() . 'newsletter_subscribe s JOIN ' . get_table_prefix() . 'newsletter n ON n.email=s.email ' . $where . ' GROUP BY s.email');
             } else {
                 $members = array();
             }
         } else {
             // Think of it like this, m_join_time (members join time) must between $last_cron_time and $time_now, but offset back by $send_seconds_after_joining
             $where = ' WHERE m_join_time>' . strval($last_cron_time - $send_seconds_after_joining) . ' AND m_join_time<=' . strval($time_now - $send_seconds_after_joining);
             if (get_option('allow_email_from_staff_disable') == '1') {
                 $where .= ' AND m_allow_emails=1';
             }
             $query = 'SELECT m_email_address,m_username,id,m_join_time FROM ' . get_table_prefix() . 'f_members' . $where;
             $members = $GLOBALS['FORUM_DB']->query($query);
         }
         //var_dump($members);exit();
         foreach ($members as $member) {
             $subject = get_translated_text($mail['w_subject'], NULL, get_lang($member['id']));
             $text = get_translated_text($mail['w_text'], NULL, get_lang($member['id']));
             $_text = do_template('NEWSLETTER_DEFAULT', array('CONTENT' => $text, 'LANG' => get_site_default_lang()));
             for ($i = 0; $i < 100; $i++) {
                 if (strpos($text, '{{' . strval($i) . '}}') !== false) {
                     $text = str_replace('{{' . strval($i) . '}}', get_timezoned_date($time_now + $i * 60 * 60 * 24), $text);
                 }
             }
             if ($member['m_email_address'] != '') {
                 $message = $_text->evaluate(get_lang($member['id']));
                 if ($newsletter_style) {
                     $forename = $member['n_forename'];
                     $surname = $member['n_surname'];
                     $name = trim($forename . ' ' . $surname);
                     require_lang('newsletter');
                     if ($name == '') {
                         $name = do_lang('NEWSLETTER_SUBSCRIBER', get_site_name());
                     }
                 } else {
                     $forename = '';
                     $surname = '';
                     $name = $member['m_username'];
                 }
                 if (addon_installed('newsletter')) {
                     if ($newsletter_style) {
                         $sendid = 'n' . strval($member['id']);
                         $hash = best_hash($member['the_password'], 'xunsub');
                     } else {
                         $sendid = 'w' . strval('id');
                         $hash = '';
                     }
                     require_code('newsletter');
                     $message = newsletter_variable_substitution($message, $subject, $forename, $surname, $name, $member['m_email_address'], $sendid, $hash);
                 }
                 if ($is_html) {
                     require_code('tempcode_compiler');
                     $temp = template_to_tempcode($message);
                     $message = $temp->evaluate(get_lang($member['id']));
                 }
                 if (get_value('notification_safety_testing') === '1') {
                     $test = $GLOBALS['SITE_DB']->query_value_null_ok('logged_mail_messages', 'm_date_and_time', array('m_subject' => $subject, 'm_to_email' => serialize(array($member['m_email_address']))));
                     if (!is_null($test)) {
                         if ($test > $member['m_join_time']) {
                             fatal_exit(do_lang('INTERNAL_ERROR') . ' [' . $member['m_email_address'] . ']');
                         }
                         // otherwise they probably just resubscribed and hence bumped their time
                     }
                 }
                 mail_wrap($subject, $message, array($member['m_email_address']), $name, '', '', 3, NULL, false, NULL, true, $is_html);
             }
         }
     }
 }
Example #11
0
/**
 * Take a page link and convert to attributes and zone.
 *
 * @param  SHORT_TEXT	The page link
 * @return array			Triple: zone, attribute-array, hash part of a URL including the hash (or blank)
 */
function page_link_decode($param)
{
    global $CHR_0;
    if (strpos($param, '#') === false) {
        $hash = '';
    } else {
        $hash_pos = strpos($param, '#');
        $hash = substr($param, $hash_pos);
        $param = substr($param, 0, $hash_pos);
    }
    if (strpos($param, $CHR_0) === false) {
        $bits = explode(':', $param);
    } else {
        $term_pos = strpos($param, $CHR_0);
        $bits = explode(':', substr($param, 0, $term_pos));
        $bits[count($bits) - 1] .= substr($param, $term_pos);
    }
    $zone = $bits[0];
    if ($zone == '_SEARCH') {
        if (isset($bits[1])) {
            $zone = get_page_zone($bits[1], false);
            if ($zone === NULL) {
                $zone = '';
            }
        } else {
            $zone = '';
        }
    } elseif ($zone == 'site' && get_option('collapse_user_zones') == '1') {
        $zone = '';
    } elseif ($zone == '_SELF') {
        $zone = get_zone_name();
    }
    if (isset($bits[1])) {
        if ($bits[1] != '') {
            if ($bits[1] == '_SELF') {
                $attributes = array('page' => get_page_name());
            } else {
                $attributes = array('page' => $bits[1]);
            }
        } else {
            $attributes = array();
        }
        unset($bits[1]);
    } else {
        $attributes = array('page' => get_zone_default_page($zone));
    }
    unset($bits[0]);
    $i = 0;
    foreach ($bits as $bit) {
        if ($bit != '' || $i == 1) {
            if ($i == 0 && strpos($bit, '=') === false) {
                $_bit = array('type', $bit);
            } elseif ($i == 1 && strpos($bit, '=') === false) {
                $_bit = array('id', $bit);
            } else {
                $_bit = explode('=', $bit, 2);
            }
        } else {
            $_bit = array($bit, '');
        }
        if (isset($_bit[1])) {
            $decoded = urldecode($_bit[1]);
            if ($decoded != '' && $decoded[0] == '{' && strlen($decoded) > 2 && intval($decoded[1]) > 51) {
                require_code('tempcode_compiler');
                $decoded = template_to_tempcode($decoded);
                $decoded = $decoded->evaluate();
            }
            if ($decoded == '<null>') {
                $attributes[$_bit[0]] = NULL;
            } else {
                $attributes[$_bit[0]] = $decoded;
            }
        }
        $i++;
    }
    return array($zone, $attributes, $hash);
}
Example #12
0
 /**
  * Parse a single symbol from an input stream and append it.
  *
  * @param  string				Code string (input stream)
  * @param  integer			Start position of input string
  * @param  integer			End position of input string
  */
 function parse_from(&$code, &$pos, &$len)
 {
     $this->cached_output = NULL;
     require_code('tempcode_compiler');
     $temp = template_to_tempcode(substr($code, $pos, $len - $pos), 0, false, '');
     $this->code_to_preexecute = $temp->code_to_preexecute;
     $this->seq_parts = $temp->seq_parts;
     $this->preprocessable_bits = $temp->preprocessable_bits;
 }
Example #13
0
/**
 * Get tempcode for a Comcode tag. This function should always return (errors should be placed in the Comcode output stream), for stability reasons (i.e. if you're submitting something, you can't have the whole submit process die half way through in an unstructured fashion).
 *
 * @param  string			The tag being converted
 * @param  array			A map of the attributes (name=>val) for the tag. Val is usually a string, although in select places, the XML parser may pass tempcode.
 * @param  mixed			Tempcode of the inside of the tag ([between]THIS[/between]); the XML parser may pass in special stuff here, which is interpreted only for select tags
 * @param  boolean		Whether we are allowed to proceed even if this tag is marked as 'dangerous'
 * @param  string			A special identifier to mark where the resultant tempcode is going to end up (e.g. the ID of a post)
 * @param  integer		The position this tag occurred at in the Comcode
 * @param  MEMBER			The member who is responsible for this Comcode
 * @param  boolean		Whether to check as arbitrary admin
 * @param  object			The database connection to use
 * @param  string			The whole chunk of comcode
 * @param  boolean		Whether this is for WML output
 * @param  boolean		Whether this is only a structure sweep
 * @param  boolean		Whether we are in semi-parse-mode (some tags might convert differently)
 * @param  ?array			A list of words to highlight (NULL: none)
 * @param  ?MEMBER		The member we are running on behalf of, with respect to how attachments are handled; we may use this members attachments that are already within this post, and our new attachments will be handed to this member (NULL: member evaluating)
 * @param  boolean		Whether what we have came from inside a semihtml tag
 * @param  boolean		Whether what we have came from semihtml mode
 * @return tempcode		The tempcode for the Comcode
 */
function _do_tags_comcode($tag, $attributes, $embed, $comcode_dangerous, $pass_id, $marker, $source_member, $as_admin, $connection, &$comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits = NULL, $on_behalf_of_member = NULL, $in_semihtml = false, $is_all_semihtml = false)
{
    if ($structure_sweep && $tag != 'title') {
        return new ocp_tempcode();
    }
    $param_given = isset($attributes['param']);
    if (!isset($attributes['param']) && $tag != 'block') {
        $attributes['param'] = '';
    }
    global $DANGEROUS_TAGS, $STRUCTURE_LIST, $COMCODE_PARSE_TITLE;
    if (isset($DANGEROUS_TAGS[$tag]) && !$comcode_dangerous) {
        $username = $GLOBALS['FORUM_DRIVER']->get_username($source_member);
        if (is_null($username)) {
            $username = do_lang('UNKNOWN');
        }
        if ($semiparse_mode) {
            $params = '';
            foreach ($attributes as $key => $val) {
                $params .= ' ' . $key . '="' . comcode_escape($val) . '"';
            }
            return make_string_tempcode('<input class="ocp_keep_ui_controlled" size="45" title="[' . $tag . '' . escape_html($params) . ']' . ($in_semihtml || $is_all_semihtml ? escape_html($embed->evaluate()) : escape_html($embed->evaluate())) . '[/' . $tag . ']" type="text" value="' . ($tag == 'block' ? do_lang('COMCODE_EDITABLE_BLOCK', escape_html($embed->evaluate())) : do_lang('COMCODE_EDITABLE_TAG', escape_html($tag))) . '" />');
        }
        return do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('comcode:NO_ACCESS_FOR_TAG', escape_html($tag), escape_html($username))));
        //return new ocp_tempcode();
    }
    // These are just bbcode compatibility tags.. we will remap to our proper comcode
    if ($tag == 'php') {
        $attributes['param'] = 'php';
        $tag = 'code';
    } elseif ($tag == 'sql') {
        $attributes['param'] = 'sql';
        $tag = 'code';
    } elseif ($tag == 'codebox') {
        $attributes['scroll'] = '1';
        $tag = 'code';
    } elseif ($tag == 'left') {
        $attributes['param'] = 'left';
        $tag = 'align';
    } elseif ($tag == 'center') {
        $attributes['param'] = 'center';
        $tag = 'align';
    } elseif ($tag == 'right') {
        $attributes['param'] = 'right';
        $tag = 'align';
    } elseif ($tag == 'thread') {
        $tag = 'topic';
    } elseif ($tag == 'internal_table' || $tag == 'external_table') {
        $tag = 'box';
        if (array_key_exists('class', $attributes)) {
            $attributes['type'] = $attributes['class'];
        }
    }
    if ($semiparse_mode) {
        $non_text_tags = array('attachment', 'section_controller', 'big_tab_controller', 'currency', 'block', 'contents', 'concepts', 'flash', 'menu', 'email', 'reference', 'upload', 'page', 'exp_thumb', 'exp_ref', 'thumb', 'snapback', 'post', 'thread', 'topic', 'include', 'random', 'jumping', 'shocker');
        // Also in JAVASCRIPT_EDITING.tpl
        if ($tag == 'attachment_safe') {
            if (preg_match('#^new\\_\\d+$#', $embed->evaluate()) != 0) {
                $non_text_tags[] = 'attachment_safe';
            }
        }
        if (in_array($tag, $non_text_tags)) {
            $params = '';
            foreach ($attributes as $key => $val) {
                $params .= ' ' . $key . '="' . str_replace('"', '\\"', $val) . '"';
            }
            if ($tag != 'block' || !is_file(get_file_base() . '/sources_custom/miniblocks/' . $embed->evaluate() . '.php')) {
                return make_string_tempcode('<input class="ocp_keep_ui_controlled" size="45" title="[' . $tag . '' . escape_html($params) . ']' . ($in_semihtml || $is_all_semihtml ? escape_html($embed->evaluate()) : escape_html($embed->evaluate())) . '[/' . $tag . ']" type="text" value="' . ($tag == 'block' ? do_lang('comcode:COMCODE_EDITABLE_BLOCK', escape_html($embed->evaluate())) : do_lang('comcode:COMCODE_EDITABLE_TAG', escape_html($tag))) . '" />');
            } else {
                return make_string_tempcode('[block' . escape_html($params) . ']' . ($in_semihtml || $is_all_semihtml ? $embed->evaluate() : escape_html($embed->evaluate())) . '[/block]');
            }
        }
    }
    $temp_tpl = new ocp_tempcode();
    switch ($tag) {
        case 'no_parse':
            $temp_tpl->attach($embed);
            break;
        case 'currency':
            if (addon_installed('ecommerce')) {
                $bracket = array_key_exists('bracket', $attributes) && $attributes['bracket'] == '1';
                if ($attributes['param'] == '') {
                    $attributes['param'] = get_option('currency');
                }
                $temp_tpl = do_template('COMCODE_CURRENCY', array('_GUID' => 'ee1fcdae082af6397ff3bad89006e012', 'AMOUNT' => $embed, 'FROM_CURRENCY' => $attributes['param'], 'BRACKET' => $bracket));
            }
            break;
        case 'overlay':
            $x = strval(array_key_exists('x', $attributes) ? intval($attributes['x']) : 100);
            $y = strval(array_key_exists('y', $attributes) ? intval($attributes['y']) : 100);
            $width = strval(array_key_exists('width', $attributes) ? intval($attributes['width']) : 300);
            $height = strval(array_key_exists('height', $attributes) ? intval($attributes['height']) : 300);
            $timein = strval(array_key_exists('timein', $attributes) ? intval($attributes['timein']) : 0);
            $timeout = strval(array_key_exists('timeout', $attributes) ? intval($attributes['timeout']) : -1);
            $temp_tpl = do_template('COMCODE_OVERLAY', array('_GUID' => 'dfd0f7a72cc2bf6b613b28f8165a0034', 'UNIQ_ID' => 'a' . uniqid('', true), 'EMBED' => $embed, 'ID' => $attributes['param'] != '' ? $attributes['param'] : 'rand' . uniqid('', true), 'X' => $x, 'Y' => $y, 'WIDTH' => $width, 'HEIGHT' => $height, 'TIMEIN' => $timein, 'TIMEOUT' => $timeout));
            break;
        case 'code':
            if ($wml) {
                $temp_tpl->attach('<b>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</b>');
                break;
            }
            list($_embed, $title) = do_code_box($attributes['param'], $embed, array_key_exists('numbers', $attributes) && $attributes['numbers'] == '1', $in_semihtml, $is_all_semihtml);
            if (!is_null($_embed)) {
                $tpl = array_key_exists('scroll', $attributes) && $attributes['scroll'] == '1' ? 'COMCODE_CODE_SCROLL' : 'COMCODE_CODE';
                if ($tpl == 'COMCODE_CODE_SCROLL' && substr_count($_embed, chr(10)) < 10) {
                    $style = 'height: auto';
                } else {
                    $style = '';
                }
                $temp_tpl = do_template($tpl, array('_GUID' => 'c5d46d0927272fcacbbabcfab0ef6b0c', 'STYLE' => $style, 'TYPE' => $attributes['param'], 'CONTENT' => $_embed, 'TITLE' => $title));
            } else {
                $_embed = '';
            }
            if ($temp_tpl->is_empty()) {
                if ($in_semihtml || $is_all_semihtml) {
                    require_code('comcode_from_html');
                    $back_to_comcode = semihtml_to_comcode($embed->evaluate());
                    // Undo what's happened already
                    //$back_to_comcode=html_entity_decode($back_to_comcode,ENT_QUOTES,get_charset()); // Remove the escaping entities that were inside the code tag
                    $embed = comcode_to_tempcode($back_to_comcode, $source_member, $as_admin, 80, $pass_id, $connection);
                    // Re-parse (with full security)
                }
                $_embed = $embed->evaluate();
                if (!array_key_exists('scroll', $attributes) && strlen($_embed) > 1000) {
                    $attributes['scroll'] = '1';
                }
                $tpl = array_key_exists('scroll', $attributes) && $attributes['scroll'] == '1' ? 'COMCODE_CODE_SCROLL' : 'COMCODE_CODE';
                $title = do_lang_tempcode('CODE');
                if ($tpl == 'COMCODE_CODE_SCROLL' && substr_count($_embed, chr(10)) < 10) {
                    $style = 'height: auto';
                } else {
                    $style = '';
                }
                $temp_tpl = do_template($tpl, array('CONTENT' => $_embed, 'TITLE' => $title, 'STYLE' => $style, 'TYPE' => $attributes['param']));
            }
            break;
        case 'list':
            if (is_array($embed)) {
                $parts = $embed;
            } else {
                $_embed = trim($embed->evaluate());
                $_embed = str_replace('[/*]', '', $_embed);
                $parts = explode('[*]', $_embed);
            }
            if (isset($temp_tpl->preprocessable_bits)) {
                $temp_tpl->preprocessable_bits = array_merge($temp_tpl->preprocessable_bits, $embed->preprocessable_bits);
            }
            if ($wml) {
                foreach ($parts as $i => $part) {
                    if ($i == 0 && str_replace(array('&nbsp;', '<br />', ' '), array('', '', ''), trim($part)) == '') {
                        continue;
                    }
                    $temp_tpl->attach('<br />* ');
                    $temp_tpl->attach($part);
                }
                $temp_tpl->attach('<br />* ');
                break;
            }
            $type = $attributes['param'];
            if ($type != '') {
                if ($type == '1') {
                    $type = 'decimal';
                } elseif ($type == 'a') {
                    $type = 'lower-alpha';
                } elseif ($type == 'i') {
                    $type = 'lower-roman';
                } elseif ($type == 'x') {
                    $type = 'none';
                } elseif (!in_array($type, array('circle', 'disc', 'square', 'armenian', 'decimal', 'decimal-leading-zero', 'georgian', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'upper-alpha', 'upper-latin', 'upper-roman'))) {
                    $type = 'disc';
                }
                $tag = in_array($type, array('circle', 'disc', 'square')) ? 'ul' : 'ol';
                $temp_tpl->attach('<' . $tag . ' style="list-style-type: ' . $type . '">');
                foreach ($parts as $i => $part) {
                    if ($i == 0 && str_replace(array('&nbsp;', '<br />', ' '), array('', '', ''), trim($part)) == '') {
                        continue;
                    }
                    $temp_tpl->attach('<li>' . preg_replace('#\\<br /\\>(\\&nbsp;|\\s)*$#D', '', preg_replace('#^\\<br /\\>(\\&nbsp;|\\s)*#D', '', $part)) . '</li>');
                }
                $temp_tpl->attach('</' . $tag . '>');
            } else {
                $temp_tpl->attach('<ul>');
                foreach ($parts as $i => $part) {
                    if ($i == 0 && str_replace(array('&nbsp;', '<br />', ' '), array('', '', ''), trim($part)) == '') {
                        continue;
                    }
                    $temp_tpl->attach('<li>' . preg_replace('#\\<br /\\>(\\&nbsp;|\\s)*$#D', '', preg_replace('#^\\<br /\\>(\\&nbsp;|\\s)*#D', '', $part)) . '</li>');
                }
                $temp_tpl->attach('</ul>');
            }
            break;
        case 'snapback':
            require_lang('ocf');
            $post_id = intval($embed->evaluate());
            $s_title = $attributes['param'] == '' ? do_lang_tempcode('FORUM_POST_NUMBERED', integer_format($post_id)) : make_string_tempcode($attributes['param']);
            $forum = array_key_exists('forum', $attributes) ? $attributes['forum'] : '';
            $temp_tpl = do_template('COMCODE_SNAPBACK', array('URL' => $GLOBALS['FORUM_DRIVER']->post_url($post_id, $forum), 'TITLE' => $s_title));
            break;
        case 'post':
            require_lang('ocf');
            $post_id = intval($embed->evaluate());
            $s_title = $attributes['param'] == '' ? do_lang_tempcode('FORUM_POST_NUMBERED', integer_format($post_id)) : make_string_tempcode($attributes['param']);
            $forum = array_key_exists('forum', $attributes) ? $attributes['forum'] : '';
            $temp_tpl->attach(hyperlink($GLOBALS['FORUM_DRIVER']->post_url($post_id, $forum), $s_title));
            break;
        case 'topic':
            require_lang('ocf');
            $topic_id = intval($embed->evaluate());
            $s_title = $attributes['param'] == '' ? do_lang_tempcode('FORUM_TOPIC_NUMBERED', integer_format($topic_id)) : make_string_tempcode($attributes['param']);
            $forum = array_key_exists('forum', $attributes) ? $attributes['forum'] : '';
            $temp_tpl->attach(hyperlink($GLOBALS['FORUM_DRIVER']->topic_url($topic_id, $forum), $s_title));
            break;
        case 'staff_note':
            $temp_tpl = new ocp_tempcode();
            return $temp_tpl;
        case 'section':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $name = array_key_exists('param', $attributes) ? $attributes['param'] : 'section' . strval(mt_rand(0, 100));
            $default = array_key_exists('default', $attributes) ? $attributes['default'] : '0';
            $temp_tpl = do_template('COMCODE_SECTION', array('_GUID' => 'a902962ccdc80046c999d6fed907d105', 'PASS_ID' => 'x' . $pass_id, 'DEFAULT' => $default == '1', 'NAME' => $name, 'CONTENT' => $embed));
            break;
        case 'section_controller':
            if ($wml) {
                break;
            }
            $sections = explode(',', $embed->evaluate());
            $temp_tpl = do_template('COMCODE_SECTION_CONTROLLER', array('_GUID' => '133bf24892e9e3ec2a01146d6ec418fe', 'SECTIONS' => $sections, 'PASS_ID' => 'x' . $pass_id));
            break;
        case 'big_tab':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $name = array_key_exists('param', $attributes) ? $attributes['param'] : 'big_tab' . strval(mt_rand(0, 100));
            $default = array_key_exists('default', $attributes) ? $attributes['default'] : '0';
            $temp_tpl = do_template('COMCODE_BIG_TABS_TAB', array('PASS_ID' => 'x' . $pass_id, 'DEFAULT' => $default == '1', 'NAME' => $name, 'CONTENT' => $embed));
            break;
        case 'big_tab_controller':
            if ($wml) {
                break;
            }
            $tabs = explode(',', $embed->evaluate());
            if (!array_key_exists('switch_time', $attributes)) {
                $attributes['switch_time'] = '6000';
            }
            $temp_tpl = do_template('COMCODE_BIG_TABS_CONTROLLER', array('SWITCH_TIME' => $attributes['switch_time'], 'TABS' => $tabs, 'PASS_ID' => 'x' . $pass_id));
            break;
        case 'tab':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $default = array_key_exists('default', $attributes) ? $attributes['default'] : '0';
            $temp_tpl = do_template('COMCODE_TAB_BODY', array('DEFAULT' => $default == '1', 'TITLE' => trim($attributes['param']), 'CONTENT' => $embed));
            break;
        case 'tabs':
            if ($wml) {
                break;
            }
            $heads = new ocp_tempcode();
            $tabs = explode(',', $attributes['param']);
            foreach ($tabs as $i => $tab) {
                $heads->attach(do_template('COMCODE_TAB_HEAD', array('TITLE' => trim($tab), 'FIRST' => $i == 0, 'LAST' => !array_key_exists($i + 1, $tabs))));
            }
            $temp_tpl = do_template('COMCODE_TAB_CONTROLLER', array('HEADS' => $heads, 'CONTENT' => $embed));
            break;
        case 'carousel':
            if ($attributes['param'] == '') {
                $attributes['param'] = '40';
            }
            $temp_tpl = do_template('COMCODE_CAROUSEL', array('CONTENT' => $embed, 'SCROLL_AMOUNT' => $attributes['param']));
            break;
        case 'menu':
            if ($wml) {
                break;
            }
            $name = array_key_exists('param', $attributes) ? $attributes['param'] : 'mnu' . strval(mt_rand(0, 100));
            $type = array_key_exists('type', $attributes) ? $attributes['type'] : 'tree';
            require_code('menus');
            require_code('menus_comcode');
            $temp_tpl = build_comcode_menu($embed->evaluate(), $name, $source_member, $type);
            break;
        case 'if_in_group':
            $groups = '';
            $_groups = explode(',', $attributes['param']);
            $all_groups = $GLOBALS['FORUM_DRIVER']->get_usergroup_list();
            foreach ($_groups as $group) {
                $find = array_search($group, $all_groups);
                if ($find === false) {
                    if ($groups != '') {
                        $groups .= ',';
                    }
                    $groups .= $group;
                } else {
                    if ($groups != '') {
                        $groups .= ',';
                    }
                    $groups .= strval($find);
                }
            }
            $temp_tpl = do_template('COMCODE_IF_IN_GROUP', array('_GUID' => '761a7cc07f7b4b68508d68ce19b87d2c', 'TYPE' => array_key_exists('type', $attributes) ? $attributes['type'] : '', 'CONTENT' => $embed, 'GROUPS' => $groups));
            break;
        case 'acronym':
        case 'abbr':
            $temp_tpl = do_template('COMCODE_ABBR', array('_GUID' => 'acbc4f991dsf03f81b61919b74ac24c91', 'CONTENT' => $embed, 'TITLE' => $attributes['param']));
            break;
        case 'address':
            $temp_tpl = do_template('COMCODE_ADDRESS', array('_GUID' => 'acbcsdf9910703f81b61919b74ac24c91', 'CONTENT' => $embed));
            break;
        case 'dfn':
            $temp_tpl = do_template('COMCODE_DFN', array('_GUID' => 'acbc4f9910703f81b61sf19b74ac24c91', 'CONTENT' => $embed));
            break;
        case 'pulse':
            $min_color = array_key_exists('min', $attributes) ? $attributes['min'] : '0000FF';
            $max_color = array_key_exists('max', $attributes) ? $attributes['max'] : 'FF0044';
            if (substr($min_color, 0, 1) == '#') {
                $min_color = substr($min_color, 1);
            }
            if (substr($max_color, 0, 1) == '#') {
                $max_color = substr($max_color, 1);
            }
            $speed = $attributes['param'] == '' ? 100 : intval($attributes['param']);
            $temp_tpl = do_template('COMCODE_PULSE', array('_GUID' => 'adsd4f9910sfd03f81b61919b74ac24c91', 'RAND_ID' => uniqid('', true), 'CONTENT' => $embed, 'MIN_COLOR' => $min_color, 'MAX_COLOR' => $max_color, 'SPEED' => strval($speed)));
            break;
        case 'del':
            $cite = array_key_exists('cite', $attributes) ? $attributes['cite'] : NULL;
            if (!is_null($cite)) {
                $temp_tpl = test_url($cite, 'del', $cite, $source_member);
            }
            $datetime = array_key_exists('datetime', $attributes) ? $attributes['datetime'] : NULL;
            $temp_tpl->attach(do_template('COMCODE_DEL', array('_GUID' => 'acsd4f9910sfd03f81b61919b74ac24c91', 'CONTENT' => $embed, 'CITE' => $cite, 'DATETIME' => $datetime)));
            break;
        case 'ins':
            $cite = array_key_exists('cite', $attributes) ? $attributes['cite'] : NULL;
            if (!is_null($cite)) {
                $temp_tpl = test_url($cite, 'ins', $cite, $source_member);
                if (!$temp_tpl->is_empty()) {
                    break;
                }
            }
            $datetime = array_key_exists('datetime', $attributes) ? $attributes['datetime'] : NULL;
            $temp_tpl->attach(do_template('COMCODE_INS', array('_GUID' => 'asss4f9910703f81b61919bsfc24c91', 'CONTENT' => $embed, 'CITE' => $cite, 'DATETIME' => $datetime)));
            break;
        case 'cite':
            $temp_tpl = do_template('COMCODE_CITE', array('_GUID' => 'acbcsf910703f81b61919b74ac24c91', 'CONTENT' => $embed));
            break;
        case 'b':
            if ($semiparse_mode) {
                $temp_tpl = make_string_tempcode('<b>' . $embed->evaluate() . '</b>');
                break;
            }
            $temp_tpl = do_template('COMCODE_BOLD', array('_GUID' => 'acbc4fds910703f81b619sf74ac24c91', 'CONTENT' => $embed));
            break;
        case 'align':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $align = array_key_exists('param', $attributes) ? $attributes['param'] : 'left';
            $temp_tpl = do_template('COMCODE_ALIGN', array('_GUID' => '950b4d9db12cac6bf536860bedd96a36', 'ALIGN' => $align, 'CONTENT' => $embed));
            break;
        case 'indent':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $indent = array_key_exists('param', $attributes) ? $attributes['param'] : '10';
            if (!is_numeric($indent)) {
                $indent = '10';
            }
            $temp_tpl = do_template('COMCODE_INDENT', array('_GUID' => 'd8e69fa17eebd5312e3ad5788e3a1343', 'INDENT' => $indent, 'CONTENT' => $embed));
            break;
        case 'surround':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            if ($semiparse_mode && $embed->evaluate() == '') {
                $temp_tpl = make_string_tempcode('<kbd class="ocp_keep" title="no_parse">[surround="' . comcode_escape(array_key_exists('param', $attributes) ? $attributes['param'] : 'float_surrounder') . '"]' . $embed->evaluate() . '[/surround]</kbd>');
                break;
            }
            $class = array_key_exists('param', $attributes) && $attributes['param'] != '' ? $attributes['param'] : 'float_surrounder';
            $temp_tpl = do_template('COMCODE_SURROUND', array('_GUID' => 'e8e69fa17eebd5312e3ad5788e3a1343', 'CLASS' => $class, 'CONTENT' => $embed));
            break;
        case 'i':
            if ($semiparse_mode) {
                $temp_tpl = make_string_tempcode('<i>' . $embed->evaluate() . '</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_ITALICS', array('_GUID' => '4321a1fe3825418e57a29410183c0c60', 'CONTENT' => $embed));
            break;
        case 'u':
            if ($semiparse_mode) {
                $temp_tpl = make_string_tempcode('<u>' . $embed->evaluate() . '</u>');
                break;
            }
            $temp_tpl = do_template('COMCODE_UNDERLINE', array('_GUID' => '69cc8e73b17f9e6a35eb1af2bd1dc6ab', 'CONTENT' => $embed));
            break;
        case 's':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            if ($semiparse_mode) {
                $temp_tpl = make_string_tempcode('<strike>' . $embed->evaluate() . '</strike>');
                break;
            }
            $temp_tpl = do_template('COMCODE_STRIKE', array('_GUID' => 'ed242591cefd365497cc0c63abbb11a9', 'CONTENT' => $embed));
            break;
        case 'tooltip':
            $param = is_object($attributes['param']) ? $attributes['param'] : comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
            if ($wml) {
                $temp_tpl->attach($embed);
                $temp_tpl->attach('[ ');
                $temp_tpl->attach($param);
                $temp_tpl->attach(' ]');
                break;
            }
            $temp_tpl = do_template('COMCODE_TOOLTIP', array('_GUID' => 'c9f4793dc0c1a92cd7d08ae1b87c2308', 'URL' => array_key_exists('url', $attributes) ? $attributes['url'] : '', 'TOOLTIP' => $param, 'CONTENT' => $embed));
            break;
        case 'sup':
            if ($wml) {
                $temp_tpl->attach('^');
                $temp_tpl->attach($embed);
                break;
            }
            $temp_tpl = do_template('COMCODE_SUP', array('_GUID' => '74d2ecfe193dacb6d922bc288828196a', 'CONTENT' => $embed));
            break;
        case 'sub':
            if ($wml) {
                $temp_tpl->attach('{');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('}');
                break;
            }
            $temp_tpl = do_template('COMCODE_SUB', array('_GUID' => '515e310e00a6d7c30f7dca0a5956ebcf', 'CONTENT' => $embed));
            break;
        case 'title':
            if ($semiparse_mode && strpos($comcode, '[contents') !== false) {
                $temp_tpl = make_string_tempcode('[title' . reinsert_parameters($attributes) . ']' . $embed->evaluate() . '[/title]');
                break;
            }
            $level = $attributes['param'] != '' ? intval($attributes['param']) : 1;
            if ($level == 0) {
                $level = 1;
            }
            // Stop crazy Comcode causing stack errors with the toc
            $uniq_id = strval(count($STRUCTURE_LIST));
            $STRUCTURE_LIST[] = array($level, $embed, $uniq_id);
            if ($level == 1) {
                $template = 'SCREEN_TITLE';
            } elseif ($level == 2) {
                $template = 'COMCODE_SECTION_TITLE';
            } elseif ($level == 3) {
                $template = 'COMCODE_MINOR_TITLE';
            } elseif ($level == 4) {
                $template = 'COMCODE_VERY_MINOR_TITLE';
            } else {
                $template = 'COMCODE_VERY_MINOR_TITLE';
            }
            if ($level == 1) {
                if (is_null($COMCODE_PARSE_TITLE)) {
                    $COMCODE_PARSE_TITLE = $embed->evaluate();
                    if (is_object($COMCODE_PARSE_TITLE)) {
                        $COMCODE_PARSE_TITLE = $COMCODE_PARSE_TITLE->evaluate();
                    }
                }
            }
            $base = array_key_exists('base', $attributes) ? intval($attributes['base']) : 2;
            if (array_key_exists('number', $attributes) && $level >= $base) {
                $list_types = $attributes['number'] == '' ? array() : explode(',', $attributes['number']);
                $list_types = array_merge($list_types, array('decimal', 'lower-alpha', 'lower-roman', 'upper-alpha', 'upper-roman', 'disc'));
                $numerals = array('i', 'ii', 'iii', 'iv', 'v', 'vi', 'viii', 'ix', 'x', 'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'xvii', 'xviii', 'xix', 'xx');
                $symbol_lookup = array('decimal' => range(1, 100), 'lower-alpha' => range('a', 'z'), 'lower-roman' => $numerals, 'upper-alpha' => range('A', 'Z'), 'upper-roman' => str_replace('i', 'I', str_replace('v', 'V', str_replace('x', 'X', $numerals))));
                $level_text = '';
                $list_pos = count($STRUCTURE_LIST) - 2;
                for ($j = $level; $j >= $base; $j--) {
                    $num_before = 0;
                    for ($i = $list_pos; $i >= 0; $i--) {
                        $list_pos--;
                        if ($STRUCTURE_LIST[$i][0] == $j - 1) {
                            break;
                        }
                        if ($STRUCTURE_LIST[$i][0] == $j) {
                            $num_before++;
                        }
                    }
                    $level_number = @strval($symbol_lookup[$list_types[$j - $base]][$num_before]);
                    $level_text = $level_number . ($level_text != '' ? '.' : '') . $level_text;
                }
                $old_embed = $embed;
                $embed = make_string_tempcode($level_text . ' &ndash; ');
                $embed->attach($old_embed);
            }
            if ($wml) {
                if ($level == 1) {
                    $temp_tpl->attach('<br /><p><big><u><b>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</b></u></big></p><br />');
                } elseif ($level == 2) {
                    $temp_tpl->attach('<br /><p><big><u>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</u></big></p><br />');
                } elseif ($level == 3) {
                    $temp_tpl->attach('<br /><p><big>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</big></p><br />');
                } elseif ($level == 4) {
                    $temp_tpl->attach('<br /><p>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</p><br />');
                }
                break;
            }
            if ($semiparse_mode) {
                $temp_tpl = make_string_tempcode('<h' . strval($level) . ($level == 1 ? ' class="main_page_title"' : '') . '><span class="inner">' . $embed->evaluate() . '</span></h' . strval($level) . '>');
                break;
            }
            $tpl_map = array('ID' => substr($pass_id, 0, 5) == 'panel' ? NULL : $uniq_id, 'TITLE' => $embed, 'HELP_URL' => '', 'HELP_TERM' => '');
            if (array_key_exists('sub', $attributes)) {
                $tpl_map['SUB'] = protect_from_escaping(comcode_to_tempcode($attributes['sub'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member));
            }
            $temp_tpl = do_template($template, $tpl_map);
            break;
        case 'attachment':
        case 'attachment2':
            // legacy
        // legacy
        case 'attachment_safe':
            if ($wml) {
                break;
            }
            require_code('attachments');
            if (is_null($on_behalf_of_member)) {
                $on_behalf_of_member = $source_member;
            }
            $id = $embed->evaluate();
            global $COMCODE_ATTACHMENTS;
            if (!is_numeric($id) && !$as_admin && !has_specific_permission($source_member, 'exceed_filesize_limit')) {
                // We work all this out before we do any downloads, to make sure orphaned files aren't dumped on the file system (possible hack method)
                if (get_forum_type() == 'ocf') {
                    require_lang('ocf');
                    require_code('ocf_groups');
                    $daily_quota = ocf_get_member_best_group_property($source_member, 'max_daily_upload_mb');
                } else {
                    $daily_quota = 5;
                    // 5 is a hard coded default for non-OCF forums
                }
                if (!is_null($daily_quota)) {
                    $_size_uploaded_today = $connection->query('SELECT SUM(a_file_size) AS the_answer FROM ' . $connection->get_table_prefix() . 'attachments WHERE a_member_id=' . strval((int) $source_member) . ' AND a_add_time>' . strval(time() - 60 * 60 * 24));
                    if (is_null($_size_uploaded_today[0]['the_answer'])) {
                        $_size_uploaded_today[0]['the_answer'] = 0;
                    }
                    $size_uploaded_today = ceil((double) $_size_uploaded_today[0]['the_answer'] / 1024.0 / 1024.0);
                    $attach_size = 0;
                    require_code('uploads');
                    is_swf_upload(true);
                    foreach ($_FILES as $_file) {
                        $attach_size += floatval($_file['size']) / 1024.0 / 1024.0;
                    }
                    if ($size_uploaded_today + $attach_size > floatval($daily_quota)) {
                        $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('OVER_DAILY_QUOTA', integer_format($daily_quota), float_format($size_uploaded_today))));
                        break;
                    }
                }
            }
            $thumb_url = array_key_exists('thumb_url', $attributes) ? $attributes['thumb_url'] : '';
            // Embedded attachments
            if (!is_numeric($id) && substr($id, 0, 4) != 'new_' && substr($id, 0, 4) != 'url_') {
                $file = base64_decode(str_replace(chr(10), '', $id));
                if ($file === false) {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('comcode:CORRUPT_ATTACHMENT')));
                    break;
                }
                $md5 = md5(substr($file, 0, 30));
                $original_filename = array_key_exists('filename', $attributes) ? $attributes['filename'] : $md5 . '.dat';
                if (get_file_extension($original_filename) != 'dat') {
                    require_code('files2');
                    check_extension($original_filename, true);
                    $new_filename = $md5 . '.' . get_file_extension($original_filename) . '.dat';
                } else {
                    $new_filename = $md5 . '.' . get_file_extension($original_filename);
                }
                $path = get_custom_file_base() . '/uploads/attachments/' . $new_filename;
                $myfile = @fopen($path, 'wb');
                if ($myfile === false) {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => intelligent_write_error_inline($path)));
                    break;
                }
                if (fwrite($myfile, $file) < strlen($file)) {
                    warn_exit(do_lang_tempcode('COULD_NOT_SAVE_FILE'));
                }
                fclose($myfile);
                fix_permissions($path);
                sync_file($path);
                $_size = strlen($file);
                $url = 'uploads/attachments/' . $new_filename;
                if ($connection->connection_write != $GLOBALS['SITE_DB']->connection_write) {
                    $url = get_custom_base_url() . '/' . $url;
                }
                // Thumbnail
                if ($thumb_url == '') {
                    require_code('images');
                    if (is_image($original_filename)) {
                        $gd = get_option('is_on_gd') == '1' && function_exists('imagetypes');
                        if ($gd) {
                            require_code('images');
                            if (!is_saveable_image($url)) {
                                $ext = '.png';
                            } else {
                                $ext = '.' . get_file_extension($original_filename);
                            }
                            $thumb_url = 'uploads/attachments_thumbs/' . $md5 . $ext;
                            convert_image(get_custom_base_url() . '/' . $url, get_custom_file_base() . '/' . $thumb_url, -1, -1, intval(get_option('thumb_width')), true, NULL, false, true);
                            if ($connection->connection_write != $GLOBALS['SITE_DB']->connection_write) {
                                $thumb_url = get_custom_base_url() . '/' . $thumb_url;
                            }
                        } else {
                            $thumb_url = $url;
                        }
                    }
                }
                if (addon_installed('galleries')) {
                    require_code('images');
                    if (is_video($url) && $connection->connection_read == $GLOBALS['SITE_DB']->connection_read) {
                        require_code('transcoding');
                        $url = transcode_video($url, 'attachments', 'a_url', 'a_original_filename', NULL, NULL);
                    }
                }
                $attachment = array('a_member_id' => $on_behalf_of_member, 'a_file_size' => $_size, 'a_url' => $url, 'a_thumb_url' => $thumb_url, 'a_original_filename' => $original_filename, 'a_num_downloads' => 0, 'a_last_downloaded_time' => NULL, 'a_add_time' => time());
                $attachment['a_description'] = array_key_exists('description', $attributes) ? is_object($attributes['description']) ? '[html]' . $attributes['description']->evaluate() . '[/html]' : $attributes['description'] : '';
                $attach_id = $connection->query_insert('attachments', $attachment, true);
                $attachment['id'] = $attach_id;
                // Create and document attachment
                if (!array_key_exists('type', $attributes)) {
                    $attributes['type'] = 'auto';
                }
                $COMCODE_ATTACHMENTS[$pass_id][] = array('tag_type' => $tag, 'type' => 'new', 'attachmenttype' => $attributes['type'], 'description' => $attachment['a_description'], 'id' => intval($attach_id), 'marker' => $marker, 'comcode' => $comcode);
                // Marker will allow us to search back and replace this with the added id
            } elseif (!is_numeric($id)) {
                require_code('uploads');
                if (substr($id, 0, 4) == 'new_') {
                    $_id = substr($id, 4);
                    if (!is_numeric($_id)) {
                        $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('comcode:INVALID_ATTACHMENT')));
                        break;
                    }
                    $attributes['type'] = post_param('attachmenttype' . $_id, array_key_exists('type', $attributes) ? $attributes['type'] : 'auto');
                    if (substr($attributes['type'], -8) == '_extract') {
                        $attributes['type'] = substr($attributes['type'], 0, strlen($attributes['type']) - 8);
                    }
                    $urls = get_url('', 'file' . $_id, 'uploads/attachments', 2, OCP_UPLOAD_ANYTHING, (!array_key_exists('thumb', $attributes) || $attributes['thumb'] != '0') && $thumb_url == '', '', '', true, true, true);
                    if ($urls[0] == '') {
                        return new ocp_tempcode();
                    }
                    //warn_exit(do_lang_tempcode('ERROR_UPLOADING'));  Can't do this, because this might not be post-calculated if something went wrong once
                    is_swf_upload(true);
                    $_size = $_FILES['file' . $_id]['size'];
                    $original_filename = $_FILES['file' . $_id]['name'];
                    if (get_magic_quotes_gpc()) {
                        $original_filename = stripslashes($original_filename);
                    }
                } elseif (substr($id, 0, 4) == 'url_') {
                    if (!has_specific_permission($source_member, 'draw_to_server') && !$as_admin) {
                        break;
                    }
                    $_id = '!';
                    $attributes['type'] = post_param('attachmenttype' . $_id, array_key_exists('type', $attributes) ? $attributes['type'] : 'auto');
                    $url = remove_url_mistakes(substr($id, 4));
                    $_POST['_specify_url'] = $url;
                    // Little hack, as we need to read it from a POST
                    if (get_magic_quotes_gpc()) {
                        $_POST['_specify_url'] = addslashes($_POST['_specify_url']);
                    }
                    $urls = get_url('_specify_url', '', 'uploads/filedump', 1, OCP_UPLOAD_ANYTHING, (!array_key_exists('thumb', $attributes) || $attributes['thumb'] != '0') && $thumb_url == '', '', '', true, true);
                    if ($urls[0] == '') {
                        return new ocp_tempcode();
                    }
                    $original_filename = rawurldecode(substr($url, strrpos($url, '/') + 1));
                    if (url_is_local($urls[0])) {
                        $_size = @filesize(get_custom_file_base() . '/' . rawurldecode($urls[0]));
                        if ($_size === false) {
                            $_size = filesize(get_file_base() . '/' . rawurldecode($urls[0]));
                        }
                    } else {
                        $_size = 0;
                    }
                } else {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('comcode:INVALID_ATTACHMENT')));
                    break;
                }
                if ($urls[0] == '') {
                    require_code('images');
                    require_code('files2');
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('ATTACHMENT_WOULD_NOT_UPLOAD', float_format(get_max_file_size() / 1024 / 1024), float_format(get_max_image_size() / 1024 / 1024))));
                    break;
                }
                $url = $urls[0];
                if ($connection->connection_write != $GLOBALS['SITE_DB']->connection_write) {
                    $url = get_custom_base_url() . '/' . $url;
                }
                if ($thumb_url == '') {
                    $thumb_url = array_key_exists(1, $urls) ? $urls[1] : '';
                }
                if ($thumb_url != '' && $connection != $GLOBALS['SITE_DB']) {
                    $thumb_url = get_custom_base_url() . '/' . $thumb_url;
                }
                $num_downloads = 0;
                $last_downloaded_time = NULL;
                $add_time = time();
                $member_id = $on_behalf_of_member;
                if (addon_installed('galleries')) {
                    require_code('images');
                    if (is_video($url) && $connection->connection_read == $GLOBALS['SITE_DB']->connection_read) {
                        require_code('transcoding');
                        $url = transcode_video($url, 'attachments', 'a_url', 'a_original_filename', NULL, NULL);
                    }
                }
                $attachment = array('a_member_id' => $member_id, 'a_file_size' => $_size, 'a_url' => $url, 'a_thumb_url' => $thumb_url, 'a_original_filename' => $original_filename, 'a_num_downloads' => $num_downloads, 'a_last_downloaded_time' => $last_downloaded_time, 'a_add_time' => $add_time);
                $attachment['a_description'] = post_param('caption' . $_id, array_key_exists('description', $attributes) ? is_object($attributes['description']) ? '[html]' . $attributes['description']->evaluate() . '[/html]' : $attributes['description'] : '');
                $attach_id = $connection->query_insert('attachments', $attachment, true);
                $attachment['id'] = $attach_id;
                if ($tag == 'attachment2' || $tag == 'attachment_safe' || substr($id, 0, 4) == 'url_') {
                    $connection->query_delete('attachment_refs', array('r_referer_type' => 'null', 'r_referer_id' => '', 'a_id' => $attachment['id']), '', 1);
                    $connection->query_insert('attachment_refs', array('r_referer_type' => 'null', 'r_referer_id' => '', 'a_id' => $attachment['id']));
                }
                // Create and document attachment
                $COMCODE_ATTACHMENTS[$pass_id][] = array('tag_type' => $tag, 'time' => time(), 'type' => substr($id, 0, 4) == 'new_' ? 'new' : 'url', 'attachmenttype' => $attributes['type'], 'description' => $attachment['a_description'], 'id' => intval($attach_id), 'marker' => $marker, 'comcode' => $comcode);
                // Marker will allow us to search back and replace this with the added id
                // Existing attachments
            } else {
                $__id = intval($id);
                // Check we have permission to re-use this
                $owner = $connection->query_value_null_ok('attachments', 'a_member_id', array('id' => $__id));
                if (is_null($owner)) {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('MISSING_RESOURCE_COMCODE', 'attachment', escape_html(strval($__id)))));
                    if (!in_array(get_page_name(), $GLOBALS['DONT_CARE_MISSING_PAGES']) && !running_script('iframe')) {
                        require_code('failure');
                        relay_error_notification(do_lang('MISSING_RESOURCE_COMCODE', 'attachment', strval($__id)), false, $GLOBALS['FORUM_DRIVER']->is_staff($source_member) ? 'error_occurred_missing_reference_important' : 'error_occurred_missing_reference');
                    }
                    break;
                }
                $_attachment = $connection->query_select('attachments', array('*'), array('id' => $__id), '', 1);
                $attachment = $_attachment[0];
                $already_referenced = array_key_exists($__id, $GLOBALS['ATTACHMENTS_ALREADY_REFERENCED']);
                if ($already_referenced || $as_admin || $source_member === $owner || (has_specific_permission($source_member, 'reuse_others_attachments') || $owner == $source_member) && has_attachment_access($source_member, $__id)) {
                    if (!array_key_exists('type', $attributes)) {
                        $attributes['type'] = 'auto';
                    }
                    $COMCODE_ATTACHMENTS[$pass_id][] = array('tag_type' => $tag, 'time' => $attachment['a_add_time'], 'type' => 'existing', 'id' => $__id, 'attachmenttype' => $attributes['type'], 'marker' => $marker, 'comcode' => $comcode);
                } else {
                    require_lang('permissions');
                    $username = $GLOBALS['FORUM_DRIVER']->get_username($source_member);
                    if (is_null($username)) {
                        $username = do_lang('DELETED');
                    }
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('permissions:ACCESS_DENIED__REUSE_ATTACHMENT', $username)));
                    break;
                    //access_denied('REUSE_ATTACHMENT');
                }
                if ($connection->connection_write != $GLOBALS['SITE_DB']->connection_write) {
                    if (url_is_local($attachment['a_url'])) {
                        $attachment['a_url'] = get_custom_base_url() . '/' . $attachment['a_url'];
                    }
                    if (url_is_local($attachment['a_url'])) {
                        $attachment['a_thumb_url'] = get_custom_base_url() . '/' . $attachment['a_thumb_url'];
                    }
                }
                $attachment['a_description'] = array_key_exists('description', $attributes) ? is_object($attributes['description']) ? '[html]' . $attributes['description']->evaluate() . '[/html]' : $attributes['description'] : $attachment['a_description'];
            }
            // Now, render it
            // ==============
            $temp_tpl = render_attachment($tag, $attributes, $attachment, $pass_id, $source_member, $as_admin, $connection, $highlight_bits, $on_behalf_of_member, $semiparse_mode);
            if (array_key_exists('float', $attributes)) {
                $temp_tpl = do_template('FLOATER', array('_GUID' => '802fe29019be80993296de7cc8b5cc5e', 'FLOAT' => $attributes['float'], 'CONTENT' => $temp_tpl));
            }
            break;
        case 'include':
            $codename = $embed->evaluate();
            $zone = $attributes['param'];
            if ($zone == '_SEARCH') {
                $zone = get_comcode_zone($codename);
            }
            if ($zone == '_SELF') {
                $zone = get_zone_name();
            }
            $temp_comcode_parse_title = $COMCODE_PARSE_TITLE;
            $temp = request_page($codename, false, $zone, NULL, true);
            $COMCODE_PARSE_TITLE = $temp_comcode_parse_title;
            if ($temp->is_empty()) {
                $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('MISSING_RESOURCE_COMCODE', 'include', hyperlink(build_url(array('page' => 'cms_comcode_pages', 'type' => '_ed', 'page_link' => $zone . ':' . $codename), get_module_zone('cms_comcode_pages')), $zone . ':' . $codename, false, true))));
                if (!in_array(get_page_name(), $GLOBALS['DONT_CARE_MISSING_PAGES']) && !running_script('iframe')) {
                    require_code('failure');
                    relay_error_notification(do_lang('MISSING_RESOURCE_COMCODE', 'include', $zone . ':' . $codename), false, $GLOBALS['FORUM_DRIVER']->is_staff($source_member) ? 'error_occurred_missing_reference_important' : 'error_occurred_missing_reference');
                }
            } else {
                $temp_tpl = symbol_tempcode('LOAD_PAGE', array($codename, $zone));
            }
            break;
        case 'random':
            unset($attributes['param']);
            if ($wml) {
                $top_attribute = array_pop($attributes);
                $temp_tpl = is_object($top_attribute) ? $top_attribute : comcode_to_tempcode($top_attribute, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                break;
            }
            $max = $embed->evaluate() == '' ? intval($embed->evaluate()) : 0;
            foreach ($attributes as $num => $val) {
                $_temp = is_object($val) ? $val : comcode_to_tempcode($val, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                $attributes[$num] = $_temp->evaluate();
                if (intval($num) > $max) {
                    $max = intval($num);
                }
            }
            $_parts = new ocp_tempcode();
            krsort($attributes);
            foreach ($attributes as $num => $val) {
                $_parts->attach(do_template('COMCODE_RANDOM_PART', array('_GUID' => '5fa49a916304f9caa0ddedeb01531142', 'NUM' => strval($num), 'VAL' => $val)));
            }
            $temp_tpl = do_template('COMCODE_RANDOM', array('_GUID' => '9b77aaf593b12c763fb0c367fab415b6', 'UNIQID' => uniqid('', true), 'FULL' => $embed, 'MAX' => strval($max), 'PARTS' => $_parts));
            break;
        case 'jumping':
            unset($attributes['param']);
            if ($wml) {
                $top_attribute = array_pop($attributes);
                $temp_tpl = is_object($top_attribute) ? $top_attribute : comcode_to_tempcode($top_attribute, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                break;
            }
            $_parts = new ocp_tempcode();
            foreach ($attributes as $val) {
                $_temp = is_object($val) ? $val : comcode_to_tempcode($val, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                $_parts->attach(do_template('COMCODE_JUMPING_PART', array('_GUID' => 'd163bd11920f39f0cb8ff2f6ba48bc80', 'PART' => $_temp->evaluate())));
            }
            $embed = $embed->evaluate();
            $temp_tpl = do_template('COMCODE_JUMPING', array('_GUID' => '85e9f83ed134868436a7db7692f56047', 'UNIQID' => uniqid('', true), 'FULL' => implode(', ', $attributes), 'TIME' => strval((int) $embed), 'PARTS' => $_parts));
            break;
        case 'shocker':
            if ($wml) {
                $top_attribute = array_pop($attributes);
                $temp_tpl = is_object($top_attribute) ? $top_attribute : comcode_to_tempcode($top_attribute, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                break;
            }
            $_parts = new ocp_tempcode();
            foreach ($attributes as $key => $val) {
                if (substr($key, 0, 5) == 'left_') {
                    $left = $val;
                    $right = array_key_exists('right_' . substr($key, 5), $attributes) ? $attributes['right_' . substr($key, 5)] : '';
                    $left = is_object($left) ? $left : comcode_to_tempcode($left, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                    $right = is_object($right) ? $right : comcode_to_tempcode($right, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                    $_parts->attach(do_template('COMCODE_SHOCKER_PART', array('LEFT' => $left, 'RIGHT' => $right)));
                }
            }
            $min_color = array_key_exists('min', $attributes) ? $attributes['min'] : '0000FF';
            $max_color = array_key_exists('max', $attributes) ? $attributes['max'] : 'FF0044';
            if (substr($min_color, 0, 1) == '#') {
                $min_color = substr($min_color, 1);
            }
            if (substr($max_color, 0, 1) == '#') {
                $max_color = substr($max_color, 1);
            }
            $embed = $embed->evaluate();
            $temp_tpl = do_template('COMCODE_SHOCKER', array('UNIQID' => uniqid('', true), 'MIN_COLOR' => $min_color, 'MAX_COLOR' => $max_color, 'FULL' => implode(', ', $attributes), 'TIME' => strval(intval($embed)), 'PARTS' => $_parts));
            break;
        case 'ticker':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $width = $attributes['param'];
            if (!is_numeric($width)) {
                $width = '300';
            }
            $fspeed = array_key_exists('speed', $attributes) ? float_to_raw_string(floatval($attributes['speed'])) : '1';
            $temp_tpl = do_template('COMCODE_TICKER', array('_GUID' => 'e48893cda61995261577f0556443c537', 'UNIQID' => uniqid('', true), 'SPEED' => $fspeed, 'WIDTH' => $width, 'TEXT' => $embed));
            break;
        case 'highlight':
            if ($wml) {
                $temp_tpl->attach('<i>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_HIGHLIGHT', array('_GUID' => '695d041b6605f06ec2aeee1e82f87185', 'CONTENT' => $embed));
            break;
        case 'size':
            $size = array_key_exists('param', $attributes) ? $attributes['param'] : '1';
            if ($wml) {
                if (floatval($size) >= 1.5) {
                    $temp_tpl->attach('<big>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</big>');
                } elseif (floatval($size) < 0.8) {
                    $temp_tpl->attach('<small>');
                    $temp_tpl->attach($embed);
                    $temp_tpl->attach('</small>');
                } else {
                    $temp_tpl->attach($embed);
                }
                break;
            }
            if (is_numeric($size)) {
                $size = 'font-size: ' . $size . 'em;';
            } elseif (substr($size, 0, 1) == '+') {
                $size = 'font-size: ' . substr($size, 1) . 'em';
            } elseif (substr($size, -1) == '%') {
                $size = 'font-size: ' . float_to_raw_string(floatval(substr($size, 0, strlen($size) - 1)) / 100.0) . 'em';
            } elseif (substr($size, -2) == 'of') {
                $new_size = '1em';
                switch ($size) {
                    case '1of':
                        $new_size = '8pt';
                        break;
                    case '2of':
                        $new_size = '10pt';
                        break;
                    case '3of':
                        $new_size = '12pt';
                        break;
                    case '4of':
                        $new_size = '14pt';
                        break;
                    case '5of':
                        $new_size = '18pt';
                        break;
                    case '6of':
                        $new_size = '24pt';
                        break;
                    case '7of':
                        $new_size = '36pt';
                        break;
                }
                $size = 'font-size: ' . $new_size;
            } else {
                $size = 'font-size: ' . $size;
            }
            $size_len = strlen($size);
            filter_html($as_admin, $source_member, 0, $size_len, $size, false, false);
            $temp_tpl = do_template('COMCODE_FONT', array('_GUID' => 'fb23fdcb45aabdfeca9f37ed8098948e', 'CONTENT' => $embed, 'SIZE' => $size, 'COLOR' => '', 'FACE' => ''));
            break;
        case 'color':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            $color = array_key_exists('param', $attributes) ? 'color: ' . $attributes['param'] . ';' : '';
            $temp_tpl = do_template('COMCODE_FONT', array('_GUID' => 'bd146414c9239ba2076f4b683df437d7', 'CONTENT' => $embed, 'SIZE' => '', 'COLOR' => $color, 'FACE' => ''));
            $color_len = strlen($color);
            filter_html($as_admin, $source_member, 0, $color_len, $color, false, false);
            break;
        case 'tt':
            if ($wml) {
                $temp_tpl->attach('<i>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_TELETYPE', array('CONTENT' => $embed));
            break;
        case 'samp':
            if ($wml) {
                $temp_tpl->attach('<i>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_SAMP', array('CONTENT' => $embed));
            break;
        case 'q':
            if ($wml) {
                $temp_tpl->attach('<i>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_Q', array('CONTENT' => $embed));
            break;
        case 'var':
            if ($wml) {
                $temp_tpl->attach('<i>');
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</i>');
                break;
            }
            $temp_tpl = do_template('COMCODE_VAR', array('CONTENT' => $embed));
            break;
        case 'font':
            $face = $attributes['param'];
            if ($face == '' && array_key_exists('face', $attributes)) {
                $face = $attributes['face'];
            }
            $color = array_key_exists('color', $attributes) ? $attributes['color'] : '';
            $size = array_key_exists('size', $attributes) ? $attributes['size'] : '';
            if ($face == '/') {
                $face = '';
            }
            if ($color == '/') {
                $color = '';
            }
            if ($size == '/') {
                $size = '';
            }
            if ($wml) {
                $before = '';
                $after = '';
                if ($size != '') {
                    if (floatval($size) >= 1.5) {
                        $before = '<big>';
                        $after = '</big>';
                    } elseif (floatval($size) < 0.8) {
                        $before = '<small>';
                        $after = '</small>';
                    }
                }
                $temp_tpl->attach($before);
                $temp_tpl->attach($embed);
                $temp_tpl->attach($after);
                break;
            }
            if ($color != '') {
                $color = 'color: ' . $color . ';';
            }
            if ($size != '') {
                if (is_numeric($size)) {
                    $size = 'font-size: ' . $size . 'em;';
                } elseif (substr($size, 0, 1) == '+') {
                    $size = 'font-size: ' . substr($size, 1) . 'em';
                } elseif (substr($size, -1) == '%') {
                    $size = 'font-size: ' . float_to_raw_string(floatval(substr($size, 0, strlen($size) - 1)) / 100.0) . 'em';
                } elseif (substr($size, -2) == 'of') {
                    $new_size = '1em';
                    switch ($size) {
                        case '1of':
                            $new_size = '8pt';
                            break;
                        case '2of':
                            $new_size = '10pt';
                            break;
                        case '3of':
                            $new_size = '12pt';
                            break;
                        case '4of':
                            $new_size = '14pt';
                            break;
                        case '5of':
                            $new_size = '18pt';
                            break;
                        case '6of':
                            $new_size = '24pt';
                            break;
                        case '7of':
                            $new_size = '36pt';
                            break;
                    }
                    $size = 'font-size: ' . $new_size;
                } else {
                    $size = 'font-size: ' . $size;
                }
            }
            if ($face != '') {
                $face = 'font-family: ' . str_replace('\'', '', $face) . ';';
            }
            $size_len = strlen($size);
            filter_html($as_admin, $source_member, 0, $size_len, $size, false, false);
            $color_len = strlen($color);
            filter_html($as_admin, $source_member, 0, $color_len, $color, false, false);
            $face_len = strlen($face);
            filter_html($as_admin, $source_member, 0, $face_len, $face, false, false);
            $temp_tpl = do_template('COMCODE_FONT', array('_GUID' => 'f5fcafe737b8fdf466a6a51773e09c9b', 'CONTENT' => $embed, 'SIZE' => $size, 'COLOR' => $color, 'FACE' => $face));
            break;
        case 'box':
            if ($wml) {
                $temp_tpl->attach('<br /><p>');
                if ($attributes['param'] != '') {
                    $temp_tpl->attach('<big>');
                    $temp_tpl->attach($attributes['param']);
                    $temp_tpl->attach('</big><br /><br />');
                }
                $temp_tpl->attach($embed);
                $temp_tpl->attach('</p></br />');
                break;
            }
            // Legacy parameter. There used to be 'place' and 'nowrap' and 'class', but these are now gone.
            $breadth = array_key_exists('breadth', $attributes) ? $attributes['breadth'] : '100%';
            if ($breadth == 'WIDE') {
                $breadth = '100%';
            }
            if ($breadth == 'WIDE_HIGH') {
                $breadth = '100%';
            }
            if ($breadth == 'THIN') {
                $breadth = 'auto';
            }
            // The new versions
            $dimensions = array_key_exists('dimensions', $attributes) ? comcode_to_tempcode($attributes['dimensions'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member) : make_string_tempcode($breadth);
            $type = array_key_exists('type', $attributes) ? $attributes['type'] : '';
            $options = array_key_exists('options', $attributes) ? $attributes['options'] : '';
            $meta = $comcode_dangerous && array_key_exists('meta', $attributes) ? $attributes['meta'] : '';
            //Insecure, unneeded here
            $links = $comcode_dangerous && array_key_exists('links', $attributes) ? $attributes['links'] : '';
            //Insecure, unneeded here
            $converted = is_object($attributes['param']) ? $attributes['param'] : comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
            $temp_tpl = directive_tempcode('BOX', $embed, array($converted, $dimensions, make_string_tempcode($type), make_string_tempcode($options), make_string_tempcode($meta), make_string_tempcode($links)));
            if (array_key_exists('float', $attributes)) {
                $temp_tpl = do_template('FLOATER', array('_GUID' => '54e8fc9ec1e16cfc5c8824e22f1e8745', 'FLOAT' => $attributes['float'], 'CONTENT' => $temp_tpl));
            }
            break;
        case 'concept':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            if (!array_key_exists('param', $attributes) || $attributes['param'] == '') {
                $key = $embed->evaluate();
                $temp_tpl = symbol_tempcode('DISPLAY_CONCEPT', array($key));
            } else {
                $temp_tpl = do_template('COMCODE_CONCEPT_INLINE', array('_GUID' => '381a59de4d6f8967446c12bf4641a9ce', 'TEXT' => $embed, 'FULL' => $attributes['param']));
            }
            break;
        case 'concepts':
            if ($wml) {
                break;
            }
            $title = $embed->evaluate();
            $concepts = new ocp_tempcode();
            foreach ($attributes as $_key => $_value) {
                if (substr($_key, -4) == '_key') {
                    $key = $_value;
                    $cid = substr($_key, 0, strlen($_key) - 4);
                    $to_parse = array_key_exists($cid . '_value', $attributes) ? $attributes[$cid . '_value'] : new ocp_tempcode();
                    $value = is_object($to_parse) ? $to_parse : comcode_to_tempcode($to_parse, $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                    $concepts->attach(do_template('COMCODE_CONCEPTS_CONCEPT', array('_GUID' => '4baf6dabc32146c594c7fd922791b6b2', 'A' => 'concept___' . preg_replace('#[^\\w]#', '_', $key), 'KEY' => $key, 'VALUE' => $value)));
                }
            }
            $temp_tpl = do_template('COMCODE_CONCEPTS', array('_GUID' => '4c7a1d70753dc1d209b9951aa10f361a', 'TITLE' => $title, 'CONCEPTS' => $concepts));
            break;
        case 'exp_ref':
            if ($wml) {
                break;
            }
            $_embed = $embed->evaluate();
            if (strpos($_embed, '.') !== false) {
                break;
            }
            $stub = get_file_base() . '/data_custom/images/' . get_zone_name() . '/';
            $stub2 = get_base_url() . '/data_custom/images/' . get_zone_name() . '/';
            if (!file_exists($stub)) {
                $stub = get_file_base() . '/data/images/' . get_zone_name() . '/';
                $stub2 = get_base_url() . '/data/images/' . get_zone_name() . '/';
            }
            if (!file_exists($stub)) {
                $stub = get_file_base() . '/data_custom/images/';
                $stub2 = get_base_url() . '/data_custom/images/';
            }
            if (!file_exists($stub)) {
                $stub = get_file_base() . '/data/images/';
                $stub2 = get_base_url() . '/data/images/';
            }
            if (substr($_embed, 0, 1) == '/') {
                $_embed = substr($_embed, 1);
            }
            if (file_exists($stub . $_embed . '.png')) {
                $url = $stub2 . $_embed . '.png';
            } elseif (file_exists($stub . $_embed . '.gif')) {
                $url = $stub2 . $_embed . '.gif';
            } elseif (file_exists($stub . $_embed . '.jpg')) {
                $url = $stub2 . $_embed . '.jpg';
            } elseif (file_exists($stub . $_embed . '.jpeg')) {
                $url = $stub2 . $_embed . '.jpeg';
            } else {
                $stub = get_file_base() . '/data/images/docs/';
                $stub2 = get_base_url() . '/data/images/docs/';
                if (substr($_embed, 0, 1) == '/') {
                    $_embed = substr($_embed, 1);
                }
                if (file_exists($stub . $_embed . '.png')) {
                    $url = $stub2 . $_embed . '.png';
                } elseif (file_exists($stub . $_embed . '.gif')) {
                    $url = $stub2 . $_embed . '.gif';
                } elseif (file_exists($stub . $_embed . '.jpg')) {
                    $url = $stub2 . $_embed . '.jpg';
                } elseif (file_exists($stub . $_embed . '.jpeg')) {
                    $url = $stub2 . $_embed . '.jpeg';
                } else {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('MISSING_RESOURCE_COMCODE', 'exp_ref', escape_html($_embed))));
                    if (array_key_exists('COMCODE_BROKEN_URLS', $GLOBALS)) {
                        $GLOBALS['COMCODE_BROKEN_URLS'][] = array($_embed, NULL);
                    } elseif (!in_array(get_page_name(), $GLOBALS['DONT_CARE_MISSING_PAGES']) && !running_script('iframe')) {
                        require_code('failure');
                        relay_error_notification(do_lang('MISSING_RESOURCE_COMCODE', 'exp_ref', $_embed), false, $GLOBALS['FORUM_DRIVER']->is_staff($source_member) ? 'error_occurred_missing_reference_important' : 'error_occurred_missing_reference');
                    }
                    break;
                }
            }
            $text = make_string_tempcode($attributes['param']);
            if ($text->is_empty()) {
                $text = do_lang_tempcode('EXAMPLE');
            }
            $temp_tpl = do_template('COMCODE_EXP_REF', array('_GUID' => '89e7f528e72096e3458d6acb70734d0b', 'TEXT' => $text, 'URL' => $url));
            break;
        case 'exp_thumb':
            if ($wml) {
                break;
            }
            $_embed = $embed->evaluate();
            if (strpos($_embed, '.') !== false) {
                break;
            }
            $stub = get_file_base() . '/data/images/' . get_zone_name() . '/';
            $stub2 = get_base_url() . '/data/images/' . get_zone_name() . '/';
            if (substr($_embed, 0, 1) == '/') {
                $_embed = substr($_embed, 1);
            }
            if (file_exists($stub . $_embed . '.png')) {
                $url_full = $stub2 . $_embed . '.png';
            } elseif (file_exists($stub . $_embed . '.gif')) {
                $url_full = $stub2 . $_embed . '.gif';
            } elseif (file_exists($stub . $_embed . '.jpg')) {
                $url_full = $stub2 . $_embed . '.jpg';
            } elseif (file_exists($stub . $_embed . '.jpeg')) {
                $url_full = $stub2 . $_embed . '.jpeg';
            } else {
                $stub = get_file_base() . '/data/images/docs/';
                $stub2 = get_base_url() . '/data/images/docs/';
                if (substr($_embed, 0, 1) == '/') {
                    $_embed = substr($_embed, 1);
                }
                if (file_exists($stub . $_embed . '.png')) {
                    $url_full = $stub2 . $_embed . '.png';
                } elseif (file_exists($stub . $_embed . '.gif')) {
                    $url_full = $stub2 . $_embed . '.gif';
                } elseif (file_exists($stub . $_embed . '.jpg')) {
                    $url_full = $stub2 . $_embed . '.jpg';
                } elseif (file_exists($stub . $_embed . '.jpeg')) {
                    $url_full = $stub2 . $_embed . '.jpeg';
                } else {
                    $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('MISSING_RESOURCE_COMCODE', 'exp_thumb', escape_html($_embed))));
                    if (array_key_exists('COMCODE_BROKEN_URLS', $GLOBALS)) {
                        $GLOBALS['COMCODE_BROKEN_URLS'][] = $_embed;
                    } elseif (!in_array(get_page_name(), $GLOBALS['DONT_CARE_MISSING_PAGES']) && !running_script('iframe')) {
                        require_code('failure');
                        relay_error_notification(do_lang('MISSING_RESOURCE_COMCODE', 'exp_thumb', $_embed), false, $GLOBALS['FORUM_DRIVER']->is_staff($source_member) ? 'error_occurred_missing_reference_important' : 'error_occurred_missing_reference');
                    }
                    break;
                }
            }
            $float = array_key_exists('float', $attributes) ? $attributes['float'] : 'right';
            $text = $attributes['param'];
            if (get_option('is_on_gd') == '0' || !function_exists('imagetypes')) {
                $url_thumb = $url_full;
            } else {
                $new_name = $_embed . '_thumb.png';
                $file_thumb = $stub . $new_name;
                if (file_exists($file_thumb)) {
                    $url_thumb = $stub2 . rawurlencode($new_name);
                } else {
                    $new_name = $_embed . '.png';
                    $file_thumb = get_custom_file_base() . '/uploads/auto_thumbs/' . $new_name;
                    if (!file_exists($file_thumb)) {
                        require_code('images');
                        convert_image($url_full, $file_thumb, -1, -1, 150, false);
                    }
                    $url_thumb = get_custom_base_url() . '/uploads/auto_thumbs/' . rawurlencode($new_name);
                }
            }
            if (get_param_integer('wide_print', 0) == 1) {
                $temp_tpl = do_template('COMCODE_EXP_THUMB_PRINT', array('_GUID' => 'de7f8a7fa29c2335f381a0beb3da9406', 'FLOAT' => $float, 'TEXT' => $text, 'URL_THUMB' => $url_thumb, 'URL_FULL' => $url_full));
            } else {
                $temp_tpl = do_template('COMCODE_EXP_THUMB', array('_GUID' => 'ce7f8a7fa29c2335f381a0beb3da9406', 'FLOAT' => $float, 'TEXT' => $text, 'URL_THUMB' => $url_thumb, 'URL_FULL' => $url_full));
            }
            break;
        case 'thumb':
            if ($wml) {
                break;
            }
            $_embed = $embed->evaluate();
            $_embed = remove_url_mistakes($_embed);
            $_embed = check_naughty_javascript_url($source_member, $_embed, $as_admin);
            if (substr($_embed, 0, 1) == '/') {
                $_embed = substr($_embed, 1);
            }
            if (url_is_local($_embed)) {
                if (file_exists(get_file_base() . '/' . $_embed) && !file_exists(get_custom_file_base() . '/' . $_embed)) {
                    $url_full = get_base_url() . '/' . $_embed;
                } else {
                    $url_full = get_custom_base_url() . '/' . $_embed;
                }
            } else {
                $url_full = $_embed;
            }
            $align = array_key_exists('align', $attributes) ? $attributes['align'] : 'bottom';
            if (get_option('is_on_gd') == '0' || !function_exists('imagetypes') || !has_specific_permission($source_member, 'draw_to_server') && !$as_admin) {
                $url_thumb = $url_full;
            } else {
                if ($attributes['param'] != '') {
                    $url_thumb = url_is_local($attributes['param']) ? get_custom_base_url() . '/' . $attributes['param'] : $attributes['param'];
                }
                if ($attributes['param'] == '' || url_is_local($attributes['param']) && !file_exists(get_custom_file_base() . '/' . rawurldecode($attributes['param']))) {
                    $new_name = url_to_filename($url_full);
                    require_code('images');
                    if (!is_saveable_image($new_name)) {
                        $new_name .= '.png';
                    }
                    if (is_null($new_name)) {
                        $temp_tpl = do_template('WARNING_TABLE', array('WARNING' => do_lang_tempcode('URL_THUMB_TOO_LONG')));
                        break;
                    }
                    $file_thumb = get_custom_file_base() . '/uploads/auto_thumbs/' . $new_name;
                    if (!file_exists($file_thumb) && strpos($file_thumb, '{$') === false) {
                        convert_image($url_full, $file_thumb, -1, -1, intval(get_option('thumb_width')), false);
                    }
                    $url_thumb = get_custom_base_url() . '/uploads/auto_thumbs/' . rawurlencode($new_name);
                }
            }
            $caption = array_key_exists('caption', $attributes) ? $attributes['caption'] : '';
            $temp_tpl = do_template('COMCODE_THUMB', array('_GUID' => '1b0d25f72ef5f816091269e29c586d60', 'CAPTION' => $caption, 'RAND' => strval(mt_rand(0, 32000)), 'ALIGN' => $align, 'PASS_ID' => intval($pass_id) < 0 ? strval(mt_rand(0, 10000)) : $pass_id, 'URL_THUMB' => $url_thumb, 'URL_FULL' => $url_full));
            if (array_key_exists('float', $attributes)) {
                $temp_tpl = do_template('FLOATER', array('_GUID' => 'cbc56770714a44f56676f43da282cc7a', 'FLOAT' => $attributes['float'], 'CONTENT' => $temp_tpl));
            }
            break;
        case 'img':
            if ($wml) {
                break;
            }
            if ($semiparse_mode && array_key_exists('rollover', $attributes)) {
                $temp_tpl = make_string_tempcode('[img' . reinsert_parameters($attributes) . ']' . $embed->evaluate() . '[/img]');
                break;
            }
            $_embed = $embed->evaluate();
            $given_url = $_embed;
            $_embed = remove_url_mistakes($_embed);
            if (substr($_embed, 0, 1) == '/') {
                $_embed = substr($_embed, 1);
            }
            $_embed = check_naughty_javascript_url($source_member, $_embed, $as_admin);
            if (url_is_local($_embed)) {
                if (file_exists(get_file_base() . '/' . $_embed) && !file_exists(get_custom_file_base() . '/' . $_embed)) {
                    $url_full = get_base_url() . '/' . $_embed;
                } else {
                    $url_full = get_custom_base_url() . '/' . $_embed;
                }
            } else {
                $url_full = $_embed;
            }
            $temp_tpl = test_url($url_full, 'img', @html_entity_decode($given_url, ENT_QUOTES, get_charset()), $source_member);
            $align = array_key_exists('align', $attributes) ? $attributes['align'] : '';
            $caption = is_object($attributes['param']) ? $attributes['param'] : comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
            if (array_key_exists('title', $attributes)) {
                $tooltip = is_object($attributes['title']) ? $attributes['title'] : comcode_to_tempcode($attributes['title'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
            } else {
                $tooltip = $caption;
            }
            $rollover = array_key_exists('rollover', $attributes) ? $attributes['rollover'] : NULL;
            if (!is_null($rollover) && url_is_local($rollover)) {
                if (file_exists(get_file_base() . '/' . $rollover) && !file_exists(get_custom_file_base() . '/' . $rollover)) {
                    $rollover = get_base_url() . '/' . $rollover;
                } else {
                    $rollover = get_custom_base_url() . '/' . $rollover;
                }
            }
            $refresh_time = array_key_exists('refresh_time', $attributes) ? strval(intval($attributes['refresh_time'])) : '0';
            $temp_tpl->attach(do_template('COMCODE_IMG', array('_GUID' => '70166d8dbb0aff064b99c0dd30ed77a8', 'RAND' => uniqid('', true), 'REFRESH_TIME' => $refresh_time, 'ROLLOVER' => $rollover, 'ALIGN' => $align, 'URL' => $url_full, 'TOOLTIP' => $tooltip, 'CAPTION' => $caption)));
            if (array_key_exists('float', $attributes)) {
                $temp_tpl = do_template('FLOATER', array('_GUID' => '918162250c80e10212efd9a051545b9b', 'FLOAT' => $attributes['float'], 'CONTENT' => $temp_tpl));
            }
            break;
        case 'flash':
            if ($wml) {
                break;
            }
            $_embed = $embed->evaluate();
            $given_url = $_embed;
            $_embed = remove_url_mistakes($_embed);
            if (substr($_embed, 0, 1) == '/') {
                $_embed = substr($_embed, 1);
            }
            $_embed = check_naughty_javascript_url($source_member, $_embed, $as_admin);
            $url_full = url_is_local($_embed) ? get_custom_base_url() . '/' . $_embed : $_embed;
            $temp_tpl = test_url($url_full, 'flash', @html_entity_decode($given_url, ENT_QUOTES, get_charset()), $source_member);
            if ($attributes['param'] == '' || strpos($attributes['param'], 'x') === false) {
                if (!array_key_exists('width', $attributes)) {
                    $attributes['width'] = '300';
                }
                if (!array_key_exists('height', $attributes)) {
                    $attributes['height'] = '300';
                }
                $attributes['param'] = $attributes['width'] . 'x' . $attributes['height'];
            }
            list($width, $height) = explode('x', $attributes['param'], 2);
            if (addon_installed('jwplayer') && (substr($url_full, -4) == '.flv' || substr($url_full, -4) == '.mp4' || substr($url_full, -4) == '.mp3' || substr($url_full, -4) == '.webm')) {
                $temp_tpl->attach(do_template('COMCODE_FLV', array('_GUID' => '4746684d9e098709cc6671e1b00ce47e', 'URL' => $url_full, 'WIDTH' => $width, 'HEIGHT' => $height)));
            } else {
                $temp_tpl->attach(do_template('COMCODE_SWF', array('_GUID' => '8bc61ad75977a5a85eff96454af31fe8', 'URL' => $url_full, 'WIDTH' => $width, 'HEIGHT' => $height)));
            }
            break;
        case 'url':
            // Make them both HTML strings
            $url = $embed->evaluate();
            if (is_object($attributes['param'])) {
                $switch_over = true;
                // We know if must be Comcode XML
                $attributes['param'] = $attributes['param']->evaluate();
            } else {
                $switch_over = !looks_like_url($url) && looks_like_url($attributes['param'], true);
                if (strpos($attributes['param'], '[') !== false || strpos($attributes['param'], '{') !== false) {
                    $param_temp = comcode_to_tempcode(escape_html($attributes['param']), $source_member, $as_admin, 60, NULL, $connection, false, false, true, false, false, $highlight_bits, $on_behalf_of_member);
                    global $ADVERTISING_BANNERS;
                    $temp_ab = $ADVERTISING_BANNERS;
                    $ADVERTISING_BANNERS = array();
                    $caption = $param_temp;
                    $ADVERTISING_BANNERS = $temp_ab;
                } else {
                    $caption = make_string_tempcode(escape_html($attributes['param']));
                    // Consistency of escaping
                }
            }
            // Do we need to switch around?
            if ($switch_over) {
                $url = $attributes['param'];
                $caption = $embed;
            }
            // If we weren't given a caption, use the URL, but crop if necessary
            if ($caption->evaluate() == '') {
                $_caption = $url;
                // Shorten the URL if it is too long
                $max_link_length = 50;
                if (strlen($_caption) > $max_link_length) {
                    $_caption = escape_html(substr(@html_entity_decode($_caption, ENT_QUOTES, get_charset()), 0, intval($max_link_length / 2 - 3))) . '&hellip;' . escape_html(substr(@html_entity_decode($_caption, ENT_QUOTES, get_charset()), intval(-$max_link_length / 2)));
                }
                $caption = make_string_tempcode($_caption);
            }
            // Tidy up the URL now
            $url = @html_entity_decode($url, ENT_QUOTES, get_charset());
            $url = fixup_protocolless_urls($url);
            // Integrity and security
            $url = check_naughty_javascript_url($source_member, $url, $as_admin);
            // More URL tidying
            $local = url_is_local($url) || strpos($url, get_domain()) !== false;
            $given_url = $url;
            if ($url != '' && $url[0] != '#') {
                if (substr($url, 0, 1) == '/') {
                    $url = substr($url, 1);
                }
                $url_full = url_is_local($url) ? get_base_url() . '/' . $url : $url;
                if ($GLOBALS['XSS_DETECT']) {
                    ocp_mark_as_escaped($url_full);
                }
            } else {
                $url_full = $url;
            }
            $striped_base_url = str_replace('www.', '', str_replace('http://', '', get_base_url()));
            if ($striped_base_url != '' && substr($url, 0, 1) != '%' && strpos($url_full, $striped_base_url) === false) {
                $temp_tpl = test_url($url_full, 'url', $given_url, $source_member);
            }
            // Render
            if (!array_key_exists('target', $attributes)) {
                $attributes['target'] = $local ? '_top' : '_blank';
            }
            if ($attributes['target'] == 'blank') {
                $attributes['target'] = '_blank';
            }
            $rel = $as_admin || has_specific_permission($source_member, 'search_engine_links') ? '' : 'nofollow';
            if ($attributes['target'] == '_blank') {
                $title = (is_object($caption) ? static_evaluate_tempcode($caption) : $caption) . ' ' . do_lang('LINK_NEW_WINDOW');
            } else {
                $title = '';
            }
            $temp_tpl->attach(do_template('COMCODE_URL', array('_GUID' => 'd1657530e6d3d57e6a4791fb3bfa0dd7', 'TITLE' => $title, 'REL' => $rel, 'TARGET' => $attributes['target'], 'URL' => $url_full, 'CAPTION' => $caption)));
            break;
        case 'email':
            $_embed = $embed->evaluate();
            require_code('type_validation');
            require_code('obfuscate');
            // If we need to switch
            if (is_object($attributes['param']) || !is_valid_email_address($_embed) && is_valid_email_address($attributes['param'])) {
                $temp = $embed;
                // Is tempcode
                $_embed = $attributes['param'];
                $attributes['param'] = $temp;
            } else {
                $attributes['param'] = comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                // Becomes tempcode
            }
            if ($attributes['param']->is_empty()) {
                $attributes['param'] = obfuscate_email_address($_embed);
            }
            $subject = array_key_exists('subject', $attributes) ? $attributes['subject'] : '';
            $body = array_key_exists('body', $attributes) ? $attributes['body'] : '';
            $title = '';
            if (array_key_exists('title', $attributes)) {
                $title = $attributes['title'];
            }
            $temp_tpl = do_template('COMCODE_EMAIL', array('_GUID' => '5f6ade8fe07701b6858575153d78f4e9', 'TITLE' => $title, 'ADDRESS' => obfuscate_email_address($_embed), 'SUBJECT' => $subject, 'BODY' => $body, 'CAPTION' => $attributes['param']));
            break;
        case 'reference':
            if ($wml) {
                break;
            }
            if (array_key_exists('type', $attributes) && $attributes['type'] == 'url') {
                $_embed = $embed->evaluate();
                $_embed = check_naughty_javascript_url($source_member, $_embed, $as_admin);
                if (!array_key_exists('title', $attributes)) {
                    $attributes['title'] = $attributes['param'];
                }
                if (is_object($attributes['title']) || $attributes['title'] != '') {
                    $_title = is_object($attributes['title']) ? make_string_tempcode(escape_html($attributes['title'])) : comcode_to_tempcode($attributes['title'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                    $title = $_title->evaluate();
                } else {
                    $title = $_embed;
                }
                $embed = hyperlink($_embed, $title, true);
            }
            $temp_tpl = do_template('COMCODE_REFERENCE', array_merge($attributes, array('SOURCE' => $embed)));
            break;
        case 'upload':
            // This points to a file path, not a URL
            $_embed = $embed->evaluate();
            $type = array_key_exists('type', $attributes) ? $attributes['type'] : 'downloads';
            if (is_object($attributes['param']) || $attributes['param'] != '') {
                $_caption = is_object($attributes['param']) ? make_string_tempcode(escape_html($attributes['param'])) : comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
                $__caption = $_caption->evaluate();
            } else {
                $__caption = $_embed;
            }
            $url = get_custom_base_url() . '/' . $type . '/' . rawurlencode($_embed);
            $url = check_naughty_javascript_url($source_member, $url, $as_admin);
            $temp_tpl = test_url($url, 'upload', $_embed, $source_member);
            $temp_tpl->attach(hyperlink($url, $__caption));
            break;
        case 'page':
            $ignore_if_hidden = array_key_exists('ignore_if_hidden', $attributes) && $attributes['ignore_if_hidden'] == '1';
            unset($attributes['ignore_if_hidden']);
            // Two sets of parameters: simple style and complex style; both are completely incompatible
            $hash = '';
            if ($attributes == array('param' => '')) {
                $zone = '_SEARCH';
                $caption = $embed;
                $attributes = array('page' => $caption->evaluate());
            } elseif (array_keys($attributes) == array('param')) {
                $caption = $embed;
                if ($wml) {
                    $temp_tpl = $embed;
                    break;
                } else {
                    if (strpos($attributes['param'], ':') !== false) {
                        global $OVERRIDE_SELF_ZONE;
                        $page_link = $attributes['param'];
                        list($zone, $attributes, $hash) = page_link_decode($page_link);
                        if (!array_key_exists('page', $attributes)) {
                            $attributes['page'] = '';
                        }
                        if ($zone == '_SELF' && !is_null($OVERRIDE_SELF_ZONE)) {
                            $zone = $OVERRIDE_SELF_ZONE;
                        }
                    } else {
                        $zone = '_SEARCH';
                        // Changed in v3 from '_SELF', to allow context-sensitivity
                        $attributes = array_merge(array('page' => $attributes['param']), $attributes);
                    }
                }
            } else {
                $caption = array_key_exists('caption', $attributes) ? comcode_to_tempcode($attributes['caption'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member) : $embed;
                if ($wml) {
                    $temp_tpl = $caption;
                    break;
                } else {
                    $zone = $param_given ? $attributes['param'] : '_SEARCH';
                    // Changed in v3 from '_SELF', to allow context-sensitivity
                    unset($attributes['caption']);
                    if (!array_key_exists('page', $attributes)) {
                        $attributes = array_merge(array('page' => $embed->evaluate()), $attributes);
                    }
                }
            }
            unset($attributes['param']);
            foreach ($attributes as $key => $val) {
                if (is_object($val)) {
                    $attributes[$key] = $val->evaluate();
                }
            }
            if ($zone == '_SEARCH') {
                $zone = get_page_zone($attributes['page'], false);
                if (is_null($zone)) {
                    $zone = '';
                }
            }
            $pl_url = build_url($attributes, $zone, NULL, false, false, false, $hash);
            $temp_tpl = hyperlink($pl_url, $caption);
            $page = $attributes['page'];
            if ($page != '') {
                if ($zone == '_SELF') {
                    $zone = get_zone_name();
                }
                if ($zone == '_SEARCH') {
                    $zone = get_page_zone($page, false);
                    if (is_null($zone)) {
                        $zone = '';
                    }
                    // Oh dear, well it will be correctly identified as not found anyway
                }
                $ptest = _request_page($page, $zone);
                if ($ptest !== false) {
                    if ($page == 'topicview' && array_key_exists('id', $attributes)) {
                        if (!is_numeric($attributes['id'])) {
                            $attributes['id'] = $GLOBALS['SITE_DB']->query_value_null_ok('url_id_monikers', 'm_resource_id', array('m_resource_page' => $page, 'm_moniker' => $attributes['id']));
                        }
                        if (!is_null($attributes['id'])) {
                            $test = $GLOBALS['FORUM_DB']->query_value_null_ok('f_topics', 'id', array('id' => $attributes['id']));
                            if (is_null($test)) {
                                $ptest = false;
                            }
                        } else {
                            $ptest = false;
                        }
                    }
                }
                if ($ptest === false) {
                    //$temp_tpl->attach(' ['.do_lang('MISSING_RESOURCE').']');  // Don't want this as we might be making the page immediately
                    if (!in_array(get_page_name(), $GLOBALS['DONT_CARE_MISSING_PAGES']) && !in_array($page, $GLOBALS['DONT_CARE_MISSING_PAGES']) && !running_script('iframe')) {
                        if ($ignore_if_hidden) {
                            $temp_tpl = do_template('COMCODE_DEL', array('CONTENT' => $caption));
                        } else {
                            require_code('failure');
                            relay_error_notification(do_lang('MISSING_RESOURCE_COMCODE', 'page_link', $page_link), false, $GLOBALS['FORUM_DRIVER']->is_staff($source_member) ? 'error_occurred_missing_reference_important' : 'error_occurred_missing_reference');
                        }
                    }
                }
            }
            break;
        case 'hide':
            if ($wml) {
                $temp_tpl = $embed;
                break;
            }
            if (array_key_exists('param', $attributes)) {
                $text = is_object($attributes['param']) ? $attributes['param'] : comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member);
            } else {
                $text = do_lang_tempcode('EXPAND');
            }
            $temp_tpl = do_template('COMCODE_HIDE', array('_GUID' => 'a591a0d1e6bb3dde0f22cebb9c7ab93e', 'TEXT' => $text, 'CONTENT' => $embed));
            break;
        case 'quote':
            if ($wml) {
                $temp_tpl->attach('<br /><br />' . $attributes['param'] . ':');
                $temp_tpl->attach($embed);
                break;
            }
            $cite = array_key_exists('cite', $attributes) ? $attributes['cite'] : NULL;
            if (!is_null($cite)) {
                $temp_tpl = test_url($cite, 'quote', $cite, $source_member);
            }
            if ($attributes['param'] == '' && isset($attributes['author'])) {
                $attributes['param'] = $attributes['author'];
            }
            // Compatibility with SMF
            if ($attributes['param'] != '') {
                if (is_numeric($attributes['param'])) {
                    $attributes['param'] = $GLOBALS['FORUM_DRIVER']->get_username($attributes['param']);
                    if (is_null($attributes['param'])) {
                        $attributes['param'] = do_lang('UNKNOWN');
                    }
                } else {
                    $attributes['param'] = protect_from_escaping(comcode_to_tempcode($attributes['param'], $source_member, $as_admin, 60, NULL, $connection, false, false, false, false, false, $highlight_bits, $on_behalf_of_member));
                }
                $temp_tpl->attach(do_template('COMCODE_QUOTE_BY', array('_GUID' => '18f55a548892ad08b0b50b3b586b5b95', 'CITE' => $cite, 'CONTENT' => $embed, 'BY' => $attributes['param'], 'SAIDLESS' => array_key_exists('saidless', $attributes) ? $attributes['saidless'] : '0')));
            } else {
                $temp_tpl->attach(do_template('COMCODE_QUOTE', array('_GUID' => 'fa275de59433c17da19b22814c17fdc5', 'CITE' => $cite, 'CONTENT' => $embed)));
            }
            break;
        case 'html':
            if ($wml) {
                break;
            }
            $temp_tpl = $embed;
            // Plain HTML. But it's been filtered already
            break;
        case 'semihtml':
            $temp_tpl = $embed;
            // Hybrid HTML. But it's been filtered already
            break;
        case 'block':
            if ($wml) {
                break;
            }
            $attributes['block'] = trim($embed->evaluate());
            if (preg_match('#^[\\w\\-]*$#', $attributes['block']) == 0) {
                $temp_tpl = paragraph(do_lang_tempcode('MISSING_BLOCK_FILE', escape_html($attributes['block'])), '90dfdlksds8d7dyddssddxs', 'error_marker');
                break;
                // Avoids a suspected hack attempt by just filtering early
            }
            $_attributes = array();
            foreach ($attributes as $key => $val) {
                $_attributes[] = $key . '=' . $val;
            }
            $temp_tpl = symbol_tempcode('BLOCK', $_attributes);
            break;
        case 'contents':
            if ($wml) {
                break;
            }
            // Do structure sweep
            $urls_for = array();
            $old_structure_list = $STRUCTURE_LIST;
            $STRUCTURE_LIST = array();
            // reset for e.g. comcode_text_to_tempcode calls (which don't itself reset it, although _comcode_to_tempcode does for top level parses)
            if (array_key_exists('files', $attributes) && $comcode_dangerous) {
                $s_zone = array_key_exists('zone', $attributes) ? $attributes['zone'] : get_zone_name();
                $pages = find_all_pages($s_zone, 'comcode_custom/' . get_site_default_lang(), 'txt') + find_all_pages($s_zone, 'comcode/' . get_site_default_lang(), 'txt');
                $prefix = $attributes['files'];
                foreach ($pages as $pg_name => $pg_type) {
                    if (substr($pg_name, 0, strlen($prefix)) == $prefix) {
                        $i = count($STRUCTURE_LIST);
                        comcode_to_tempcode(file_get_contents(zone_black_magic_filterer(get_file_base() . '/' . $s_zone . '/pages/' . $pg_type . '/' . $pg_name . '.txt'), FILE_TEXT), $source_member, $as_admin, 60, NULL, $connection, false, false, false, true, false, NULL, $on_behalf_of_member);
                        $page_url = build_url(array('page' => $pg_name), $s_zone);
                        while (array_key_exists($i, $STRUCTURE_LIST)) {
                            $urls_for[] = $page_url;
                            $i++;
                        }
                    }
                }
                $base = array_key_exists('base', $attributes) ? intval($attributes['base']) : 1;
            } else {
                if (substr($comcode, 0, 8) == '<comcode') {
                    require_code('comcode_xml');
                    if (!$as_admin) {
                        check_specific_permission('comcode_dangerous', NULL, $source_member);
                    }
                    $_ = new comcode_xml_to_tempcode($comcode, $source_member, 60, NULL, $connection, false, false, false, true, false, $on_behalf_of_member);
                } else {
                    require_code('comcode_text');
                    comcode_text_to_tempcode($comcode, $source_member, $as_admin, 60, NULL, $connection, false, false, false, true, false, NULL, $on_behalf_of_member);
                }
                $base = array_key_exists('base', $attributes) ? intval($attributes['base']) : 1;
            }
            $list_types = $embed->evaluate() == '' ? array() : explode(',', $embed->evaluate());
            $list_types += array('decimal', 'lower-alpha', 'lower-roman', 'upper-alpha', 'upper-roman', 'disc');
            $levels_allowed = array_key_exists('levels', $attributes) ? intval($attributes['levels']) : NULL;
            // Convert the list structure into a tree structure
            $past_level_stack = array(1);
            $subtree_stack = array(array());
            $levels = 1;
            foreach ($STRUCTURE_LIST as $i => $struct) {
                $level = $struct[0];
                $title = $struct[1];
                $uniq_id = $struct[2];
                $url = array_key_exists($i, $urls_for) ? $urls_for[$i] : '';
                if ($level > $levels_allowed && !is_null($levels_allowed)) {
                    continue;
                }
                // Going down the tree
                if ($level > $past_level_stack[$levels - 1]) {
                    array_push($past_level_stack, $level);
                    array_push($subtree_stack, array(array($uniq_id, $title->evaluate(), $url)));
                    $levels++;
                } else {
                    // Going back up the tree, destroying levels that must have now closed off
                    while ($level < $past_level_stack[$levels - 1] && $levels > 2) {
                        array_pop($past_level_stack);
                        $subtree = array_pop($subtree_stack);
                        $levels--;
                        // Alter the last of the next level on stack so it is actually taking the closed off level as children, and changing from a property list to a pair: property list & children
                        $subtree_stack[$levels - 1][count($subtree_stack[$levels - 1]) - 1] = array($subtree_stack[$levels - 1][count($subtree_stack[$levels - 1]) - 1], $subtree);
                    }
                    // Store the title where we are
                    $subtree_stack[$levels - 1][] = array($uniq_id, $title->evaluate(), $url);
                }
            }
            // Clean up... going up until we're with 1
            while ($levels > 1) {
                array_pop($past_level_stack);
                $subtree = array_pop($subtree_stack);
                $levels--;
                $parent_level_start_index = count($subtree_stack[$levels - 1]) - 1;
                if ($parent_level_start_index < 0) {
                    $subtree_stack[$levels - 1] = $subtree;
                } else {
                    $subtree_stack[$levels - 1][$parent_level_start_index] = array($subtree_stack[$levels - 1][$parent_level_start_index], $subtree);
                }
            }
            // Now we have the structure to display
            $levels_t = _do_contents_level($subtree_stack[0], $list_types, $base);
            $temp_tpl = do_template('COMCODE_CONTENTS', array('_GUID' => 'ca2f5320fa930e2257a2e74e4f98e5a0', 'LEVELS' => $levels_t));
            $STRUCTURE_LIST = $old_structure_list;
            // Restore, so subsequent 'title' tags have correct numbering
            break;
    }
    // Last ditch effort: custom tags
    if ($temp_tpl->is_definitely_empty() && !$wml) {
        global $REPLACE_TARGETS;
        if (array_key_exists($tag, $REPLACE_TARGETS)) {
            $replace = $REPLACE_TARGETS[$tag]['replace'];
            $parameters = explode(',', $REPLACE_TARGETS[$tag]['parameters']);
            $binding = array('CONTENT' => $embed, 'RAND' => uniqid('', true));
            foreach ($parameters as $parameter) {
                $parameter = trim($parameter);
                $parts = explode('=', $parameter);
                if (count($parts) == 1) {
                    $parts[] = '';
                }
                if (count($parts) != 2) {
                    continue;
                }
                list($parameter, $default) = $parts;
                if (!array_key_exists($parameter, $attributes) || $attributes[$parameter] == '') {
                    $attributes[$parameter] = $default;
                }
                $binding[strtoupper($parameter)] = $attributes[$parameter];
                $replace = str_replace('{' . $parameter . '}', '{' . strtoupper($parameter) . '*}', $replace);
            }
            $replace = str_replace('{content}', array_key_exists($tag, $GLOBALS['TEXTUAL_TAGS']) ? '{CONTENT}' : '{CONTENT*}', $replace);
            require_code('tempcode_compiler');
            $temp_tpl = template_to_tempcode($replace);
            $temp_tpl = $temp_tpl->bind($binding, '(custom comcode: ' . $tag . ')');
        }
    }
    return $temp_tpl;
}
Example #14
0
/**
 * Actually send out the newsletter in the background.
 */
function newsletter_shutdown_function()
{
    global $NEWSLETTER_SUBJECT, $NEWSLETTER_MESSAGE, $NEWSLETTER_HTML_ONLY, $NEWSLETTER_FROM_EMAIL, $NEWSLETTER_FROM_NAME, $NEWSLETTER_PRIORITY, $NEWSLETTER_SEND_DETAILS, $NEWSLETTER_LANGUAGE, $CSV_DATA, $NEWSLETTER_MAIL_TEMPLATE;
    //mail_wrap($NEWSLETTER_SUBJECT,$NEWSLETTER_MESSAGE,$NEWSLETTER_ADDRESSES,$NEWSLETTER_USERNAMES,$NEWSLETTER_FROM_EMAIL,$NEWSLETTER_FROM_NAME,3,NULL,true,NULL,true,$NEWSLETTER_HTML_ONLY==1);  Not so easy any more as message needs tailoring per subscriber
    disable_php_memory_limit();
    // As PHP can leak memory, or caches can fill, even if we do this carefully
    $last_cron = get_value('last_cron');
    $start = 0;
    do {
        list($addresses, $hashes, $usernames, $forenames, $surnames, $ids, ) = newsletter_who_send_to($NEWSLETTER_SEND_DETAILS, $NEWSLETTER_LANGUAGE, $start, 100, false, $CSV_DATA);
        // Send to all
        foreach ($addresses as $i => $email_address) {
            // Variable substitution in body
            $newsletter_message_substituted = newsletter_variable_substitution($NEWSLETTER_MESSAGE, $NEWSLETTER_SUBJECT, $forenames[$i], $surnames[$i], $usernames[$i], $email_address, $ids[$i], $hashes[$i]);
            $in_html = false;
            if (strpos($newsletter_message_substituted, '<html') === false) {
                if ($NEWSLETTER_HTML_ONLY == 1) {
                    $_m = comcode_to_tempcode($newsletter_message_substituted, get_member(), true);
                    $newsletter_message_substituted = $_m->evaluate($NEWSLETTER_LANGUAGE);
                    $in_html = true;
                }
            } else {
                require_code('tempcode_compiler');
                $_m = template_to_tempcode($newsletter_message_substituted);
                $newsletter_message_substituted = $_m->evaluate($NEWSLETTER_LANGUAGE);
                $in_html = true;
            }
            if (!is_null($last_cron)) {
                $GLOBALS['SITE_DB']->query_insert('newsletter_drip_send', array('d_inject_time' => time(), 'd_subject' => $NEWSLETTER_SUBJECT, 'd_message' => $newsletter_message_substituted, 'd_html_only' => $NEWSLETTER_HTML_ONLY, 'd_to_email' => $email_address, 'd_to_name' => $usernames[$i], 'd_from_email' => $NEWSLETTER_FROM_EMAIL, 'd_from_name' => $NEWSLETTER_FROM_NAME, 'd_priority' => $NEWSLETTER_PRIORITY, 'd_template' => $NEWSLETTER_MAIL_TEMPLATE));
            } else {
                mail_wrap($NEWSLETTER_SUBJECT, $newsletter_message_substituted, array($email_address), array($usernames[$i]), $NEWSLETTER_FROM_EMAIL, $NEWSLETTER_FROM_NAME, $NEWSLETTER_PRIORITY, NULL, true, NULL, true, $in_html, false, $NEWSLETTER_MAIL_TEMPLATE);
            }
        }
        $start += 100;
    } while (array_key_exists(0, $addresses));
}
Example #15
0
 /**
  * Standard modular run function.
  *
  * @param  array		A map of parameters.
  * @return tempcode	The result of execution.
  */
 function run($map)
 {
     require_lang('news');
     require_css('news');
     require_css('side_blocks');
     require_code('obfuscate');
     $url = array_key_exists('param', $map) ? $map['param'] : 'http://ocportal.com/backend.php?type=rss&mode=news&filter=16,17,18,19,20';
     // http://channel9.msdn.com/Feeds/RSS/
     if (strpos($url, '{') !== false) {
         require_code('tempcode_compiler');
         $url = static_evaluate_tempcode(template_to_tempcode($url));
     }
     $ticker = array_key_exists('ticker', $map) && $map['ticker'] == '1';
     require_code('rss');
     $rss = new rss($url);
     if (!is_null($rss->error)) {
         $GLOBALS['DO_NOT_CACHE_THIS'] = true;
         require_code('failure');
         if (strpos($url, 'twitter') === false) {
             // Twitter is always failing ;).
             relay_error_notification(do_lang('ERROR_HANDLING_RSS_FEED', $url, $rss->error), false, 'error_occurred_rss');
         }
         if (cron_installed()) {
             if (!$GLOBALS['FORUM_DRIVER']->is_staff(get_member())) {
                 return new ocp_tempcode();
             }
         }
         return do_template('INLINE_WIP_MESSAGE', array('MESSAGE' => htmlentities($rss->error)));
     }
     // Sorting
     $items = array();
     foreach ($rss->gleamed_items as $item) {
         if (!array_key_exists('clean_add_date', $item)) {
             $item['clean_add_date'] = time();
         }
         $items[] = $item;
     }
     global $M_SORT_KEY;
     $M_SORT_KEY = 'clean_add_date';
     usort($items, 'multi_sort');
     $items = array_reverse($items);
     global $NEWS_CATS;
     $NEWS_CATS = $GLOBALS['SITE_DB']->query_select('news_categories', array('*'), array('nc_owner' => NULL));
     $NEWS_CATS = list_to_map('id', $NEWS_CATS);
     if (!array_key_exists('title', $rss->gleamed_feed)) {
         $rss->gleamed_feed['title'] = do_lang_tempcode('RSS_STREAM');
     }
     if (array_key_exists('title', $map)) {
         $rss->gleamed_feed['title'] = $map['title'];
     }
     // Reduce what we collected about the feed to a minimum. This is very awkward, as we don't know what's here.
     if (array_key_exists('author', $rss->gleamed_feed)) {
         $__author = NULL;
         $_author_string = $rss->gleamed_feed['author'];
         if (array_key_exists('url', $rss->gleamed_feed)) {
             $__author = hyperlink($rss->gleamed_feed['url'], escape_html($_author_string), true);
         } elseif (array_key_exists('author_url', $rss->gleamed_feed)) {
             $__author = hyperlink($rss->gleamed_feed['author_url'], escape_html($_author_string), true);
         } elseif (array_key_exists('author_email', $rss->gleamed_feed)) {
             $__author = hyperlink(mailto_obfuscated() . obfuscate_email_address($rss->gleamed_feed['author_email']), escape_html($_author_string), true);
         }
         if (!is_null($__author)) {
             $_author_string = $__author->evaluate();
         }
         $_author = do_lang_tempcode('RSS_SOURCE_FROM', $_author_string);
     } else {
         $_author = new ocp_tempcode();
     }
     if (!array_key_exists('copyright', $rss->gleamed_feed)) {
         $rss->gleamed_feed['copyright'] = '';
     }
     if (array_key_exists('copyright', $map)) {
         $rss->gleamed_feed['copyright'] = $map['copyright'];
     }
     // Now for the actual stream contents
     $max = array_key_exists('max_entries', $map) ? intval($map['max_entries']) : 5;
     $content = new ocp_tempcode();
     foreach ($items as $i => $item) {
         if ($i >= $max) {
             break;
         }
         if (array_key_exists('full_url', $item)) {
             $full_url = $item['full_url'];
         } elseif (array_key_exists('guid', $item)) {
             $full_url = $item['guid'];
         } elseif (array_key_exists('comment_url', $item)) {
             $full_url = $item['comment_url'];
         } else {
             $full_url = '';
         }
         $_title = $item['title'];
         $_title = array_key_exists('title', $item) ? $item['title'] : '';
         $date = array_key_exists('clean_add_date', $item) ? get_timezoned_date($item['clean_add_date']) : (array_key_exists('add_date', $item) ? $item['add_date'] : '');
         $content->attach(do_template('BLOCK_SIDE_RSS_SUMMARY', array('_GUID' => '18f6d1ccfe980cc01bbdd2ee178c2410', 'TICKER' => $ticker, 'FEED_URL' => $url, 'FULL_URL' => $full_url, 'NEWS_TITLE' => $_title, 'DATE' => $date, 'DATE_RAW' => array_key_exists('clean_add_date', $item) ? strval($item['clean_add_date']) : '', 'SUMMARY' => array_key_exists('news', $item) ? $item['news'] : (array_key_exists('news_article', $item) ? $item['news_article'] : ''))));
     }
     return do_template('BLOCK_SIDE_RSS', array('_GUID' => 'fe3319e942d75fedb83e4cf80f80e19f', 'TICKER' => $ticker, 'FEED_URL' => $url, 'TITLE' => $rss->gleamed_feed['title'], 'CONTENT' => $content));
 }
Example #16
0
 /**
  * The UI to confirm sending of our newsletter.
  *
  * @return tempcode		The UI
  */
 function confirm_send()
 {
     $title = get_page_title('NEWSLETTER_SEND');
     $message = post_param('message');
     $subject = post_param('subject');
     $lang = choose_language($title);
     $template = post_param('template', 'MAIL');
     $in_full = post_param_integer('in_full', 0);
     $html_only = post_param_integer('html_only', 0);
     $from_email = post_param('from_email', '');
     $from_name = post_param('from_name', '');
     $extra_post_data = array();
     require_code('uploads');
     if (is_swf_upload(true) && array_key_exists('file', $_FILES) || array_key_exists('file', $_FILES) && is_uploaded_file($_FILES['file']['tmp_name'])) {
         $_csv_data = array();
         $myfile = fopen($_FILES['file']['tmp_name'], 'rt');
         $del = ',';
         $csv_test_line = fgetcsv($myfile, 4096, $del);
         if (count($csv_test_line) == 1 && strpos($csv_test_line[0], ';') !== false) {
             $del = ';';
         }
         rewind($myfile);
         while (($csv_line = fgetcsv($myfile, 4096, $del)) !== false) {
             $_csv_data[] = $csv_line;
         }
         fclose($myfile);
         $extra_post_data['csv_data'] = serialize($_csv_data);
     }
     if (post_param_integer('make_periodic', 0) == 1) {
         // We're making a periodic newsletter. Thus we need to pass this info
         // through to the next step
         $extra_post_data['make_periodic'] = '1';
         // Re-generate preview from latest chosen_categories
         $message = $this->generate_whats_new_comcode(post_param('chosen_categories', ''), $in_full, $lang, get_input_date('cutoff'));
     }
     $address = $GLOBALS['FORUM_DRIVER']->get_member_email_address(get_member());
     if ($address == '') {
         $address = get_option('staff_address');
     }
     $username = $GLOBALS['FORUM_DRIVER']->get_username(get_member());
     $message = newsletter_variable_substitution($message, $subject, '', '', do_lang('UNKNOWN'), $address, 'test', '');
     require_code('mail');
     require_code('tempcode_compiler');
     $in_html = false;
     if (strpos($message, '<html') !== false) {
         $_preview = template_to_tempcode($message);
         $in_html = true;
     } else {
         $comcode_version = comcode_to_tempcode($message, get_member(), true);
         $_preview = do_template('MAIL', array('TITLE' => $subject, 'CSS' => css_tempcode(true, true, $comcode_version->evaluate()), 'LANG' => get_site_default_lang(), 'LOGOURL' => get_logo_url(''), 'CONTENT' => $comcode_version), NULL, false, NULL, '.tpl', 'templates', $GLOBALS['FORUM_DRIVER']->get_theme(''));
         $in_html = $html_only == 1;
     }
     $text_preview = $html_only == 1 ? '' : comcode_to_clean_text(static_evaluate_tempcode(template_to_tempcode($message)));
     require_code('mail');
     $preview_subject = $subject;
     if (post_param_integer('make_periodic', 0) == 1) {
         $preview_subject .= ' - ' . get_timezoned_date(time(), false, false, false, true);
     }
     require_code('comcode_text');
     $preview = do_template('NEWSLETTER_CONFIRM_WRAP', array('_GUID' => '02bd5a782620141f8589e647e2c6d90b', 'TEXT_PREVIEW' => $text_preview, 'PREVIEW' => $_preview, 'SUBJECT' => $subject));
     mail_wrap($preview_subject, $html_only == 1 ? $_preview->evaluate() : $message, array($address), $username, $from_email, $from_name, 3, NULL, true, NULL, true, $in_html);
     breadcrumb_set_parents(array(array('_SELF:_SELF:misc', do_lang_tempcode('MANAGE_NEWSLETTER')), array('_SELF:_SELF:new', do_lang_tempcode('NEWSLETTER_SEND'))));
     breadcrumb_set_self(do_lang_tempcode('CONFIRM'));
     require_code('templates_confirm_screen');
     return form_confirm_screen($title, $preview, 'send', get_param('old_type', 'new'), $extra_post_data);
 }
Example #17
0
/**
 * Output a theme component straight to the browser.
 */
function themewizard_script()
{
    $type = get_param('type');
    $source_theme = get_param('keep_theme_source', 'default');
    $algorithm = get_param('keep_theme_algorithm', 'equations');
    $show = get_param('show');
    $seed = get_param('keep_theme_seed');
    if ($seed == 'kiddie') {
        $seed = str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    }
    $_dark = get_param_integer('keep_theme_dark', NULL);
    $dark = is_null($_dark) ? NULL : $_dark == 1;
    if ($type == 'preview') {
        $_tpl = do_template('THEMEWIZARD_2_PREVIEW');
        $tpl = do_template('STYLED_HTML_WRAP', array('TITLE' => do_lang_tempcode('PREVIEW'), 'CONTENT' => $_tpl));
        $tpl->evaluate_echo();
    }
    if ($type == 'css') {
        @ini_set('ocproducts.xss_detect', '0');
        list($colours, $landscape) = calculate_theme($seed, $source_theme, $algorithm, 'colours', $dark);
        $css = theme_wizard_colours_to_sheet($show, $landscape, $source_theme, $algorithm, $seed);
        header('Content-type: text/css');
        require_code('tempcode_compiler');
        $tpl = template_to_tempcode($css);
        $tpl->evaluate_echo();
    }
    if ($type == 'image') {
        $image = calculate_theme($seed, $source_theme, $algorithm, $show, $dark);
        if (is_null($image)) {
            header('Location: ' . find_theme_image($show));
            exit;
        }
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
    }
}
Example #18
0
/**
 * Handle GET URLs requesting embedded media files.
 */
function handle_self_referencing_embedment()
{
    // If this is self-referring to CSS or logo
    if (array_key_exists('type', $_GET)) {
        $type = $_GET['type'];
        if ($type == 'ajax_ftp_details') {
            header('Content-Type: text/plain');
            if (!function_exists('ftp_connect')) {
                echo do_lang('NO_PHP_FTP');
                exit;
            }
            $conn = false;
            $domain = trim(get_param('ftp_domain'));
            $port = 21;
            if (strpos($domain, ':') !== false) {
                list($domain, $_port) = explode(':', $domain, 2);
                $port = intval($_port);
            }
            if (function_exists('ftp_ssl_connect')) {
                $conn = @ftp_ssl_connect($domain, $port);
            }
            $ssl = $conn !== false;
            $username = get_param('ftp_username');
            $password = get_param('ftp_password');
            $ssl = $conn !== false;
            if ($ssl && !@ftp_login($conn, $username, $password)) {
                $conn = false;
                $ssl = false;
            }
            if ($conn === false) {
                $conn = ftp_connect($domain, $port);
            }
            if ($conn === false) {
                echo do_lang('NO_FTP_CONNECT');
                exit;
            }
            if (!$ssl && !@ftp_login($conn, $username, $password)) {
                echo do_lang('NO_FTP_LOGIN', @strval($php_errormsg));
                ftp_close($conn);
                exit;
            }
            $ftp_folder = get_param('ftp_folder');
            if (substr($ftp_folder, -1) != '/') {
                $ftp_folder .= '/';
            }
            if (!@ftp_chdir($conn, $ftp_folder)) {
                echo do_lang('NO_FTP_DIR', @strval($php_errormsg), '1');
                ftp_close($conn);
                exit;
            }
            $files = @ftp_nlist($conn, '.');
            if ($files === false) {
                $files = array();
                if (@ftp_rename($conn, 'install.php', 'install.php')) {
                    $files = array('install.php', 'data.ocp');
                }
            }
            if (!in_array('install.php', $files)) {
                echo do_lang('NO_FTP_DIR', @strval($php_errormsg), '2');
            }
            ftp_close($conn);
            exit;
        }
        if ($type == 'ajax_db_details') {
            header('Content-Type: text/plain');
            global $SITE_INFO;
            if (!isset($SITE_INFO)) {
                $SITE_INFO = array();
            }
            $SITE_INFO['db_type'] = get_param('db_type');
            require_code('database');
            if (get_param('db_site') == '') {
                $db = new database_driver(get_param('db_forums'), get_param('db_forums_host'), get_param('db_forums_user'), get_param('db_forums_password'), '', true);
            } else {
                $db = new database_driver(get_param('db_site'), get_param('db_site_host'), get_param('db_site_user'), get_param('db_site_password'), '', true);
            }
            $connection =& $db->connection_write;
            if (count($connection) > 4) {
                call_user_func_array(array($db->static_ob, 'db_get_connection'), $connection);
            }
            exit;
        }
        if ($type == 'logo') {
            header('Content-type: image/png');
            if (!file_exists(get_file_base() . '/themes/default/images/' . get_site_default_lang() . '/logo/trimmed-logo.png')) {
                $out = file_array_get('themes/default/images/' . get_site_default_lang() . '/logo/trimmed-logo.png');
                echo $out;
            } else {
                print file_get_contents(get_file_base() . '/themes/default/images/' . get_site_default_lang() . '/logo/trimmed-logo.png');
                exit;
            }
            exit;
        }
        if ($type == 'contract') {
            header('Content-type: image/png');
            if (!file_exists(get_file_base() . '/themes/default/images/contract.png')) {
                $out = file_array_get('themes/default/images/contract.png');
                echo $out;
            } else {
                print file_get_contents(get_file_base() . '/themes/default/images/contract.png');
                exit;
            }
            exit;
        }
        if ($type == 'expand') {
            header('Content-type: image/png');
            if (!file_exists(get_file_base() . '/themes/default/images/expand.png')) {
                $out = file_array_get('themes/default/images/expand.png');
                echo $out;
            } else {
                print file_get_contents(get_file_base() . '/themes/default/images/expand.png');
                exit;
            }
            exit;
        }
        if (substr($type, 0, 15) == 'themes/default/') {
            header('Content-type: image/png');
            if (!file_exists(get_file_base() . '/' . $type)) {
                $out = file_array_get(filter_naughty($type));
                echo $out;
            } else {
                print file_get_contents(get_file_base() . '/' . filter_naughty($type));
                exit;
            }
            exit;
        }
        if ($type == 'css') {
            header('Content-Type: text/css');
            if (!file_exists(get_file_base() . '/themes/default/css/global.css')) {
                $file = file_array_get('themes/default/css/global.css');
            } else {
                $file = file_get_contents(get_file_base() . '/themes/default/css/global.css', FILE_TEXT);
            }
            $file = preg_replace('#\\{\\$IMG;?\\,([^,\\}\']+)\\}#', 'install.php?type=themes/default/images/${1}.png', $file);
            require_code('tempcode_compiler');
            $css = template_to_tempcode($file, 0, false, '');
            $file = $css->evaluate();
            print $file;
            exit;
        }
        if ($type == 'css_2') {
            header('Content-Type: text/css');
            if (!file_exists(get_file_base() . '/themes/default/css/install.css')) {
                $file = file_array_get('themes/default/css/install.css');
                echo $file;
            } else {
                $file = file_get_contents(get_file_base() . '/themes/default/css/install.css', FILE_TEXT);
            }
            $file = preg_replace('#\\{\\$IMG\\,([^,\\}\']+)\\}#', 'themes/default/images/${1}.png', $file);
            require_code('tempcode_compiler');
            $css = template_to_tempcode($file, 0, false, '');
            $file = $css->evaluate();
            print $file;
            exit;
        }
        exit;
    }
}
Example #19
0
/**
 * Convert the specified comcode (text format) into a tempcode tree. You shouldn't output the tempcode tree to the browser, as it looks really horrible. If you are in a rare case where you need to output directly (not through templates), you should call the evaluate method on the tempcode object, to convert it into a string.
 *
 * @param  LONG_TEXT		The comcode to convert
 * @param  MEMBER			The member the evaluation is running as. This is a security issue, and you should only run as an administrator if you have considered where the comcode came from carefully
 * @param  boolean		Whether to explicitly execute this with admin rights. There are a few rare situations where this should be done, for data you know didn't come from a member, but is being evaluated by one.
 * @param  ?integer		The position to conduct wordwrapping at (NULL: do not conduct word-wrapping)
 * @param  ?string		A special identifier that can identify this resource in a sea of our resources of this class; usually this can be ignored, but may be used to provide a binding between Javascript in evaluated comcode, and the surrounding environment (NULL: no explicit binding)
 * @param  object			The database connection to use
 * @param  boolean		Whether to parse so as to create something that would fit inside a semihtml tag. It means we generate HTML, with Comcode written into it where the tag could never be reverse-converted (e.g. a block).
 * @param  boolean		Whether this is being pre-parsed, to pick up errors before row insertion.
 * @param  boolean		Whether to treat this whole thing as being wrapped in semihtml, but apply normal security otherwise.
 * @param  boolean		Whether we are only doing this parse to find the title structure
 * @param  boolean		Whether to only check the Comcode. It's best to use the check_comcode function which will in turn use this parameter.
 * @param  ?array			A list of words to highlight (NULL: none)
 * @param  ?MEMBER		The member we are running on behalf of, with respect to how attachments are handled; we may use this members attachments that are already within this post, and our new attachments will be handed to this member (NULL: member evaluating)
 * @return tempcode		The tempcode generated
 */
function comcode_text_to_tempcode($comcode, $source_member, $as_admin, $wrap_pos, $pass_id, $connection, $semiparse_mode, $preparse_mode, $is_all_semihtml, $structure_sweep, $check_only, $highlight_bits = NULL, $on_behalf_of_member = NULL)
{
    global $ADVERTISING_BANNERS, $ALLOWED_ENTITIES, $POTENTIALLY_EMPTY_TAGS, $CODE_TAGS, $REVERSABLE_TAGS, $PUREHTML_TAGS, $DANGEROUS_TAGS, $VALID_COMCODE_TAGS, $BLOCK_TAGS, $POTENTIAL_JS_NAUGHTY_ARRAY, $TEXTUAL_TAGS, $LEET_FILTER, $IMPORTED_CUSTOM_COMCODE, $REPLACE_TARGETS;
    $wml = false;
    // removed feature from ocPortal now
    $print_mode = get_param_integer('wide_print', 0) == 1;
    $len = strlen($comcode);
    if (function_exists('set_time_limit') && ini_get('max_execution_time') != '0') {
        @set_time_limit(300);
    }
    $allowed_html_seqs = array('<table>', '<table class="[^"]*">', '<table class="[^"]*" summary="[^"]*">', '<table summary="[^"]*">', '</table>', '<tr>', '</tr>', '<td>', '</td>', '<th>', '</th>', '<pre>', '</pre>', '<br />', '<br/>', '<br >', '<br>', '<p>', '</p>', '<p />', '<b>', '</b>', '<u>', '</u>', '<i>', '</i>', '<em>', '</em>', '<strong>', '</strong>', '<li>', '</li>', '<ul>', '</ul>', '<ol>', '</ol>', '<del>', '</del>', '<dir>', '</dir>', '<s>', '</s>', '</a>', '</font>', '<!--', '<h1 id="main_page_title">', '<h1 class="main_page_title">', '<h1 id="main_page_title" class="main_page_title">', '</h1>', '<img (class="inline_image" )?alt="[^"]*" src="[^"]*" (complete="true" )*/>', '<img src=["\'][^"\'<>]*["\']( border=["\'][^"\'<>]*["\'])?( alt=["\'][^"\'<>]*["\'])?( )?(/)?' . '>', '<a href=["\'][^"\'<>]*["\']( target=["\'][^"\'<>]*["\'])?' . '>');
    // HTML tag may actually be used in very limited conditions: only the following HTML seqs will come out as HTML. This is, unless the blacklist filter is used instead.
    if ($as_admin) {
        $comcode_dangerous = true;
        $comcode_dangerous_html = true;
    } else {
        $comcode_dangerous = $GLOBALS['MICRO_BOOTUP'] == 0 && has_specific_permission($source_member, 'comcode_dangerous');
        $comcode_dangerous_html = false;
        if (has_specific_permission($source_member, 'allow_html') && ($is_all_semihtml || strpos($comcode, '[html') !== false || strpos($comcode, '[semihtml') !== false)) {
            $comcode_dangerous_html = true;
            /*foreach (array_keys($POTENTIALLY_EMPTY_TAGS) as $tag) // Find whether we really need to enable the computational-expensive filtering. Code disabled, not sure why this would have ever worked!
            		{
            			if (($tag!='html') && ($tag!='semihtml') && (strpos($comcode,'['.$tag)!==false))
            			{
            				$comcode_dangerous_html=false;
            				break;
            			}
            		}*/
        }
    }
    if (is_null($pass_id)) {
        $pass_id = strval(mt_rand(0, 32000));
    }
    // This is a unique ID that refers to this specific piece of comcode
    global $COMCODE_ATTACHMENTS;
    if (!array_key_exists($pass_id, $COMCODE_ATTACHMENTS)) {
        $COMCODE_ATTACHMENTS[$pass_id] = array();
    }
    // Tag level
    $current_tag = '';
    $attribute_map = array();
    $tag_output = new ocp_tempcode();
    $continuation = '';
    $close = mixed();
    // Properties that come from our tag
    $white_space_area = true;
    $textual_area = true;
    $formatting_allowed = true;
    $in_html = false;
    $in_semihtml = $is_all_semihtml;
    $in_separate_parse_section = false;
    // Not escaped because it has to be passed to a secondary filter
    $in_code_tag = false;
    $code_nest_stack = 0;
    // Our state
    $status = CCP_NO_MANS_LAND;
    $lax = $GLOBALS['LAX_COMCODE'] || function_exists('get_member') && $source_member != get_member() || count($_POST) == 0;
    // if we don't want to produce errors for technically invalid Comcode
    $tag_stack = array();
    $pos = 0;
    $line_starting = true;
    $just_ended = false;
    $none_wrap_length = 0;
    $just_new_line = true;
    // So we can detect lists starting right away
    $just_title = false;
    global $NUM_LINES;
    $NUM_LINES = 0;
    $queued_tempcode = new ocp_tempcode();
    $mindless_mode = false;
    // If we're doing a semi parse mode and going over a tag we don't actually process
    $tag_raw = '';
    if (!is_null($wrap_pos) && strtolower(get_charset()) == 'utf-8') {
        $wrap_pos *= 2;
    }
    $stupidity_mode = get_value('stupidity_mode');
    // bork or leet
    if ($comcode_dangerous) {
        $stupidity_mode = get_param('stupidity_mode', '');
    }
    if ($stupidity_mode == 'leet') {
        $LEET_FILTER = array('B' => '8', 'C' => '(', 'E' => '3', 'G' => '9', 'I' => '1', 'L' => '1', 'O' => '0', 'P' => '9', 'S' => '5', 'U' => '0', 'V' => '\\/', 'Z' => '2');
    }
    $smilies = $GLOBALS['FORUM_DRIVER']->find_emoticons();
    // We'll be needing the smiley array
    $shortcuts = array('(EUR-)' => '&euro;', '{f.}' => '&fnof;', '-|-' => '&dagger;', '=|=' => '&Dagger;', '{%o}' => '&permil;', '{~S}' => '&Scaron;', '{~Z}' => '&#x17D;', '(TM)' => '&trade;', '{~s}' => '&scaron;', '{~z}' => '&#x17E;', '{.Y.}' => '&Yuml;', '(c)' => '&copy;', '(r)' => '&reg;', '---' => '&mdash;', '--' => '&ndash;', '...' => '&hellip;', '-->' => '&rarr;', '<--' => '&larr;');
    // Text syntax possibilities, that get maintained as our cursor moves through the text block
    $list_indent = 0;
    $list_type = 'ul';
    if ($is_all_semihtml) {
        filter_html($as_admin, $source_member, $pos, $len, $comcode, false, false);
    }
    // Pre-filter the whole lot (note that this means during general output we do no additional filtering)
    while ($pos < $len) {
        $next = $comcode[$pos];
        ++$pos;
        // State machine
        switch ($status) {
            case CCP_NO_MANS_LAND:
                if ($next == '[') {
                    // Look ahead to make sure it's a valid tag. If it's not then it's considered normal user input, not a tag at all
                    $dif = $pos < $len && $comcode[$pos] == '/' ? 1 : 0;
                    $ahead = substr($comcode, $pos + $dif, MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH);
                    $equal_pos = strpos($ahead, '=');
                    $space_pos = strpos($ahead, ' ');
                    $end_pos = strpos($ahead, ']');
                    $lax_end_pos = strpos($ahead, '[');
                    $cl_pos = strpos($ahead, chr(10));
                    if ($equal_pos === false) {
                        $equal_pos = MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH + 3;
                    }
                    if ($space_pos === false) {
                        $space_pos = MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH + 3;
                    }
                    if ($end_pos === false) {
                        $end_pos = MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH + 3;
                    }
                    if ($lax_end_pos === false) {
                        $lax_end_pos = MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH + 3;
                    }
                    if ($cl_pos === false) {
                        $cl_pos = MAX_COMCODE_TAG_LOOK_AHEAD_LENGTH + 3;
                    }
                    $use_pos = min($equal_pos, $space_pos, $end_pos, $lax_end_pos, $cl_pos);
                    $potential_tag = strtolower(substr($ahead, 0, $use_pos));
                    if ($use_pos != 22 && (!$in_semihtml || $dif == 1 || $potential_tag != 'html' && $potential_tag != 'semihtml') && (!$in_html || $dif == 1 && $potential_tag == 'html') && (!$in_code_tag || isset($CODE_TAGS[$potential_tag]) && $potential_tag == $current_tag) && (!$structure_sweep || $potential_tag != 'contents')) {
                        if ($in_code_tag) {
                            if ($dif == 1) {
                                $code_nest_stack--;
                            } else {
                                $code_nest_stack++;
                            }
                            $ok = $code_nest_stack == -1;
                        } else {
                            $ok = true;
                        }
                        if ($ok) {
                            if (!isset($VALID_COMCODE_TAGS[$potential_tag])) {
                                if (!$IMPORTED_CUSTOM_COMCODE) {
                                    _custom_comcode_import($connection);
                                }
                            }
                            if (isset($VALID_COMCODE_TAGS[$potential_tag]) && strtolower(substr($ahead, 0, 2)) != 'i ') {
                                if ($comcode[$pos] != '/' || count($tag_stack) == 0) {
                                    $mindless_mode = $semiparse_mode && (!isset($REVERSABLE_TAGS[$potential_tag]) || is_string($REVERSABLE_TAGS[$potential_tag]) && preg_match($REVERSABLE_TAGS[$potential_tag], substr($comcode, $pos, 100)) != 0) && !isset($PUREHTML_TAGS[$potential_tag]);
                                } else {
                                    $mindless_mode = $tag_stack[count($tag_stack) - 1][7];
                                }
                                $close = false;
                                $current_tag = '';
                                if ($GLOBALS['XSS_DETECT']) {
                                    ocp_mark_as_escaped($continuation);
                                }
                                $tag_output->attach($continuation);
                                $continuation = '';
                                if ($just_new_line || isset($BLOCK_TAGS[$potential_tag])) {
                                    list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                                    if ($GLOBALS['XSS_DETECT']) {
                                        ocp_mark_as_escaped($close_list);
                                    }
                                    $tag_output->attach($close_list);
                                }
                                $status = CCP_STARTING_TAG;
                                if ($mindless_mode) {
                                    if ($comcode[$pos] != '/') {
                                        if (array_key_exists($potential_tag, $BLOCK_TAGS)) {
                                            $tag_raw = '&#8203;<kbd title="' . escape_html($potential_tag) . '" class="ocp_keep_block">[';
                                        } else {
                                            $tag_raw = '&#8203;<kbd title="' . escape_html($potential_tag) . '" class="ocp_keep">[';
                                        }
                                    } else {
                                        $tag_raw = '[';
                                    }
                                } else {
                                    $tag_raw = '';
                                }
                                continue;
                            }
                        }
                    } else {
                        if ($use_pos != 22 && (($in_semihtml || $in_html) && ($potential_tag == 'html' || $potential_tag == 'semihtml')) && !$in_code_tag) {
                            $ahc = strpos($ahead, ']');
                            if ($ahc !== false) {
                                $pos += $ahc + 1;
                                continue;
                            }
                        }
                    }
                }
                if ($in_html || $in_semihtml && !$in_code_tag && ($next == '<' || $next == '>' || $next == '"')) {
                    if ($next == chr(10)) {
                        ++$NUM_LINES;
                    }
                    if (!$comcode_dangerous_html && $next == '<') {
                        $close = strpos($comcode, '>', $pos - 1);
                        $portion = substr($comcode, $pos - 1, $close - $pos + 2);
                        $seq_ok = false;
                        foreach ($allowed_html_seqs as $allowed_html_seq) {
                            if (preg_match('#^' . $allowed_html_seq . '$#', $portion) != 0) {
                                $seq_ok = true;
                            }
                        }
                        if (!$seq_ok) {
                            // $next='&lt;';  //OLD STYLE
                            if ($close !== false) {
                                $pos = $close + 1;
                            }
                            // NEW STYLE
                            continue;
                        }
                    }
                    if (substr($comcode, $pos - 1, 4) == '<!--') {
                        $continuation .= '<!--';
                        $pos += 3;
                    } else {
                        $continuation .= $mindless_mode && $in_code_tag ? escape_html($next) : $next;
                    }
                } else {
                    // Text-format possibilities
                    if ($just_new_line && $formatting_allowed && !$wml) {
                        if ($continuation != '') {
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($continuation);
                            }
                            $tag_output->attach($continuation);
                            $continuation = '';
                        }
                        // List
                        $found_list = false;
                        $old_list_indent = $list_indent;
                        if ($pos + 2 < $len && is_numeric($next) && (is_numeric($comcode[$pos]) && $comcode[$pos + 1] == ')' && $comcode[$pos + 2] == ' ' || $comcode[$pos] == ')' && $comcode[$pos + 1] == ' ') && ($list_type == '1' && $list_indent != 0 || preg_match('#^[^\\n]*\\n\\d+\\) #', substr($comcode, $pos + 1)) != 0)) {
                            if ($list_indent != 0 && $list_type != '1') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                if ($GLOBALS['XSS_DETECT']) {
                                    ocp_mark_as_escaped($temp_tpl);
                                }
                                $tag_output->attach($temp_tpl);
                            }
                            $list_indent = 1;
                            $found_list = true;
                            $scan_pos = $pos;
                            $list_type = '1';
                        } elseif ($pos + 2 < $len && ord($next) >= ord('a') && ord($next) <= ord('z') && $comcode[$pos] == ')' && $comcode[$pos + 1] == ' ' && ($list_type == 'a' && $list_indent != 0 || preg_match('#^[^\\n]*\\n[a-z]+\\) #', substr($comcode, $pos + 1)) != 0)) {
                            if ($list_indent != 0 && $list_type != 'a') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                if ($GLOBALS['XSS_DETECT']) {
                                    ocp_mark_as_escaped($temp_tpl);
                                }
                                $tag_output->attach($temp_tpl);
                            }
                            $list_indent = 1;
                            $found_list = true;
                            $scan_pos = $pos;
                            $list_type = 'a';
                        } elseif ($next == ' ') {
                            if ($old_list_indent != 0 && $list_type != 'ul') {
                                list($temp_tpl, $old_list_indent) = _close_open_lists($list_indent, $list_type);
                                if ($GLOBALS['XSS_DETECT']) {
                                    ocp_mark_as_escaped($temp_tpl);
                                }
                                $tag_output->attach($temp_tpl);
                            }
                            $scan_pos = $pos - 1;
                            $list_indent = 0;
                            while ($scan_pos < $len) {
                                $scan_next = $comcode[$scan_pos];
                                if ($scan_next == '-' && $scan_pos + 1 < $len && $comcode[$scan_pos + 1] == ' ') {
                                    $found_list = true;
                                    break;
                                } else {
                                    if ($scan_next == ' ') {
                                        ++$list_indent;
                                    } else {
                                        break;
                                    }
                                }
                                ++$scan_pos;
                            }
                            if (!$found_list) {
                                $list_indent = 0;
                            } else {
                                $list_type = 'ul';
                            }
                        } else {
                            list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($close_list);
                            }
                            $tag_output->attach($close_list);
                            $old_list_indent = 0;
                            if ($next == '-' && !$just_title) {
                                $scan_pos = $pos;
                                $found_rule = true;
                                while ($scan_pos < $len) {
                                    $scan_next = $comcode[$scan_pos];
                                    if ($scan_next != '-') {
                                        if ($scan_next == chr(10)) {
                                            ++$NUM_LINES;
                                            break;
                                        } else {
                                            $found_rule = false;
                                        }
                                    }
                                    ++$scan_pos;
                                }
                                if ($found_rule) {
                                    $_temp_tpl = do_template('COMCODE_TEXTCODE_LINE');
                                    $tag_output->attach($_temp_tpl);
                                    $pos = $scan_pos + 1;
                                    $just_ended = true;
                                    $none_wrap_length = 0;
                                    continue;
                                }
                            }
                        }
                        // List handling
                        if ($list_indent == $old_list_indent && $old_list_indent != 0) {
                            $temp_tpl = '</li>';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                        }
                        for ($i = $list_indent; $i < $old_list_indent; ++$i) {
                            $temp_tpl = '</li>';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                            $temp_tpl = $list_type == 'ul' ? '</ul>' : '</ol>';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                        }
                        if ($list_indent < $old_list_indent && $list_indent != 0) {
                            $temp_tpl = '</li>';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                        }
                        if ($found_list) {
                            if ($list_indent - $old_list_indent > 1 && !$lax) {
                                return comcode_parse_error($preparse_mode, array('CCP_LIST_JUMPYNESS'), $pos, $comcode, $check_only);
                            }
                            for ($i = $old_list_indent; $i < $list_indent; ++$i) {
                                switch ($list_type) {
                                    case 'ul':
                                        if ($i < $list_indent - 1) {
                                            $temp_tpl = '<ul><li>';
                                        } else {
                                            $temp_tpl = '<ul>';
                                        }
                                        if ($GLOBALS['XSS_DETECT']) {
                                            ocp_mark_as_escaped($temp_tpl);
                                        }
                                        $tag_output->attach($temp_tpl);
                                        break;
                                    case '1':
                                        if ($i < $list_indent - 1) {
                                            $temp_tpl = '<ol type="1"><li>';
                                        } else {
                                            $temp_tpl = '<ol type="1">';
                                        }
                                        if ($GLOBALS['XSS_DETECT']) {
                                            ocp_mark_as_escaped($temp_tpl);
                                        }
                                        $tag_output->attach($temp_tpl);
                                        break;
                                    case 'a':
                                        if ($i < $list_indent - 1) {
                                            $temp_tpl = '<ol type="a"><li>';
                                        } else {
                                            $temp_tpl = '<ol type="a">';
                                        }
                                        if ($GLOBALS['XSS_DETECT']) {
                                            ocp_mark_as_escaped($temp_tpl);
                                        }
                                        $tag_output->attach($temp_tpl);
                                        break;
                                }
                            }
                            $temp_tpl = '<li>';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                            $just_ended = true;
                            $none_wrap_length = 0;
                            $next = '';
                            $pos = $scan_pos + 2;
                        }
                    }
                    if ($next == chr(10) && $white_space_area && $print_mode && $list_indent == 0) {
                        $tag_output->attach($queued_tempcode);
                        $queued_tempcode = new ocp_tempcode();
                    }
                    if ($next == chr(10) && $white_space_area && !$in_semihtml && (!$just_ended || $semiparse_mode || substr($comcode, $pos, 3) == ' - ')) {
                        ++$NUM_LINES;
                        $line_starting = true;
                        if ($GLOBALS['XSS_DETECT']) {
                            ocp_mark_as_escaped($continuation);
                        }
                        $tag_output->attach($continuation);
                        $continuation = '';
                        $just_new_line = true;
                        $none_wrap_length = 0;
                        if ($list_indent == 0 && !$just_ended) {
                            $temp_tpl = '<br />';
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($temp_tpl);
                            }
                            $tag_output->attach($temp_tpl);
                        }
                    } else {
                        $just_new_line = false;
                        if ($next == ' ' && $white_space_area && !$in_semihtml) {
                            if ($line_starting || $pos > 1 && $comcode[$pos - 2] == ' ') {
                                $next = '&nbsp;';
                                ++$none_wrap_length;
                            } else {
                                $none_wrap_length = 0;
                            }
                            $continuation .= $mindless_mode && $in_code_tag ? escape_html($next) : $next;
                        } elseif ($next == "\t" && $white_space_area && !$in_semihtml) {
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($continuation);
                            }
                            $tag_output->attach($continuation);
                            $continuation = '';
                            $tab_tpl = do_template('COMCODE_TEXTCODE_TAB');
                            $_tab_tpl = $tab_tpl->evaluate();
                            $none_wrap_length += strlen($_tab_tpl);
                            $tag_output->attach($tab_tpl);
                        } else {
                            if ($next == ' ' || $next == "\t" || $just_ended) {
                                $none_wrap_length = 0;
                            } else {
                                if (!is_null($wrap_pos) && $none_wrap_length >= $wrap_pos && (strtolower(get_charset()) != 'utf-8' || preg_replace(array('#[\\x09\\x0A\\x0D\\x20-\\x7E]#', '#[\\xC2-\\xDF][\\x80-\\xBF]#', '#\\xE0[\\xA0-\\xBF][\\x80-\\xBF]#', '#[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}#', '#\\xED[\\x80-\\x9F][\\x80-\\xBF]#', '#\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}#', '#[\\xF1-\\xF3][\\x80-\\xBF]{3}#', '#\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}#'), array('', '', '', '', '', '', '', ''), $continuation) == '') && $textual_area && !$in_semihtml) {
                                    if ($GLOBALS['XSS_DETECT']) {
                                        ocp_mark_as_escaped($continuation);
                                    }
                                    $tag_output->attach($continuation);
                                    $continuation = '';
                                    $temp_tpl = '<br />';
                                    if ($GLOBALS['XSS_DETECT']) {
                                        ocp_mark_as_escaped($temp_tpl);
                                    }
                                    $tag_output->attach($temp_tpl);
                                    $none_wrap_length = 0;
                                } elseif ($textual_area) {
                                    ++$none_wrap_length;
                                }
                            }
                            $line_starting = false;
                            $just_ended = false;
                            $differented = false;
                            // If somehow via lookahead we've changed this to HTML and thus won't use it in raw form
                            // Variable lookahead
                            if (!$in_code_tag && ($next == '{' && isset($comcode[$pos]) && ($comcode[$pos] == '$' || $comcode[$pos] == '+' || $comcode[$pos] == '!'))) {
                                if ($comcode_dangerous) {
                                    if (!$in_code_tag && (!$semiparse_mode || in_tag_stack($tag_stack, array('url', 'img', 'flash')))) {
                                        if ($GLOBALS['XSS_DETECT']) {
                                            ocp_mark_as_escaped($continuation);
                                        }
                                        $tag_output->attach($continuation);
                                        $continuation = '';
                                        if ($comcode[$pos] == '+') {
                                            $p_end = $pos + 5;
                                            while ($p_end < $len) {
                                                $p_portion = substr($comcode, $pos - 1, $p_end - ($pos - 1) + 5);
                                                if (substr_count($p_portion, '{+START') == substr_count($p_portion, '{+END')) {
                                                    break;
                                                }
                                                $p_end++;
                                            }
                                            $p_len = 1;
                                            while ($pos + $p_len < $len) {
                                                $p_portion = substr($comcode, $pos - 1, $p_len);
                                                if (substr_count(str_replace('{', ' { ', $p_portion), '{') == substr_count(str_replace('}', ' } ', $p_portion), '}')) {
                                                    break;
                                                }
                                                // str_replace is to workaround a Quercus bug #4494
                                                $p_len++;
                                            }
                                            $p_len--;
                                            $p_portion = substr($comcode, $pos + $p_len, $p_end - ($pos + $p_len));
                                            require_code('tempcode_compiler');
                                            $ret = template_to_tempcode(substr($comcode, $pos - 1, $p_len + 1) . '{DIRECTIVE_EMBEDMENT}' . substr($comcode, $p_end, 6));
                                            $attaches_before = count($COMCODE_ATTACHMENTS[$pass_id]);
                                            $ret->singular_bind('DIRECTIVE_EMBEDMENT', comcode_text_to_tempcode($p_portion, $source_member, $as_admin, $wrap_pos, $pass_id, $connection, $semiparse_mode, $preparse_mode, $in_semihtml, $structure_sweep, $check_only, $highlight_bits, $on_behalf_of_member));
                                            for ($attach_inspect = $attaches_before; $attach_inspect < count($COMCODE_ATTACHMENTS[$pass_id]); $attach_inspect++) {
                                                $COMCODE_ATTACHMENTS[$pass_id][$attach_inspect]['marker'] += $pos + $p_len;
                                            }
                                            $pos = $p_end + 6;
                                        } elseif ($comcode[$pos] == '!') {
                                            $p_len = $pos;
                                            $balance = 1;
                                            while ($p_len < $len && $balance != 0) {
                                                if ($comcode[$p_len] == '{') {
                                                    $balance++;
                                                } elseif ($comcode[$p_len] == '}') {
                                                    $balance--;
                                                }
                                                $p_len++;
                                            }
                                            $ret = new ocp_tempcode();
                                            $less_pos = $pos - 1;
                                            $ret->parse_from($comcode, $less_pos, $p_len);
                                            $pos = $p_len;
                                            if ($ret->parameterless(0) && $pos < $len) {
                                                $matches = array();
                                                if (preg_match('#\\{\\!([\\w\\d\\_\\:]+)(\\}|$)#U', substr($comcode, $less_pos, $p_len - $less_pos), $matches) != 0) {
                                                    $temp_lang_string = $matches[1];
                                                    $ret = comcode_lang_string($temp_lang_string);
                                                    // Recreate as a Comcode lang string
                                                }
                                            }
                                        } else {
                                            $p_len = $pos;
                                            $balance = 1;
                                            while ($p_len < $len && $balance != 0) {
                                                if ($comcode[$p_len] == '{') {
                                                    $balance++;
                                                } elseif ($comcode[$p_len] == '}') {
                                                    $balance--;
                                                }
                                                $p_len++;
                                            }
                                            $ret = new ocp_tempcode();
                                            $less_pos = $pos - 1;
                                            $ret->parse_from($comcode, $less_pos, $p_len);
                                            $pos = $p_len;
                                        }
                                        $differented = true;
                                        if ($pos <= $len || !$lax) {
                                            $tag_output->attach($ret);
                                        }
                                    }
                                } else {
                                    if ($comcode[$pos] == '$' && $pos < $len - 2 && $comcode[$pos + 1] == ',' && strpos($comcode, '}', $pos) !== false) {
                                        $pos = strpos($comcode, '}', $pos) + 1;
                                        $differented = true;
                                    }
                                }
                            }
                            // Escaping of comcode tag starts lookahead
                            if ($next == '\\' && !$in_code_tag) {
                                if ($pos != $len && ($comcode[$pos] == '"' || substr($comcode, $pos - 1, 6) == '&quot;')) {
                                    if ($semiparse_mode) {
                                        $continuation .= '\\';
                                    }
                                    if ($comcode[$pos] == '"') {
                                        $continuation .= $mindless_mode ? '&quot;' : '"';
                                        ++$pos;
                                    } else {
                                        $continuation .= '&quot;';
                                        $pos += 6;
                                    }
                                    $differented = true;
                                } elseif ($pos != $len && $comcode[$pos] == '[') {
                                    if ($semiparse_mode) {
                                        $continuation .= '\\';
                                    }
                                    $continuation .= '[';
                                    ++$pos;
                                    $differented = true;
                                } elseif ($pos != $len && $comcode[$pos] == '{') {
                                    if ($semiparse_mode) {
                                        $continuation .= '\\';
                                    }
                                    $continuation .= '{';
                                    ++$pos;
                                    $differented = true;
                                } elseif ($pos == $len || $comcode[$pos] == '\\') {
                                    if ($semiparse_mode) {
                                        $continuation .= '\\';
                                    }
                                    $continuation .= '\\';
                                    ++$pos;
                                    $differented = true;
                                }
                            }
                            if (!$differented) {
                                if (($textual_area || $in_semihtml) && trim($next) != '' && !$wml) {
                                    // Emoticon lookahead
                                    foreach ($smilies as $smiley => $imgcode) {
                                        if ($in_semihtml) {
                                            $smiley = ' ' . $smiley . ' ';
                                        }
                                        if ($next == $smiley[0]) {
                                            if (substr($comcode, $pos - 1, strlen($smiley)) == $smiley) {
                                                if ($GLOBALS['XSS_DETECT']) {
                                                    ocp_mark_as_escaped($continuation);
                                                }
                                                $tag_output->attach($continuation);
                                                $continuation = '';
                                                $pos += strlen($smiley) - 1;
                                                $differented = true;
                                                $tag_output->attach(do_emoticon($imgcode));
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            if (trim($next) != '' && !$in_code_tag && !$differented) {
                                // CEDI pages
                                if ($pos < $len && $next == '[' && $pos + 1 < $len && $comcode[$pos] == '[' && !$semiparse_mode && addon_installed('cedi')) {
                                    $matches = array();
                                    if (preg_match('#^\\[([^\\[\\]]*)\\]\\]#', substr($comcode, $pos, 200), $matches) != 0) {
                                        $cedi_page_name = $matches[1];
                                        if ($GLOBALS['XSS_DETECT']) {
                                            ocp_mark_as_escaped($continuation);
                                        }
                                        $tag_output->attach($continuation);
                                        $continuation = '';
                                        $hash_pos = strpos($cedi_page_name, '#');
                                        if ($hash_pos !== false) {
                                            $jump_to = substr($cedi_page_name, $hash_pos + 1);
                                            $cedi_page_name = substr($cedi_page_name, 0, $hash_pos);
                                        } else {
                                            $jump_to = '';
                                        }
                                        $cedi_page_url = build_url(array('page' => 'cedi', 'type' => 'misc', 'find' => $cedi_page_name), get_module_zone('cedi'));
                                        if ($jump_to != '') {
                                            $cedi_page_url->attach('#' . $jump_to);
                                        }
                                        $tag_output->attach(do_template('COMCODE_CEDI_LINK', array('_GUID' => 'ebcd7ba5290c5b2513272a53b4d666e5', 'URL' => $cedi_page_url, 'TEXT' => $cedi_page_name)));
                                        $pos += strlen($matches[1]) + 3;
                                        $differented = true;
                                    }
                                }
                                // Usernames
                                if ($pos < $len && $next == '{' && $pos + 1 < $len && $comcode[$pos] == '{' && !$in_code_tag && !$semiparse_mode) {
                                    $matches = array();
                                    if (preg_match('#^\\{([^"{}&\'\\$<>]+)\\}\\}#', substr($comcode, $pos, 80), $matches) != 0) {
                                        $username = $matches[1];
                                        if ($username[0] == '?') {
                                            $username_info = true;
                                            $username = substr($username, 1);
                                        } else {
                                            $username_info = false;
                                        }
                                        $this_member_id = $GLOBALS['FORUM_DRIVER']->get_member_from_username($username);
                                        if (!is_null($this_member_id) && !is_guest($this_member_id)) {
                                            if ($GLOBALS['XSS_DETECT']) {
                                                ocp_mark_as_escaped($continuation);
                                            }
                                            $tag_output->attach($continuation);
                                            $continuation = '';
                                            $poster_url = $GLOBALS['FORUM_DRIVER']->member_profile_url($this_member_id, false, true);
                                            if (get_forum_type() == 'ocf' && $username_info) {
                                                require_lang('ocf');
                                                require_code('ocf_members2');
                                                $details = ocf_show_member_box($this_member_id);
                                                $tag_output->attach(do_template('HYPERLINK_TOOLTIP', array('_GUID' => 'd8f4f4ac70bd52b3ef9ee74ae9c5e085', 'TOOLTIP' => $details, 'CAPTION' => $username, 'URL' => $poster_url, 'NEW_WINDOW' => false)));
                                            } else {
                                                $tag_output->attach(hyperlink($poster_url, $username));
                                            }
                                            $pos += strlen($matches[1]) + 3;
                                            $differented = true;
                                        }
                                    }
                                }
                            }
                            if ($textual_area && !$in_code_tag && trim($next) != '' && !$differented) {
                                // Shortcut lookahead
                                if (!$differented) {
                                    if ($in_semihtml && substr($comcode, $pos - 1, 3) == '-->') {
                                        $continuation .= '-->';
                                        $pos += 2;
                                        break;
                                    }
                                    foreach ($shortcuts as $code => $replacement) {
                                        if ($next == $code[0] && substr($comcode, $pos - 1, strlen($code)) == $code) {
                                            if ($GLOBALS['XSS_DETECT']) {
                                                ocp_mark_as_escaped($continuation);
                                            }
                                            $tag_output->attach($continuation);
                                            $continuation = '';
                                            $pos += strlen($code) - 1;
                                            $differented = true;
                                            if ($GLOBALS['XSS_DETECT']) {
                                                ocp_mark_as_escaped($replacement);
                                            }
                                            $tag_output->attach($replacement);
                                            break;
                                        }
                                    }
                                }
                            }
                            if ($textual_area && !$in_code_tag && trim($next) != '' && !$differented) {
                                // Table syntax
                                if (!$differented) {
                                    if ($pos < $len && $comcode[$pos] == '|') {
                                        $end_tbl = strpos($comcode, chr(10) . '|}', $pos);
                                        if ($end_tbl !== false) {
                                            $end_fst_line_pos = strpos($comcode, chr(10), $pos);
                                            $caption = substr($comcode, $pos + 2, max($end_fst_line_pos - $pos - 2, 0));
                                            $pos += strlen($caption) + 1;
                                            $rows = preg_split('#(\\|-|\\|\\})#Um', substr($comcode, $pos, $end_tbl - $pos));
                                            if (preg_match('#(^|\\s)floats($|\\s)#', $caption) != 0) {
                                                $caption = preg_replace('#(^|\\s)floats($|\\s)#', '', $caption);
                                                $ratios = array();
                                                $ratios_matches = array();
                                                if (preg_match('#(^|\\s)([\\d\\.]+%(:[\\d\\.]+%)*)($|\\s)#', $caption, $ratios_matches) != 0) {
                                                    $ratios = explode(':', $ratios_matches[2]);
                                                    $caption = str_replace($ratios_matches[0], '', $caption);
                                                }
                                                foreach ($rows as $h => $row) {
                                                    if ($h != 0) {
                                                        $tag_output->attach(do_template('BLOCK_SEPARATOR'));
                                                    }
                                                    $cells = preg_split('/(\\n\\! | \\!\\! |\\n\\| | \\|\\| )/', $row, -1, PREG_SPLIT_DELIM_CAPTURE);
                                                    array_shift($cells);
                                                    // First one is non-existant empty
                                                    $spec = true;
                                                    // Find which to float
                                                    $to_float = NULL;
                                                    foreach ($cells as $i => $cell) {
                                                        if (!$spec) {
                                                            if (strpos($cell, '!') !== false || is_null($to_float)) {
                                                                $to_float = $i;
                                                            }
                                                        }
                                                        $spec = !$spec;
                                                    }
                                                    $tag_output->attach(do_template('COMCODE_FAKE_TABLE_WRAP_START'));
                                                    // Do floated one
                                                    $i_dir_1 = $to_float == 1 ? 'left' : 'right';
                                                    $i_dir_2 = $to_float != 1 ? 'left' : 'right';
                                                    if (preg_match('#(^|\\s)wide($|\\s)#', $caption) != 0) {
                                                        $tag_output->attach(do_template('COMCODE_FAKE_TABLE_WIDE_START', array('_GUID' => 'ced8c3a142f74296a464b085ba6891c9', 'WIDTH' => array_key_exists($to_float == 1 ? 0 : count($cells) - 1, $ratios) ? $ratios[$to_float == 1 ? 0 : count($cells) - 1] : (count($cells) == 2 ? '0' : float_to_raw_string(97.0 / (floatval(count($cells)) / 2.0 - 1.0), 2) . '%'), 'FLOAT' => $i_dir_1, 'PADDING' => $to_float == 1 ? '' : '-left', 'PADDING_AMOUNT' => count($cells) == 2 ? '0' : float_to_raw_string(3.0 / (floatval(count($cells) - 2) / 2.0), 2))));
                                                    } else {
                                                        $tag_output->attach(do_template('COMCODE_FAKE_TABLE_START', array('_GUID' => '90be72fcbb6b9d8a312da0bee5b86cb3', 'WIDTH' => array_key_exists($to_float, $ratios) ? $ratios[$to_float] : '', 'FLOAT' => $i_dir_1, 'PADDING' => $to_float == 1 ? '' : '-left', 'PADDING_AMOUNT' => count($cells) == 2 ? '0' : float_to_raw_string(3.0 / (floatval(count($cells) - 2.0) / 2.0), 2))));
                                                    }
                                                    $attaches_before = count($COMCODE_ATTACHMENTS[$pass_id]);
                                                    $tag_output->attach(comcode_text_to_tempcode(isset($cells[$to_float]) ? rtrim($cells[$to_float]) : '', $source_member, $as_admin, 60, $pass_id, $connection, $semiparse_mode, $preparse_mode, $in_semihtml, $structure_sweep, $check_only, $highlight_bits, $on_behalf_of_member));
                                                    for ($attach_inspect = $attaches_before; $attach_inspect < count($COMCODE_ATTACHMENTS[$pass_id]); $attach_inspect++) {
                                                        $COMCODE_ATTACHMENTS[$pass_id][$attach_inspect]['marker'] += strpos($comcode, $cells[$to_float], $pos);
                                                    }
                                                    $tag_output->attach(do_template('COMCODE_FAKE_TABLE_END'));
                                                    // Do non-floated ones
                                                    $cell_i = 0;
                                                    foreach ($cells as $i => $cell) {
                                                        if ($i % 2 == 1) {
                                                            if ($i != $to_float) {
                                                                if (preg_match('#(^|\\s)wide($|\\s)#', $caption) != 0) {
                                                                    $tag_output->attach(do_template('COMCODE_FAKE_TABLE_WIDE2_START', array('_GUID' => '9bac42a1b62c5c9a2f758639fcb3bb2f', 'WIDTH' => array_key_exists($cell_i, $ratios) ? $ratios[$cell_i] : float_to_raw_string(97.0 / (floatval(count($cells)) / 2.0), 2) . '%', 'PADDING_AMOUNT' => count($cells) == 2 ? '0' : float_to_raw_string(3.0 / (floatval(count($cells) - 2) / 2.0), 2), 'FLOAT' => $i_dir_1, 'PADDING' => $to_float == 1 || $cell_i != 0 ? '-left' : '')));
                                                                } else {
                                                                    $tag_output->attach(do_template('COMCODE_FAKE_TABLE_2_START', array('_GUID' => '0f15f9d5554635ed7ac154c9dc5c72b8', 'WIDTH' => array_key_exists($cell_i, $ratios) ? $ratios[$cell_i] : '', 'FLOAT' => $i_dir_1, 'PADDING' => $to_float == 1 || $cell_i != 0 ? '-left' : '', 'PADDING_AMOUNT' => count($cells) == 2 ? '0' : float_to_raw_string(3.0 / (floatval(count($cells) - 2) / 2.0), 2))));
                                                                }
                                                                $attaches_before = count($COMCODE_ATTACHMENTS[$pass_id]);
                                                                $tag_output->attach(comcode_text_to_tempcode(rtrim($cell), $source_member, $as_admin, 60, $pass_id, $connection, $semiparse_mode, $preparse_mode, $in_semihtml, $structure_sweep, $check_only, $highlight_bits, $on_behalf_of_member));
                                                                for ($attach_inspect = $attaches_before; $attach_inspect < count($COMCODE_ATTACHMENTS[$pass_id]); $attach_inspect++) {
                                                                    $COMCODE_ATTACHMENTS[$pass_id][$attach_inspect]['marker'] += strpos($comcode, $cell, $pos);
                                                                }
                                                                $tag_output->attach(do_template('COMCODE_FAKE_TABLE_END'));
                                                            }
                                                            $cell_i++;
                                                        }
                                                    }
                                                    $tag_output->attach(do_template('COMCODE_FAKE_TABLE_WRAP_END'));
                                                }
                                            } else {
                                                $ratios = array();
                                                $ratios_matches = array();
                                                if (preg_match('#(^|\\s)([\\d\\.]+%(:[\\d\\.]+%)*)($|\\s)#', $caption, $ratios_matches) != 0) {
                                                    $ratios = explode(':', $ratios_matches[2]);
                                                    $caption = str_replace($ratios_matches[0], '', $caption);
                                                }
                                                if (preg_match('#(^|\\s)wide($|\\s)#', $caption) != 0) {
                                                    $tag_output->attach(do_template('COMCODE_REAL_TABLE_START', array('SUMMARY' => preg_replace('#(^|\\s)wide($|\\s)#', '', $caption))));
                                                } else {
                                                    $tag_output->attach(do_template('COMCODE_REAL_TABLE_START_SUMMARY', array('_GUID' => '0c5674fba61ba14b4b9fa39ea31ff54f', 'CAPTION' => $caption)));
                                                }
                                                foreach ($rows as $table_row) {
                                                    $tag_output->attach(do_template('COMCODE_REAL_TABLE_ROW_START'));
                                                    $cells = preg_split('/(\\n\\! | \\!\\! |\\n\\| | \\|\\| )/', $table_row, -1, PREG_SPLIT_DELIM_CAPTURE);
                                                    array_shift($cells);
                                                    // First one is non-existant empty
                                                    $spec = true;
                                                    $c_type = '';
                                                    $cell_i = 0;
                                                    foreach ($cells as $i => $cell) {
                                                        if ($spec) {
                                                            $c_type = strpos($cell, '!') !== false ? 'th' : 'td';
                                                        } else {
                                                            $attaches_before = count($COMCODE_ATTACHMENTS[$pass_id]);
                                                            $_mid = comcode_text_to_tempcode(rtrim($cell), $source_member, $as_admin, 60, $pass_id, $connection, $semiparse_mode, $preparse_mode, $in_semihtml, $structure_sweep, $check_only, $highlight_bits, $on_behalf_of_member);
                                                            for ($attach_inspect = $attaches_before; $attach_inspect < count($COMCODE_ATTACHMENTS[$pass_id]); $attach_inspect++) {
                                                                $COMCODE_ATTACHMENTS[$pass_id][$attach_inspect]['marker'] += strpos($comcode, $cell, $pos);
                                                            }
                                                            $tag_output->attach(do_template('COMCODE_REAL_TABLE_CELL', array('_GUID' => '6640df8b503f65e3d36f595b0acf7600', 'WIDTH' => array_key_exists($cell_i, $ratios) ? $ratios[$cell_i] : '', 'C_TYPE' => $c_type, 'MID' => $_mid, 'PADDING' => $cell_i == 0 ? '' : '-left', 'PADDING_AMOUNT' => count($cells) == 2 ? '0' : float_to_raw_string(5.0 / (floatval(count($cells) - 2) / 2.0), 2))));
                                                            $cell_i++;
                                                        }
                                                        $spec = !$spec;
                                                    }
                                                    $tag_output->attach(do_template('COMCODE_REAL_TABLE_ROW_END'));
                                                }
                                                $tag_output->attach(do_template('COMCODE_REAL_TABLE_END'));
                                            }
                                            $pos = $end_tbl + 3;
                                            $differented = true;
                                        }
                                    }
                                }
                                // Advertising
                                $b_all = true;
                                // leave true - for test purposes only
                                if (!$differented && !$semiparse_mode && !$in_code_tag && addon_installed('banners') && ($b_all || !has_specific_permission($source_member, 'banner_free'))) {
                                    // Pick up correctly, including permission filtering
                                    if (is_null($ADVERTISING_BANNERS)) {
                                        $rows = $GLOBALS['SITE_DB']->query('SELECT * FROM ' . get_table_prefix() . 'banners b LEFT JOIN ' . get_table_prefix() . 'banner_types t ON b.b_type=t.id WHERE t_comcode_inline=1 AND ' . db_string_not_equal_to('b_title_text', ''), NULL, NULL, true);
                                        if (!is_null($rows)) {
                                            // Filter out what we don't have permission for
                                            if (get_option('use_banner_permissions', true) == '1') {
                                                require_code('permissions');
                                                $groups = _get_where_clause_groups($source_member);
                                                if (!is_null($groups)) {
                                                    $perhaps = collapse_1d_complexity('category_name', $GLOBALS['SITE_DB']->query('SELECT category_name FROM ' . get_table_prefix() . 'group_category_access WHERE ' . db_string_equal_to('module_the_name', 'banners') . ' AND (' . $groups . ')'));
                                                    $new_rows = array();
                                                    foreach ($rows as $row) {
                                                        if (in_array($row['name'], $perhaps)) {
                                                            $new_rows[] = $row;
                                                        }
                                                    }
                                                    $rows = $new_rows;
                                                }
                                            }
                                            $ADVERTISING_BANNERS = array();
                                            foreach ($rows as $row) {
                                                $trigger_text = $row['b_title_text'];
                                                foreach (explode(',', $trigger_text) as $t) {
                                                    if (trim($t) != '') {
                                                        $ADVERTISING_BANNERS[trim($t)] = $row;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    // Apply
                                    if (!is_null($ADVERTISING_BANNERS)) {
                                        foreach ($ADVERTISING_BANNERS as $ad_trigger => $ad_bits) {
                                            if (strtolower($next) == strtolower($ad_trigger[0])) {
                                                if (strtolower(substr($comcode, $pos - 1, strlen($ad_trigger))) == strtolower($ad_trigger)) {
                                                    require_code('banners');
                                                    if ($GLOBALS['XSS_DETECT']) {
                                                        ocp_mark_as_escaped($continuation);
                                                    }
                                                    $tag_output->attach($continuation);
                                                    $continuation = '';
                                                    $differented = true;
                                                    $ad_text = show_banner($ad_bits['name'], $ad_bits['b_title_text'], get_translated_tempcode($ad_bits['caption']), $ad_bits['img_url'], '', $ad_bits['site_url'], $ad_bits['b_type']);
                                                    $embed_output = _do_tags_comcode('tooltip', array('param' => $ad_text, 'url' => url_is_local($ad_bits['site_url']) && $ad_bits['site_url'] != '' ? get_custom_base_url() . '/' . $ad_bits['site_url'] : $ad_bits['site_url']), substr($comcode, $pos - 1, strlen($ad_trigger)), $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits);
                                                    $pos += strlen($ad_trigger) - 1;
                                                    $tag_output->attach($embed_output);
                                                }
                                            }
                                        }
                                    }
                                }
                                // Search highlighting lookahead
                                if (!$differented && !is_null($highlight_bits)) {
                                    foreach ($highlight_bits as $highlight_bit) {
                                        if (strtolower($next) == strtolower($highlight_bit[0])) {
                                            if (strtolower(substr($comcode, $pos - 1, strlen($highlight_bit))) == strtolower($highlight_bit)) {
                                                if ($GLOBALS['XSS_DETECT']) {
                                                    ocp_mark_as_escaped($continuation);
                                                }
                                                $tag_output->attach($continuation);
                                                $continuation = '';
                                                $differented = true;
                                                $embed_output = _do_tags_comcode('highlight', array(), escape_html(substr($comcode, $pos - 1, strlen($highlight_bit))), $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits);
                                                $pos += strlen($highlight_bit) - 1;
                                                $tag_output->attach($embed_output);
                                                break;
                                            }
                                        }
                                    }
                                }
                                // Link lookahead
                                if (!$differented && !$in_code_tag) {
                                    if (!$in_semihtml && $next == 'h' && (substr($comcode, $pos - 1, strlen('http://')) == 'http://' || substr($comcode, $pos - 1, strlen('https://')) == 'https://' || substr($comcode, $pos - 1, strlen('ftp://')) == 'ftp://')) {
                                        $link_end_pos = strpos($comcode, ' ', $pos - 1);
                                        $link_end_pos_2 = strpos($comcode, chr(10), $pos - 1);
                                        $link_end_pos_3 = strpos($comcode, '[', $pos - 1);
                                        $link_end_pos_4 = strpos($comcode, ')', $pos - 1);
                                        $link_end_pos_5 = strpos($comcode, '"', $pos - 1);
                                        $link_end_pos_6 = strpos($comcode, '>', $pos - 1);
                                        $link_end_pos_7 = strpos($comcode, '<', $pos - 1);
                                        $link_end_pos_8 = strpos($comcode, '.' . chr(10), $pos - 1);
                                        $link_end_pos_9 = strpos($comcode, ', ', $pos - 1);
                                        $link_end_pos_10 = strpos($comcode, '. ', $pos - 1);
                                        $link_end_pos_11 = strpos($comcode, "'", $pos - 1);
                                        if ($link_end_pos_2 !== false && ($link_end_pos === false || $link_end_pos_2 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_2;
                                        }
                                        if ($link_end_pos_3 !== false && ($link_end_pos === false || $link_end_pos_3 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_3;
                                        }
                                        if ($link_end_pos_4 !== false && ($link_end_pos === false || $link_end_pos_4 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_4;
                                        }
                                        if ($link_end_pos_5 !== false && ($link_end_pos === false || $link_end_pos_5 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_5;
                                        }
                                        if ($link_end_pos_6 !== false && ($link_end_pos === false || $link_end_pos_6 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_6;
                                        }
                                        if ($link_end_pos_7 !== false && ($link_end_pos === false || $link_end_pos_7 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_7;
                                        }
                                        if ($link_end_pos_8 !== false && ($link_end_pos === false || $link_end_pos_8 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_8;
                                        }
                                        if ($link_end_pos_9 !== false && ($link_end_pos === false || $link_end_pos_9 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_9;
                                        }
                                        if ($link_end_pos_10 !== false && ($link_end_pos === false || $link_end_pos_10 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_10;
                                        }
                                        if ($link_end_pos_11 !== false && ($link_end_pos === false || $link_end_pos_11 < $link_end_pos)) {
                                            $link_end_pos = $link_end_pos_11;
                                        }
                                        if ($link_end_pos === false) {
                                            $link_end_pos = strlen($comcode);
                                        }
                                        $auto_link = preg_replace('#(keep|for)_session=[\\d\\w]*#', 'filtered=1', substr($comcode, $pos - 1, $link_end_pos - $pos + 1));
                                        if (substr($auto_link, -3) != '://') {
                                            if (substr($auto_link, -1) == '.') {
                                                $auto_link = substr($auto_link, 0, strlen($auto_link) - 1);
                                                $link_end_pos--;
                                            }
                                            $auto_link_tempcode = new ocp_tempcode();
                                            $auto_link_tempcode->attach($auto_link);
                                            if (!$check_only) {
                                                $link_captions_title = $GLOBALS['SITE_DB']->query_value_null_ok('url_title_cache', 't_title', array('t_url' => $auto_link));
                                                if (is_null($link_captions_title) || substr($link_captions_title, 0, 1) == '!') {
                                                    $GLOBALS['COMCODE_PARSE_URLS_CHECKED']++;
                                                    if ($GLOBALS['NO_LINK_TITLES'] || $GLOBALS['COMCODE_PARSE_URLS_CHECKED'] >= MAX_URLS_TO_READ) {
                                                        $link_captions_title = $auto_link;
                                                    } else {
                                                        $link_captions_title = '';
                                                        $downloaded_at_link = http_download_file($auto_link, 3000, false);
                                                        if (is_string($downloaded_at_link) && $GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'] !== NULL && strpos($GLOBALS['HTTP_DOWNLOAD_MIME_TYPE'], 'html') !== false && $GLOBALS['HTTP_MESSAGE'] == '200') {
                                                            $matches = array();
                                                            if (preg_match('#\\s*<title[^>]*\\s*>\\s*(.*)\\s*\\s*<\\s*/title\\s*>#miU', $downloaded_at_link, $matches) != 0) {
                                                                require_code('character_sets');
                                                                $link_captions_title = trim(str_replace('&ndash;', '-', str_replace('&mdash;', '-', @html_entity_decode(convert_to_internal_encoding($matches[1]), ENT_QUOTES, get_charset()))));
                                                                if ((strpos(strtolower($link_captions_title), 'login') !== false || strpos(strtolower($link_captions_title), 'log in') !== false) && substr($auto_link, 0, strlen(get_base_url())) == get_base_url()) {
                                                                    $link_captions_title = '';
                                                                }
                                                                // don't show login screen titles for our own website. Better to see the link verbatim
                                                            }
                                                        }
                                                        $GLOBALS['SITE_DB']->query_insert('url_title_cache', array('t_url' => substr($auto_link, 0, 255), 't_title' => substr($link_captions_title, 0, 255)), false, true);
                                                        // To stop weird race-like conditions
                                                    }
                                                }
                                                $embed_output = mixed();
                                                $link_handlers = find_all_hooks('systems', 'comcode_link_handlers');
                                                foreach (array_keys($link_handlers) as $link_handler) {
                                                    require_code('hooks/systems/comcode_link_handlers/' . $link_handler);
                                                    $link_handler_ob = object_factory('Hook_comcode_link_handler_' . $link_handler, true);
                                                    if (is_null($link_handler_ob)) {
                                                        continue;
                                                    }
                                                    $embed_output = $link_handler_ob->bind($auto_link, $link_captions_title, $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits);
                                                    if (!is_null($embed_output)) {
                                                        break;
                                                    }
                                                }
                                                if (is_null($embed_output)) {
                                                    $page_link = url_to_pagelink($auto_link, true);
                                                    if ($link_captions_title == '') {
                                                        $link_captions_title = $auto_link;
                                                    }
                                                    if ($page_link != '') {
                                                        $embed_output = _do_tags_comcode('page', array('param' => $page_link), make_string_tempcode(escape_html($link_captions_title)), $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits);
                                                    } else {
                                                        $embed_output = _do_tags_comcode('url', array('param' => $link_captions_title), $auto_link_tempcode, $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, $highlight_bits);
                                                    }
                                                }
                                            } else {
                                                $embed_output = new ocp_tempcode();
                                            }
                                            if ($GLOBALS['XSS_DETECT']) {
                                                ocp_mark_as_escaped($continuation);
                                            }
                                            $tag_output->attach($continuation);
                                            $continuation = '';
                                            $tag_output->attach($embed_output);
                                            $pos += $link_end_pos - $pos;
                                            $differented = true;
                                        }
                                    }
                                }
                            }
                            if (!$differented) {
                                if ($stupidity_mode != '' && $textual_area) {
                                    if ($stupidity_mode == 'leet' && mt_rand(0, 1) == 1) {
                                        if (array_key_exists(strtoupper($next), $LEET_FILTER)) {
                                            $next = $LEET_FILTER[strtoupper($next)];
                                        }
                                    } elseif ($stupidity_mode == 'bork' && mt_rand(0, 60) == 1) {
                                        $next .= '-bork-bork-bork-';
                                    }
                                }
                                if (!$in_separate_parse_section && (!$in_semihtml || !$comcode_dangerous_html && !$is_all_semihtml)) {
                                    if ($next == '&') {
                                        $ahead = substr($comcode, $pos, 20);
                                        $ahead_lower = strtolower($ahead);
                                        $matches = array();
                                        $entity = preg_match('#^(\\#)?([\\w]*);#', $ahead_lower, $matches) != 0;
                                        // If it is a SAFE entity, use it
                                        if ($entity && !$in_code_tag) {
                                            if ($matches[1] == '' && ($in_semihtml || isset($ALLOWED_ENTITIES[$matches[2]]))) {
                                                $pos += strlen($matches[2]) + 1;
                                                $continuation .= '&' . $matches[2] . ';';
                                            } elseif (is_numeric($matches[2]) && $matches[1] == '#') {
                                                $matched_entity = intval(base_convert($matches[2], 16, 10));
                                                if ($matched_entity < 127 && array_key_exists(chr($matched_entity), $POTENTIAL_JS_NAUGHTY_ARRAY)) {
                                                    $continuation .= escape_html($next);
                                                } else {
                                                    $pos += strlen($matches[2]) + 2;
                                                    $continuation .= '&#' . $matches[2] . ';';
                                                }
                                            } else {
                                                $continuation .= '&amp;';
                                            }
                                        } else {
                                            $continuation .= '&amp;';
                                        }
                                    } else {
                                        $continuation .= escape_html($next);
                                    }
                                } else {
                                    $continuation .= $next;
                                }
                            }
                        }
                    }
                }
                break;
            case CCP_IN_TAG_NAME:
                if ($mindless_mode && $next != '[') {
                    $tag_raw .= $next;
                }
                if ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                    $current_attribute_name = 'param';
                } elseif (trim($next) == '') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                } elseif ($next == '[') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_OPEN_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    $next = ']';
                    $pos--;
                }
                if ($next == ']') {
                    if ($close) {
                        if ($formatting_allowed) {
                            list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($close_list);
                            }
                            $tag_output->attach($close_list);
                        }
                        if (count($tag_stack) == 0) {
                            if ($lax) {
                                $status = CCP_NO_MANS_LAND;
                                break;
                            }
                            return comcode_parse_error($preparse_mode, array('CCP_NO_CLOSE', $current_tag), strrpos(substr($comcode, 0, $pos), '['), $comcode, $check_only);
                        }
                        $has_it = false;
                        foreach (array_reverse($tag_stack) as $t) {
                            if ($t[0] == $current_tag) {
                                $has_it = true;
                                break;
                            }
                            if ($in_semihtml && ($current_tag == 'html' || $current_tag == 'semihtml')) {
                                // Only search one level for this
                                break;
                            }
                        }
                        if ($has_it) {
                            $_last = array_pop($tag_stack);
                            if ($_last[0] != $current_tag) {
                                if (!$lax) {
                                    return comcode_parse_error($preparse_mode, array('CCP_NO_CLOSE_MATCH', $current_tag, $_last[0]), $pos, $comcode, $check_only);
                                }
                                do {
                                    $embed_output = _do_tags_comcode($_last[0], $_last[1], $tag_output, $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, NULL, NULL, $in_semihtml, $is_all_semihtml);
                                    $in_code_tag = false;
                                    $white_space_area = $_last[3];
                                    $in_separate_parse_section = $_last[4];
                                    $formatting_allowed = $_last[5];
                                    $textual_area = $_last[6];
                                    $tag_output = $_last[2];
                                    $tag_output->attach($embed_output);
                                    $mindless_mode = $_last[7];
                                    $comcode_dangerous = $_last[8];
                                    $comcode_dangerous_html = $_last[9];
                                    if (count($tag_stack) == 0) {
                                        $status = CCP_NO_MANS_LAND;
                                        break 2;
                                    }
                                    $_last = array_pop($tag_stack);
                                } while ($_last[0] != $current_tag);
                            }
                        } else {
                            $extraneous_semihtml = !$is_all_semihtml && !$in_semihtml || $current_tag != 'html' && $current_tag != 'semihtml';
                            if (!$lax && $extraneous_semihtml) {
                                $_last = array_pop($tag_stack);
                                return comcode_parse_error($preparse_mode, array('CCP_NO_CLOSE_MATCH', $current_tag, $_last[0]), $pos, $comcode, $check_only);
                            }
                            $status = CCP_NO_MANS_LAND;
                            break;
                        }
                        // Do the comcode for this tag
                        if ($in_semihtml) {
                            foreach ($_last[1] as $index => $conv) {
                                $_last[1][$index] = @html_entity_decode(str_replace('<br />', chr(10), $conv), ENT_QUOTES, get_charset());
                            }
                        }
                        $mindless_mode = $_last[7];
                        if ($mindless_mode) {
                            $embed_output = $tag_output;
                        } elseif (!$check_only) {
                            $_structure_sweep = false;
                            if ($structure_sweep) {
                                $_structure_sweep = !in_tag_stack($tag_stack, array('title'));
                            }
                            $embed_output = _do_tags_comcode($_last[0], $_last[1], $tag_output, $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $_structure_sweep, $semiparse_mode, $highlight_bits, NULL, $in_semihtml, $is_all_semihtml);
                        } else {
                            $embed_output = new ocp_tempcode();
                        }
                        $in_code_tag = false;
                        $white_space_area = $_last[3];
                        $in_separate_parse_section = $_last[4];
                        $formatting_allowed = $_last[5];
                        $textual_area = $_last[6];
                        $tag_output = $_last[2];
                        $comcode_dangerous = $_last[8];
                        $comcode_dangerous_html = $_last[9];
                        if ($print_mode && $_last[0] == 'exp_thumb') {
                            $queued_tempcode->attach($embed_output);
                        } else {
                            $tag_output->attach($embed_output);
                        }
                        $just_ended = isset($BLOCK_TAGS[$current_tag]);
                        if ($current_tag == 'title') {
                            if (strlen($comcode) > $pos + 1 && $comcode[$pos] == chr(10) && $comcode[$pos + 1] == chr(10)) {
                                $NUM_LINES += 2;
                                $pos += 2;
                                $just_new_line = true;
                            }
                        }
                        if ($current_tag == 'html') {
                            $in_html = false;
                        } elseif ($current_tag == 'semihtml') {
                            $in_semihtml = false;
                        }
                        $status = CCP_NO_MANS_LAND;
                    } else {
                        if ($current_tag == 'title') {
                            $just_new_line = false;
                            list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                            if ($GLOBALS['XSS_DETECT']) {
                                ocp_mark_as_escaped($close_list);
                            }
                            $tag_output->attach($close_list);
                        }
                        array_push($tag_stack, array($current_tag, $attribute_map, $tag_output, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area, $mindless_mode, $comcode_dangerous, $comcode_dangerous_html));
                        list($tag_output, $comcode_dangerous, $comcode_dangerous_html, $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag($mindless_mode, $as_admin, $source_member, $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                        if ($in_code_tag) {
                            $code_nest_stack = 0;
                        }
                    }
                    $tag_output->attach($tag_raw);
                    if ($close && $mindless_mode) {
                        $temp_tpl = '</kbd>&#8203;';
                        if ($GLOBALS['XSS_DETECT']) {
                            ocp_mark_as_escaped($temp_tpl);
                        }
                        $tag_output->attach($temp_tpl);
                    }
                } elseif ($status == CCP_IN_TAG_NAME) {
                    $current_tag .= strtolower($next);
                }
                break;
            case CCP_STARTING_TAG:
                if ($mindless_mode && $next != '[') {
                    $tag_raw .= $next;
                }
                if ($next == '[') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_OPEN_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    $status = CCP_NO_MANS_LAND;
                    $pos--;
                } elseif ($next == ']') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_CLOSE_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    $status = CCP_NO_MANS_LAND;
                } elseif ($next == '/') {
                    $close = true;
                } else {
                    $current_tag .= strtolower($next);
                    $status = CCP_IN_TAG_NAME;
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTES:
                if ($mindless_mode && $next != '[') {
                    $tag_raw .= $next;
                }
                if ($next == ']') {
                    if ($current_tag == 'title') {
                        $just_new_line = false;
                        list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                        if ($GLOBALS['XSS_DETECT']) {
                            ocp_mark_as_escaped($close_list);
                        }
                        $tag_output->attach($close_list);
                    }
                    array_push($tag_stack, array($current_tag, $attribute_map, $tag_output, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area, $mindless_mode, $comcode_dangerous, $comcode_dangerous_html));
                    list($tag_output, $comcode_dangerous, $comcode_dangerous_html, $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag($mindless_mode, $as_admin, $source_member, $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    if ($in_code_tag) {
                        $code_nest_stack = 0;
                    }
                    $tag_output->attach($tag_raw);
                } elseif ($next == '[') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_OPEN_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    if ($current_tag == 'title') {
                        $just_new_line = false;
                        list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                        if ($GLOBALS['XSS_DETECT']) {
                            ocp_mark_as_escaped($close_list);
                        }
                        $tag_output->attach($close_list);
                    }
                    array_push($tag_stack, array($current_tag, $attribute_map, $tag_output, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area, $mindless_mode, $comcode_dangerous, $comcode_dangerous_html));
                    list($tag_output, $comcode_dangerous, $comcode_dangerous_html, $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag($mindless_mode, $as_admin, $source_member, $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    if ($in_code_tag) {
                        $code_nest_stack = 0;
                    }
                    $tag_output->attach($tag_raw);
                    $pos--;
                } elseif (trim($next) != '') {
                    $status = CCP_IN_TAG_ATTRIBUTE_NAME;
                    $current_attribute_name = $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_NAME:
                if ($mindless_mode && $next != '[') {
                    $tag_raw .= $next;
                }
                if ($next == '[') {
                    $status = CCP_NO_MANS_LAND;
                    $pos--;
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_OPEN_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    if ($current_tag == 'title') {
                        $just_new_line = false;
                        list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
                        if ($GLOBALS['XSS_DETECT']) {
                            ocp_mark_as_escaped($close_list);
                        }
                        $tag_output->attach($close_list);
                    }
                    array_push($tag_stack, array($current_tag, $attribute_map, $tag_output, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area, $mindless_mode, $comcode_dangerous, $comcode_dangerous_html));
                    list($tag_output, $comcode_dangerous, $comcode_dangerous_html, $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag($mindless_mode, $as_admin, $source_member, $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    if ($in_code_tag) {
                        $code_nest_stack = 0;
                    }
                    $tag_output->attach($tag_raw);
                } elseif ($next == ']') {
                    if ($attribute_map == array() && !$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_CLOSE_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    if ($attribute_map != array()) {
                        $at_map_keys = array_keys($attribute_map);
                        $old_attribute_name = $at_map_keys[count($at_map_keys) - 1];
                        $attribute_map[$old_attribute_name] .= ' ' . $current_attribute_name;
                    }
                    array_push($tag_stack, array($current_tag, $attribute_map, $tag_output, $white_space_area, $in_separate_parse_section, $formatting_allowed, $textual_area, $mindless_mode, $comcode_dangerous, $comcode_dangerous_html));
                    list($tag_output, $comcode_dangerous, $comcode_dangerous_html, $white_space_area, $formatting_allowed, $in_separate_parse_section, $textual_area, $attribute_map, $status, $in_html, $in_semihtml, $pos, $in_code_tag) = _opened_tag($mindless_mode, $as_admin, $source_member, $attribute_map, $current_tag, $pos, $comcode_dangerous, $comcode_dangerous_html, $in_separate_parse_section, $in_html, $in_semihtml, $close, $len, $comcode);
                    if ($in_code_tag) {
                        $code_nest_stack = 0;
                    }
                    $tag_output->attach($tag_raw);
                } elseif ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                } elseif ($next != ' ') {
                    $current_attribute_name .= strtolower($next);
                } else {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_LEFT;
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_LEFT:
                if ($mindless_mode && $next != '[' && $next != ']') {
                    $tag_raw .= $next;
                }
                if ($next == '=') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT;
                } elseif (trim($next) != '') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_ATTRIBUTE_ERROR', $current_attribute_name, $current_tag), $pos, $comcode, $check_only);
                    }
                    if ($next == '[') {
                        $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                        $pos--;
                    } elseif ($next == ']') {
                        $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                        $pos--;
                    }
                }
                break;
            case CCP_IN_TAG_BETWEEN_ATTRIBUTE_NAME_VALUE_RIGHT:
                if ($mindless_mode && $next != '[' && $next != ']') {
                    $tag_raw .= $next;
                }
                if ($next == '[') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_OPEN_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    $pos--;
                } elseif ($next == ']') {
                    if (!$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_TAG_CLOSE_ANOMALY'), $pos, $comcode, $check_only);
                    }
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    $pos--;
                } elseif ($next == '"' || $in_semihtml && substr($comcode, $pos - 1, 6) == '&quot;') {
                    if ($next != '"') {
                        $pos += 5;
                        if ($mindless_mode) {
                            $tag_raw .= 'quot;';
                        }
                    }
                    $status = CCP_IN_TAG_ATTRIBUTE_VALUE;
                    $current_attribute_value = '';
                } elseif ($next != '') {
                    $status = CCP_IN_TAG_ATTRIBUTE_VALUE_NO_QUOTE;
                    $current_attribute_value = $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_VALUE_NO_QUOTE:
                if ($mindless_mode && $next != ']') {
                    $tag_raw .= $next;
                }
                if ($next == ' ') {
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    if (isset($attribute_map[$current_attribute_name]) && !$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_DUPLICATE_ATTRIBUTES', $current_attribute_name, $current_tag), $pos, $comcode, $check_only);
                    }
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                } elseif ($next == ']') {
                    if (isset($attribute_map[$current_attribute_name]) && !$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_DUPLICATE_ATTRIBUTES', $current_attribute_name, $current_tag), $pos, $comcode, $check_only);
                    }
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                    $pos--;
                } else {
                    $current_attribute_value .= $next;
                }
                break;
            case CCP_IN_TAG_ATTRIBUTE_VALUE:
                if ($mindless_mode) {
                    $tag_raw .= $next;
                }
                if ($next == '"' || $in_semihtml && substr($comcode, $pos - 1, 6) == '&quot;') {
                    if ($next != '"') {
                        $pos += 5;
                        if ($mindless_mode) {
                            $tag_raw .= 'quot;';
                        }
                    }
                    $status = CCP_IN_TAG_BETWEEN_ATTRIBUTES;
                    if (isset($attribute_map[$current_attribute_name]) && !$lax) {
                        return comcode_parse_error($preparse_mode, array('CCP_DUPLICATE_ATTRIBUTES', $current_attribute_name, $current_tag), $pos, $comcode, $check_only);
                    }
                    $attribute_map[$current_attribute_name] = $current_attribute_value;
                } else {
                    if ($next == '\\') {
                        if ($comcode[$pos] == '"') {
                            if ($mindless_mode) {
                                $tag_raw .= '&quot;';
                            }
                            $current_attribute_value .= '"';
                            ++$pos;
                        } elseif (substr($comcode, $pos - 1, 6) == '&quot;') {
                            if ($mindless_mode) {
                                $tag_raw .= '&quot;';
                            }
                            $current_attribute_value .= '&quot;';
                            $pos += 6;
                        } elseif ($comcode[$pos] == '\\') {
                            if ($mindless_mode) {
                                $tag_raw .= '\\';
                            }
                            $current_attribute_value .= '\\';
                            ++$pos;
                        } else {
                            $current_attribute_value .= $next;
                        }
                    } else {
                        $current_attribute_value .= $next;
                    }
                }
                break;
        }
    }
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($continuation);
    }
    $tag_output->attach($continuation);
    $continuation = '';
    list($close_list, $list_indent) = _close_open_lists($list_indent, $list_type);
    if ($GLOBALS['XSS_DETECT']) {
        ocp_mark_as_escaped($close_list);
    }
    $tag_output->attach($close_list);
    if ($status != CCP_NO_MANS_LAND || count($tag_stack) != 0) {
        if (!$lax) {
            $stack_top = array_pop($tag_stack);
            return comcode_parse_error($preparse_mode, array('CCP_BROKEN_END', is_null($stack_top) ? $current_tag : $stack_top[0]), $pos, $comcode, $check_only);
        } else {
            while (count($tag_stack) > 0) {
                $_last = array_pop($tag_stack);
                /*if ($_last[0]=='title') Not sure about this
                		{
                			$_structure_sweep=false;
                			break;
                		}*/
                $embed_output = _do_tags_comcode($_last[0], $_last[1], $tag_output, $comcode_dangerous, $pass_id, $pos, $source_member, $as_admin, $connection, $comcode, $wml, $structure_sweep, $semiparse_mode, NULL, NULL, $in_semihtml, $is_all_semihtml);
                $in_code_tag = false;
                $white_space_area = $_last[3];
                $in_separate_parse_section = $_last[4];
                $formatting_allowed = $_last[5];
                $textual_area = $_last[6];
                $tag_output = $_last[2];
                $tag_output->attach($embed_output);
                $mindless_mode = $_last[7];
                $comcode_dangerous = $_last[8];
                $comcode_dangerous_html = $_last[9];
            }
        }
    }
    //	$tag_output->left_attach('<div class="xhtml_validator_off">');
    //	$tag_output->attach('</div>');
    return $tag_output;
}